phplaraveleloquentlistings

Display user name from another table Laravel 8


Hellow guys, so I have 2 tables

  1. is Listings
  2. is Users

in Listings I have some columns, one is user_id, and is related to users tables. I want to display the user name related to the user table. in the index blade, I use some tags. But when I use ->rightjoin("users", "users.id", "=", "listings.user_id") it's works but, the join broke my tags make them default, same with others posts.

 public function index(Request $request)
    {
        $listings = Listing::where('is_active', true)->with('tags') 
            //->rightjoin("users", "users.id", "=", "listings.user_id") //don't show tags of the posts
            ->orderBy('listings.created_at', 'desc')
            ->get();
                //check if posts ar listing by last date or something
$tags = Tag::orderBy('name') // variable displayed in view
            ->get();

Solution

  • You could just use the with method to get the related user like this

    public function index(Request $request) {
            $listings = Listing::where('is_active', true)->with(['user', 'tags']) 
                ->orderBy('listings.created_at', 'desc')
                ->get();
    }
    

    but make sure that you add to your Listing model the correct relation like this

    Listing Model

    
    public function user() {
       return $this->belongsTo(User::class);
    }