gileneusz
gileneusz

Reputation: 1485

Laravel eloquent not getting many-to-many related table

I've got OffersConntroller and I try to fetch all offers with specialities from other table (which is many-to-many relationship - working correctly)

Offer model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;



class Offer extends Model
{
    protected $fillable = [
        'title', 'body'
    ];

    public function specialities()
    {
        return $this->belongsToMany('App\Speciality');
    }
}

Speciality model

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Speciality extends Model
{
    // protected $table = 'specialities';

    protected $casts = [
        'speciality_id'=>'string'
    ];

    public function offers()
    {
        return $this->belongsToMany('App\Offer');
    }
}

specialities table has name, id, offer_speciality table has offer_id, speciality_id

I'm trying to get name so in OffersController:

public function index()
{
    return Offer::orderBy('created_at','desc')->with('specialities:name')->get();
}

And I got empty array "speciality" within correct the array of fetched offers

Upvotes: 1

Views: 33

Answers (1)

user320487
user320487

Reputation:

Change the order of the methods around:

Orders::with('specialities')->orderBy('created_at','desc')->get();

Upvotes: 3

Related Questions