Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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?

like image 936
Inigo Avatar asked Dec 01 '16 10:12

Inigo


1 Answers

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

like image 169
mcklayin Avatar answered Oct 31 '22 17:10

mcklayin