query to get only one item from target column in Laravel - laravel

Is there any query to get only one item from target column? below didn't working?
App\Job::whereNotNull('deleted_at')->pluck('customer_name')->first()
I wish to get just one item name from 'customer_name'
Now Laravel 5.6 using...

When using eloquent, using first will give you a single item, the first record matching your query. You can then access the property on that item:
// This will give you an instance of App\Job (or null)
$job = App\Job::whereNotNull('deleted_at')->first();
// You can then access the customer_name property on the object
$job->customer_name;
If you only want to retrieve that single column when you run your query, you can pass an array of columns to first.
App\Job::whereNotNull('deleted_at')->first(['customer_name']);
Assuming you're using the SoftDeletes trait in your model, your query will automatically have an additional check added to all of your queries to ensure that deleted_at is null. So when you're doing ->whereNotNull('deleted_at') you're adding an additional clause to ensure records are not null as well, so you won't have any records being returned.
If you want to look only at deleted records, you can use onlyTrashed():
App\Job::onlyTrashed()->first();

There is a built-in method for this: value('field')
App\Job::whereNotNull('deleted_at')->value('customer_name');
Docs: https://laravel.com/docs/5.6/queries, look for "Retrieving A Single Row / Column From A Table"
If you meant only one field but still as rows, you can use ->select('field') instead.
And since you want only trashed items, you can use ->onlyTrashed() instead of the not null check.
Soft deleting documentation: https://laravel.com/docs/5.6/eloquent#deleting-models

Try like this:
$job = \App\Job::selectRaw('customer_name')
->whereNotNull('deleted_at')
->first();
And use it like $job->customer_name

Related

Laravel eloquent not retrieving results based on boolean column

I have 33 results on my DB where this boolean field (resolvido) is showing zero, if I run the SQL query it retrieves the results, however in the model the collection always comes empty.
If I change to Model::where('resolvido',1)->get(), I do get the correspondent results, however the Model::where('resolvido',0)->get() or the Model::where('resolvido',false)->get() or even using the query builder and raw sql, the collection never picks up those 33 results where resolvido = 0.
I've also tried in Tinker and it always comes up empty.
Migration:
$table->boolean('resolvido')->nullable();
On DB comes up as TINYINT
Any tips on what it might be?
Thanks in advance
Naturally, there is no boolean data type for MySQL but rather uses TINYINT (0 or 1) for this.
Laravel's query builder, allows using boolean in the where clause. You might want to try these:
Model::where('resolved', true)->get();
Model::where('resolved', false)->get();
Since you've set the resolved column in the DB as nullable, you might also want to try:
Model::where('resolved', null)->get();
If you don't want that behavior use $table->boolean('resolved')->default(false) instead
Try this
Model::where('resolved', null)->get()
or
Model::where('resolved', '')->get()

Get unique value from table Laravel

I want to get all rows that have one unique column. The problem with my code is that it works only when I select just that one column, but in the end I need to have multiple columns.
$values= Model::select('id','value_first','gender_first','value_second','gender_second')->groupBy('value_first')->get();
Here is Solution of Your Problem
$values= Model::select('id','value_first','gender_first','value_second','gender_second')->distinct('value_first')->get();
As per Laravel Documentation you can use distinct method for the same
The distinct method allows you to force the query to return distinct
results for e.g
$values= Model::select('id','value_first','gender_first','value_second','gender_second')->distinct('value_first')->get();
Reference: Laravel-> Database: Query Builder -> Selects

laravel the best way to check the contents of a variable

I have a few questions, the first one is:
What is the best way to check if the variable has any records from the database. e.g when I want get single row from collection:
$variable->sth->first()->url
I get reply:
Call to a member function first() on null.
So if I will use something like this:
#if($variable->sth->count() > 0)
code here
#endif
is this correct ? and what's the difference between
#if($variable->sth->count() > 0) and #if(count($variable->sth)>0 #endif because both work, but not always
second question is: Why when I want get one row from collection and when collection is empty an error appears? but when I use foreach to get all rows from db and when collection whether row is empty, nothing is not appears.
the third question is: when should I check that, the returned data isn't empty?
I'am newbie, sorry.
What is the best way to check if the variable has any records from the database.
You can use laravel methods like dd() or use var_dump() to see the content of a variable.
I get reply: Call to a member function first() on null.
That happens because property sth in $variable is null so it doesn't contains a function or member called first()
Why when I want get one row from collection and when collection is empty an error appears? but when I use foreach to get all rows from db and when collection whether row is empty, nothing is not appears.
Foreach evaluates first if there is data on the collection before doing whatever. You are getting an error because you are accessing a row that maybe doesn't exist. You need to evaluate first if the collection is null or not before accessing its data
when should I check that, the returned data isn't empty?
Before attempting to use it

How to stop Doctrine from returning a primary key for every query

I am kind of annoyed at Doctrine for returning primary keys in each and every query even though I don't want it to. Is there anyway to stop this ? coz I don't really want those damn primary keys along with my doctrine query results.
A query for instance that I have is:
$getAllDatesForUserQuery = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_ARRAY) ;
In this situation, it retrieves all the datenames as it should, but also happily returns the primary key column value. I DON"T WANT IT.
Is it me? or is it Doctrine ?
In a case like this where you want a simple array and only have a single field being selected, the answer is the Single Scalar Hydration mode. Use it like this:
$q = $this->createQuery('s')
->select('s.datename')
->where('s.userid = ?',3)
->setHydrationMode(Doctrine::HYDRATE_SINGLE_SCALAR);
You should find that the query will return a simple one-dimensional array containing only the value(s) you wanted.

Yii ActiveRecord Primary Key retrieval

I have looked around and have not found anything similar to what I am asking.
Short of extending the CActiveRecord class is there a way to query just the primary key values (or any column's values) of a table and have an array of those values returned instead of a collection of activerecord objects?
ie
ModelName::model()->getColumnValues('column_name');
I keep having to get a list of record that match a certain condition and then run through the results to pull out the column values I need. I would like to cut out the last step and just get the values instead of the entire record.
Any ideas?
Using a CDbCommand you can execute a query and fetch the results from one column with the queryColumn method. queryColumn returns the results from the first column.
Example:
$command = Yii::app()->db->createCommand("SELECT column FROM table WHERE ...");
$result = $command->queryColumn();

Resources