Inigo
Inigo

Reputation: 8685

Laravel 5 Eloquent relationship: can't modify/overwrite relationship table property

I am using Laravel 5's belongsToMany method to define related tables using an intermediary pivot table. My application is using the eloquent models Tour and TourCategory. In the Tour Model I have:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Tour extends Model
{
    public function cats(){
        return $this->belongsToMany('App\TourCategory', 'tour_cat_assignments', 'tour_id', 'cat_id');
    }

}

In my controller I am retrieving all the data from the tour table along with the associated category data using Laravel's with method:

$tours = Tour::with('cats')->get();

That all works fine. The problem is that I don't want the category data in its current raw form, I need to first rearrange it. However I cannot overwrite the cats property without unsetting it first:

public function serveTourData(){

    $tours = Tour::with('sections', 'cats')->get();

    foreach($tours as $tour){

        unset($tour->cats); // If I unset first, then it respects the new value. Why do I need to do this?

        $tour->cats = "SOME NEW VALUE";
    }

    Log::info($tours);
}

Can someone explain the logic behind this please?

Upvotes: 8

Views: 3566

Answers (1)

mcklayin
mcklayin

Reputation: 1360

To override relations on some model, you can use:

public function serveTourData(){

$tours = Tour::with('sections', 'cats')->get();

foreach($tours as $tour){
    $tour->setRelation('cats', "SOME NEW VALUE");
}

Log::info($tours);

}

For laravel 5.4 - setRelation

Of course if you are using laravel >= 5.6, you can unset relations by unsetRelation

Upvotes: 13

Related Questions