phplaraveleloquentmany-to-manyrelationships

Laravel whereHas on Many-to-Many relationships


I have two main tables with relationships many to many and a pivot table.

Model 'Type'

    public function attributes()
    {
        return $this->belongsToMany('App\Attribute', 'attribute_type');
    }

Model 'Attribute'

    public function types()
    {
        return $this->belongsToMany('App\Type', 'attribute_type');
    }

Pivot table 'attribute_type'

    Schema::create('attribute_type', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('type_id')->unsigned();
        $table->foreign('type_id')->references('id')->on('types');
        $table->integer('attribute_id')->unsigned();
        $table->foreign('attribute_id')->references('id')->on('attributes');
    });

I want to show 5 attributes in random order which belong to the types of id < 10.

$attributes = Attribute::whereHas('types', function ($query) {
            $query->where('id', '<', '10');
        })->orderByRaw("RAND()")->limit(5);

and for example

$attribute->id

gives me "Undefined property: Illuminate\Database\Eloquent\Builder::$id"


Solution

  • All you have to do is execute query and get the collection with get() method like this:

    $attributes = Attribute::whereHas('types', function ($query) {
            $query->where('id', '<', '10');
        })->orderByRaw("RAND()")->limit(5)
        ->get();
    

    Now you are trying to iterate over the query builder which is giving you another query builder as a result of $attribute