What is the meaning of Eloquent’s Model::query()?

Any time you’re querying a Model in Eloquent, you’re using the Eloquent Query Builder. Eloquent models pass calls to the query builder using magic methods (__call, __callStatic). Model::query() returns an instance of this query builder. Therefore, since where() and other query calls are passed to the query builder: Model::where()->get(); Is the same as: Model::query()->where()->get(); Where … Read more

A JOIN With Additional Conditions Using Query Builder or Eloquent

$results = DB::table(‘rooms’) ->distinct() ->leftJoin(‘bookings’, function($join) { $join->on(‘rooms.id’, ‘=’, ‘bookings.room_type_id’); $join->on(‘arrival’,’>=’,DB::raw(“‘2012-05-01′”)); $join->on(‘arrival’,'<=’,DB::raw(“‘2012-05-10′”)); $join->on(‘departure’,’>=’,DB::raw(“‘2012-05-01′”)); $join->on(‘departure’,'<=’,DB::raw(“‘2012-05-10′”)); }) ->where(‘bookings.room_type_id’, ‘=’, NULL) ->get(); Not quite sure if the between clause can be added to the join in laravel. Notes: DB::raw() instructs Laravel not to put back quotes. By passing a closure to join methods you can add more join … Read more

Get the Query Executed in Laravel 3/4

Laravel 4+ Note for Laravel 5 users: You’ll need to call DB::enableQueryLog() before executing the query. Either just above the line that runs the query or inside a middleware. In Laravel 4 and later, you have to call DB::getQueryLog() to get all ran queries. $queries = DB::getQueryLog(); $last_query = end($queries); Or you can download a … Read more

Get Specific Columns Using “With()” Function in Laravel Eloquent

Well I found the solution. It can be done one by passing a closure function in with() as second index of array like Post::query() ->with([‘user’ => function ($query) { $query->select(‘id’, ‘username’); }]) ->get() It will only select id and username from other table. I hope this will help others. Remember that the primary key (id … Read more

How to Create Multiple Where Clause Query Using Laravel Eloquent?

In Laravel 5.3 (and still true as of 7.x) you can use more granular wheres passed as an array: $query->where([ [‘column_1’, ‘=’, ‘value_1’], [‘column_2’, ‘<>’, ‘value_2′], [COLUMN, OPERATOR, VALUE], … ]) Personally I haven’t found use-case for this over just multiple where calls, but fact is you can use it. Since June 2014 you can … Read more

How do I get the query builder to output its raw SQL query as a string?

Use the toSql() method on a QueryBuilder instance. DB::table(‘users’)->toSql() would return: select * from `users` This is easier than wiring up an event listener, and also lets you check what the query will actually look like at any point while you’re building it. Note: This method works for query builder or Eloquent, however toSql() is … Read more

tech