Ad

Can't Access Data From Many To Many Relationship

- 1 answer

I have Bus and Route model trying to access route through bus but gets error

Undefined property: stdClass::$route

Controller:

foreach ($Bus as $tBus){

            foreach ($tBus->route as $tBusRoute) {//Undefined property: stdClass::$route
                if($tBusRoute->id == $rId){
                    $BusRouteId = $tBusRoute->pivot->id;            }
            }
            }


Bus Model:

class Bus extends Model
{
    protected $table = 'bus';
    public $primaryKey = 'id';
    public $timestamp = true;


    public function route(){

        return $this->belongsToMany(Route::class , 'bus_route' , 'bus_id' , 'route_id')->withPivot('id');
}

Route Model:

class Route extends Model
{

    protected $table = 'route';
    public $primaryKey = 'id';
    public $timestamp = true;

    public function bus(){

        return $this->belongsToMany(Bus::class , 'bus_route' , 'route_id' , 'bus_id');
    }

Error: Undefined property: stdClass::$route

Ad

Answer

You are using Query Builder directly and not going through Eloquent to do your query.

To use the model:

$buses = Bus::where('transport_company_id', $tld)->get();

The Query Builder returns a Collection of stdClass objects, hence your error. If you query through the Model you will get a Collection of Model instances.

Laravel 6.0 Docs - Eloquent - Retrieving Models

Ad
source: stackoverflow.com
Ad