Anji
Anji

Reputation: 111

How to fetch data along with relationship data in Laravel using with keyword?

How can I fetch data along with blog category and blog tags from Blogs table using with in query.

Below is my model and controller code, I am getting Get Blogs Api Error instead of the blogs data.

Blog Controller

public function getBlogs()
{
    try {
        $blogs = Blog::where('status', 1)
            ->with('category')
            ->with('tag')
            ->with('user')
            ->with('comment')
            ->orderBy('id', 'desc')
            ->paginate(5);
        return response()->json($blogs);
    } catch (\Illuminate\Database\QueryException $e) {
        $e = "Get Blogs Api Error";
        return response()->json($e);
    }
}

Blog Model

class Blog extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
    public function category()
    {
        return $this->hasMany(Category::class);
    }
    public function tag()
    {
        return $this->hasMany(Tag::class);
    }
    public function comment()
    {
        return $this->hasMany(Comment::class);
    }
}

User Model

public function blog_user()
{
    return $this->hasMany(Blog::class);
}

Blog Category Model

public function blog_category()
{
    return $this->belongsTo(Blog::class);
}

Blog Tag Model

public function blog_tag()
{
    return $this->belongsTo(Blog::class);
}

Blog Comment Model

public function blog_comment()
{
    return $this->belongsTo(Blog::class);
}

Database table structure

blogs table structure

Blogs table structure

blog_categories table structure

Blog Category

blog_tags table structure

Blog Tags

Upvotes: 3

Views: 1311

Answers (1)

rameezmeans
rameezmeans

Reputation: 850

First of all change names to plural. not singular. as you are using one to many. and use belongsToMany() method. not hasMany().

public function categories(){
    return $this->belongsToMany(Category::class);
}

and change the name of pivot table to blog_category not blog_categories. It will work. and your BlogCategory model will look like this.

class BlogCategory extends Model {
    protected $table = 'blog_category';

    public function blog() {
        return $this->belongsTo( Blog::class );
    }
}

now you can get blogs like this.

$blogs = Blog::with( 'categories' )->get();

and this is how you will fetch blog for any category.

$category = BlogCategory::where( 'category_id', $category->id )->first();

dd( $category->blog );

Upvotes: 2

Related Questions