Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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();

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading