Laravel join query with conditions

I’m still not completely sure about your table relationships but from my guess, I came up with the following solution, first create the relationships using Eloquent models: User Model (for usres table): namespace App; use App\Course; use Illuminate\Notifications\Notifiable; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { use Notifiable; public function courses() { return $this->hasMany(Course::class); … 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

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