PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How to filter entries via hasMany relationship in Laravel

 October 21, 2022     eloquent, has-many, laravel, php     No comments   

Issue

I'm trying write an website with Laravel (current version is 5.7) and I have 3 models as: Post, User and Fav. I'm using a simple form to add posts to "favs" table which has 3 columns as; id, user_id and post_id. And I want to list posts that user added favorites bu I can't use "hasMany" method properly.

I can use variables like; $post->user->name but I can't figure it out how to use relationship with "favs" table.

Post Model

public function user() {
    return $this->belongsTo('App\User');
}

public function favs() {
    return $this->hasMany('App\Fav');
}

Fav Model

public function users() {
    return $this->hasMany('App\User');
}
public function posts() {
    return $this->hasMany('App\Post', 'post_id', 'id');
}

User Model

public function posts() {
    return $this->hasMany('App\Post');
}

public function favs() {
    return $this->hasMany('App\Fav');
}

Controller

public function user($id){

    $favs = Fav::orderBy('post_id', 'desc')->get();
    $user = User::find($id);
    $posts = Post::orderBy('id', 'desc')->where('user_id', $id)->where('status', '4')->paginate(10);
    return view('front.user')->with('user', $user)->with('posts', $posts)->with('favs', $favs);
}

Solution

The Fav model only has one User and Post each, so you need to use belongsTo() instead of hasMany and change the method names to singular. You can also remove the additional parameters in post() since they're the default values.

public function user() {
    return $this->belongsTo('App\User');
}
public function post() {
    return $this->belongsTo('App\Post');
}

Loading all Posts that a user has favorited:

$user->favs()->with('post')->get();

The with() method is used to eager load the relationship.

Now you can loop through the Favs:

@foreach($favs as $fav)
{{ $fav->post->name }}
@endforeach


Answered By - Thomas
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing