Laravel 5.5 model pivot table count

Published 6 months ago by afoysal

I have 3 tables. users,gallery and gallery_blog.gallery_blog has gallery_id and blog_id.gallery_blog is a pivot table. gallery has user_id and name. users has id.One User has many gallery. One gallery has many blog.

I need a query to know how many blogs in a gallery along with gallery name of current user.

I wrote below query

use App\User as user_gallery;    
$galleries = user_gallery::find(Auth::user()->id)->gallery;

I have below code in User model.

public function gallery() {   
        return $this->hasMany('App\Models\Gallery');  
    }
Dry7
Dry7
6 months ago (151,680 XP)

@afoysal

class Gallery extends Model {
    public function blogs()
    {
        return $this->belongsToMany('App\Models\Blog');
    }
}

and use https://laravel.com/docs/5.5/eloquent-relationships#counting-related-models or just

$gallery->blogs->count()

Please sign in or create an account to participate in this conversation.