Filtering Eloquent collection data with $collection->filter()

The collection’s filter method calls array_filter on the underlying array, which, according to the PHP docs, preserves the array keys. This then results in your array being converted to a JavaScript object instead of an array. Call values() on your collection to reset the keys on the underlying array: $filtered_collection = $collection->filter(function ($item) { return … Read more

Laravel named route for resource controller

When you use a resource controller route, it automatically generates names for each individual route that it creates. Route::resource() is basically a helper method that then generates individual routes for you, rather than you needing to define each route manually. You can view the route names generated by typing php artisan routes in Laravel 4 … Read more

Laravel mail: pass string instead of view

update on 7/20/2022: For more current versions of Laravel, the setBody() method in the Mail::send() example below has been replaced with the text() or html() methods. update: In Laravel 5 you can use raw instead: Mail::raw(‘Hi, welcome user!’, function ($message) { $message->to(..) ->subject(..); }); This is how you do it: Mail::send([], [], function ($message) { … Read more

Laravel 4: how to run a raw SQL?

In the Laravel 4 manual – it talks about doing raw commands like this: DB::select(DB::raw(‘RENAME TABLE photos TO images’)); edit: I just found this in the Laravel 4 documentation which is probably better: DB::statement(‘drop table users’); Update: In Laravel 4.1 (maybe 4.0 – I’m not sure) – you can also do this for a raw … Read more

How to access model hasMany Relation with where condition?

I think that this is the correct way: class Game extends Eloquent { // many more stuff here // relation without any constraints …works fine public function videos() { return $this->hasMany(‘Video’); } // results in a “problem”, se examples below public function available_videos() { return $this->videos()->where(‘available’,’=’, 1); } } And then you’ll have to $game … Read more

Laravel Eloquent – Attach vs Sync

attach(): Insert related models when working with many-to-many relations No array parameter is expected Example: $user = User::find(1); $user->roles()->attach(1); sync(): Similar to the attach() method, the sync() method is used to attach related models. However, the main differences are: sync() accepts an array of IDs to place on the pivot table Secondly, most important, the … Read more

First Or Create

firstOrCreate() checks for all the arguments to be present before it finds a match. If not all arguments match, then a new instance of the model will be created. If you only want to check on a specific field, then use firstOrCreate([‘field_name’ => ‘value’]) with only one item in the array. This will return the … Read more