Alan
Alan

Reputation: 116

Laravel/Eloquent belongsToMany returning all records

Mostly a beginner of Eloquent here. I have got a working many to many relationship between two models: Venue and Category.

Venue.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Venue extends Model
{
    public function categories()
    {
        return $this->belongsToMany('App\Models\Category');
    }
}

Category.php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function venues()
    {
        return $this->belongsToMany('App\Models\Venue');
    }
}

I need to return a JSON object containing the venue and the related categories as a sub-property. However, using $venue->with('categories') returns a Builder object – which can't be converted to JSON – and using $venue->with('categories')->get() returns me a huge object containing all the venues (or so I think they are) in the DB.

What's the correct way to do this?


Edit 03/27/2017: After accepting the answer below, I'm still curious why eloquent returns that huge array of Venue objects. If somebody knows, please leave an answer anyway!

Upvotes: 2

Views: 1804

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163898

Use the first() method:

$venue = Venue::where('name', $name)->with('categories')->first();

If $venue is already has specific venue, use the load() method to lazy eager load related data:

$venue->load('categories');

Upvotes: 1

Related Questions