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

Automatically deleting related rows in Laravel (Eloquent ORM)

I believe this is a perfect use-case for Eloquent events (http://laravel.com/docs/eloquent#model-events). You can use the “deleting” event to do the cleanup: class User extends Eloquent { public function photos() { return $this->has_many(‘Photo’); } // this is a recommended way to declare event handlers public static function boot() { parent::boot(); static::deleting(function($user) { // before delete() method … 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

Property Property Property [title] does not exist on this collection instance does not exist on this collection instance does not exist on this collection instance

When you’re using get() you get a collection. In this case you need to iterate over it to get properties: @foreach ($collection as $object) {{ $object->title }} @endforeach Or you could just get one of objects by it’s index: {{ $collection[0]->title }} Or get first object from collection: {{ $collection->first() }} When you’re using find() … Read more