Laravel where statement - laravel

I am new in Laravel. I want to create a search filter using eloquent model.
I want to check some columns are equal to some enteries and return the results, but the problem is that if any of the enteries is empty it returns nothing.
How to make it to search if other enteries matche and return values even one of the entery is empty.
$result = person::Where('age','>=',$age)
->Where('hairColor','=',$hairColor)
->Where('height','>=',$height)
->get();

Just use orWhere
$result = person::Where('age','>=',$age)
->orWhere('hairColor','=',$hairColor)
->orWhere('height','>=',$height)
->get();
Also, check this documentation
Laravel where clauses

Related

Laravel query use parent column inside whereRelation

I have problem with my eloquent query, i need to use data of my base model into whereRelation.
I tried this query bottom, but results was not what i except. The query return me all users who have one city relation, not only user who have city updated between my last user sync.
$users = People::whereRaw('TIMESTAMPDIFF(SECOND, people.latest_sync, people.updated_at) > 20')
->orWhereRelation('city', 'updated_at', '>', 'people.updated_at')
->get();
I'v tried people.updated_at and latest_sync in value of my Where Relation
Do i need to make pure SQL Raw query with classic join ?
PS: the first whereRaw is ok, and work (i really need)

I want to extract the first five data that match the where clause from Laravel relationships

I'd like to do something like this with Laravel's Eloquent:relationship, but it doesn't work.
$playlist->setRelation('tags', $playlist->tags->where('privacySetting', 'public')->take(5));
It works without where clause, but I want to retrieve the first 5 data in the tags relationship table that match the where clause.
How can I do this?
Laravel version is 7.28.1.
this will select top 5 based on criteria from model
$playlist = Playlist::with(['tags' => function($filter){
return $filter->where('privacySetting', 'public')
->take(5);
}])
->get();
//try dd($playlist);

laravel query builder remove where clause

I have whereIn in Query Builder (Laravel 5.6)
$data->whereIn('field1', [1,2,3])->whereIn('field2', [4,5,6])->whereIn('field3', [8,9,10]);
....
$some_count = clone $data;
$result = $data->get();
$count_result = $some_count->count(); <-- need without one of whereIn
And now, I need to do count() without one of whereIn, for example "whereIn('field2', [4,5,6])". How to remove this clause from $some_count?

Laravel Collection Filter By Multiple Concatenated Unique Fields

I have a model download which has two three properties. Those properties are 'id' , 'user_id' , 'file_id'.
Whenever a user downloads a file a download record is created.
I want to grab all downloads that have both a unique file_id and unique user_id.
How is this accomplished.
A collection might come from a relationship and needs filtering afterward. Below is a tested working solution in laravel 5.7 and most probably in later versions also:
$unique = $collection->unique(function ($item)
{
return $item['brand'] . $item['model'];
});
Here is an article about this: http://laravel.at.jeffsbox.eu/laravel-5-eloquent-collection-methods-unique
You can use the groupBy method.
$downloads = DB::table('downloads')
->groupBy('file_id')
->groupBy('user_id')
->get();
OR
You can use the distinct method.
$downloads = DB::table('downloads')->distinct()->get();

Laravel Eloquent: Ordering results of all()

I'm stuck on a simple task.
I just need to order results coming from this call
$results = Project::all();
Where Project is a model. I've tried this
$results = Project::all()->orderBy("name");
But it didn't work. Which is the better way to obtain all data from a table and get them ordered?
You can actually do this within the query.
$results = Project::orderBy('name')->get();
This will return all results with the proper order.
You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.
Ascending Order
$results = Project::all()->sortBy("name");
Descending Order
$results = Project::all()->sortByDesc("name");
Check out the documentation about Collections for more details.
https://laravel.com/docs/5.1/collections
In addition, just to buttress the former answers, it could be sorted as well either in descending desc or ascending asc orders by adding either as the second parameter.
$results = Project::orderBy('created_at', 'desc')->get();
DO THIS:
$results = Project::orderBy('name')->get();
Why?
Because it's fast! The ordering is done in the database.
DON'T DO THIS:
$results = Project::all()->sortBy('name');
Why?
Because it's slow. First, the the rows are loaded from the database, then loaded into Laravel's Collection class, and finally, ordered in memory.
2017 update
Laravel 5.4 added orderByDesc() methods to query builder:
$results = Project::orderByDesc('name')->get();
While you need result for date as desc
$results = Project::latest('created_at')->get();
In Laravel Eloquent you have to create like the query below it will get all the data from the DB, your query is not correct:
$results = Project::all()->orderBy("name");
You have to use it in this way:
$results = Project::orderBy('name')->get();
By default, your data is in ascending order, but you can also use orderBy in the following ways:
//---Ascending Order
$results = Project::orderBy('name', 'asc')->get();
//---Descending Order
$results = Project::orderBy('name', 'desc')->get();
Check out the sortBy method for Eloquent: http://laravel.com/docs/eloquent
Note, you can do:
$results = Project::select('name')->orderBy('name')->get();
This generate a query like:
"SELECT name FROM proyect ORDER BY 'name' ASC"
In some apps when the DB is not optimized and the query is more complex, and you need prevent generate a ORDER BY in the finish SQL, you can do:
$result = Project::select('name')->get();
$result = $result->sortBy('name');
$result = $result->values()->all();
Now is php who order the result.
You instruction require call to get, because is it bring the records and orderBy the catalog
$results = Project::orderBy('name')
->get();
Example:
$results = Result::where ('id', '>=', '20')
->orderBy('id', 'desc')
->get();
In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.
Try this:
$categories = Category::all()->sortByDesc("created_at");
One interesting thing is multiple order by:
according to laravel docs:
DB::table('users')
->orderBy('priority', 'desc')
->orderBy('email', 'asc')
->get();
this means laravel will sort result based on priority attribute. when it's done, it will order result with same priority based on email internally.
EDIT:
As #HedayatullahSarwary said, it's recommended to prefer Eloquent over QueryBuilder. off course i didn't encourage using QueryBuilder and we all know that each has own usecases.
Any way so why i wrote an answer with QueryBuilder? As we see in eloquent documents:
You can think of each Eloquent model as a powerful query builder allowing you to fluently query the database table associated with the model.
BTWS the above code with eloquent should be something like this:
Project::orderBy('priority', 'desc')
->orderBy('email', 'asc')
->get();

Resources