Laravel Brackets to Eloquent Query (And Or Conditions)
This article will discuss putting brackets to And Or Conditions of laravel eloquent query. Eloquent is a great tool to interact with database via a model. Basically Laravel Models are Eloquent models and you can perform any kind of query in a simple way but sometimes it gets a little trickier and gives hard time.
If you want to read more about Laravel Eloquent related articles then you can read https://opensourcelisting.com/open-source-laravel-listing/laravel-models/
For example if we want to get projects assigned to based on user id as foreign key and between some timestamp in which the project has been created or updated. so typically we will do like this in the controller as,
$projects = Project::were('user_id', 1)->whereYear('created_at', 2022) -> orWhereYear('updated_at, 2021)->get();
It seems correct query but it will not filter out the user_id field because the order of our query is not correct. If You look the sql version of this query it will look like this,
select * from `projects` where `user_id` = ? and year(`created_at`) = ? or year(`updated_at`) = ?
So there are not brackets to separate the user_id from the timestamp condition and to solve this issue we insert brackets to our query by inserting a call back function to our query like,
$projects = Project::were('user_id', 1)-> where( function($query) { return $query -> whereYear('created_at', 2022) -> orWhereYear('updated_at, 2021); })->get();
This Query will separate the conditions with brackets and we will only get those projects which will assigned to user id 1 and between some timestamp which we given the 2022 or 2021.
Now if want to look at this sql version of this query we will do somethings like this,
$projects = Project::were('user_id', 1)-> where( function($query) { return $query -> whereYear('created_at', 2022) -> orWhereYear('updated_at, 2021); })->toSql();
and it SQL version will be,
select * from `projects` where `user_id` = ? and (year(`created_at`) = ? or year(`updated_at`) = ?)
So Eloquent is a great tool to interact with database but you will have to be cautious sometimes when writing the queries.
Please follow our posts on our website