How to sort by a field of the pivot table of a many-to-many relationship in Eloquent ORM

Not sure if you plan to move to Laravel 4, but here’s an Eloquent example for sorting by a pivot tables fields: public function songs() { return $this ->belongsToMany(‘Song’) ->withPivot(‘play_count’) ->orderBy(‘pivot_play_count’, ‘desc’); } withPivot is like the eloquent with and will add the play_count field from the pivot table to the other keys it already … Read more

Laravel 5.1 Create or Update on Duplicate

As per the Definition of the Eloquent Model Method “updateOrCreate()” function updateOrCreate(array $attributes, array $values = []){} it takes two argument … one is the attributes using which you want to check in database if the record is present second is the new attribute values that you want to create or update AppInfo::updateOrCreate([‘app_id’ => $postData[‘appId’]], … Read more

Laravel adding data to pivot table while inserting new record

It’s really all described in the documentation. Anyway, here’s how you do it: $user = new User(); $user->username = Input::get(‘username’); $user->password = Hash::make(Input::get(‘password’)); $user->save(); $user->roles()->attach($roles); The important part is that you have to save the user before attaching (using attach()) the roles because otherwise the user doesn’t have an id yet to be used in … Read more