Clone an Eloquent object including all relationships?

tested in laravel 4.2 for belongsToMany relationships if you’re in the model: //copy attributes $new = $this->replicate(); //save model before you recreate relations (so it has an id) $new->push(); //reset relations on EXISTING MODEL (this way you can control which ones will be loaded $this->relations = []; //load relations on EXISTING MODEL $this->load(‘relation1′,’relation2’); //re-sync everything … Read more

Laravel Eloquent update just if changes have been made

You’re already doing it! save() will check if something in the model has changed. If it hasn’t it won’t run a db query. Here’s the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate: protected function performUpdate(Builder $query, array $options = []) { $dirty = $this->getDirty(); if (count($dirty) > 0) { // runs update query } return true; … Read more

Laravel 5.3 withCount() nested relation

You can only do a withCount() on a defined relation of the model. However, a relationship can be hasManyThrough which would achieve what you are after. class Tutorial extends Model { function chapters() { return $this->hasMany(‘App\Chapter’); } function videos() { return $this->hasManyThrough(‘App\Video’, ‘App\Chapter’); } } And then you can do: Tutorial::withCount([‘chapters’, ‘videos’]) Docs: https://laravel.com/docs/5.3/eloquent-relationships#has-many-through

Laravel Eloquent – Where In All

You’ll have to add multiple whereHas for that: $query = User::with(‘activities’); foreach($selectedActivities as $activityId){ $query->whereHas(‘activities’, function($q) use ($activityId){ $q->where(‘id’, $activityId); }); } $userByActivities = $query->get();

Laravel Many to many self referencing table only works one way

Instead of creating two records use a new function. public function friends() { return $this->belongsToMany(‘User’, ‘friend_user’, ‘user_id’, ‘friend_id’); } // Same table, self referencing, but change the key order public function theFriends() { return $this->belongsToMany(‘User’, ‘friend_user’, ‘friend_id’, ‘user_id’); } //You can then call opposite record(s) using: foreach( Auth::user()->theFriends as $theFriends ) I used this approach … Read more

How to setup conditional relationship on Eloquent

Lets take a different approach in solving your problem. First lets setup relationship for the various models respectively. class User extends Model { public function agentProfile() { return $this->hasOne(AgentProfile::class); } public function institutionProfile() { return $this->hasOne(InstitutionProfile::class); } public function schoolProfile() { return $this->hasOne(SchoolProfile::class); } public function academyProfile() { return $this->hasOne(AcademyProfile::class); } // create scope to … Read more