Search code examples
laraveleloquentlaravel-livewire

Get specific data from another table using foreign key in Laravel Livewire


I a new Livewire user and I want to fetch a specific name from the User table using the foreign key of the user in my Blog table. I'm unsure of how to put code in the render() and Blade template. I've seen something like this: {{ blogs->id->name }}. How can I come up with a solution?

User table

Schema::create('users', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email')->unique();
    $table->timestamp('email_verified_at')->nullable();
    $table->string('password');
    $table->rememberToken();
    $table->timestamps();
});

Blog table

Schema::create('blogs', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
    $table->string('title');
    $table->text('heading')->nullable();
    $table->text('paragraph');
    $table->text('featured_img');
    $table->timestamps();
});

in User model declared

public function blogs() 
{
    return $this->hasMany(Blogs::class);
}

in Blog model declared

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

render() method in Blogs class

public function render()
{
    $blogs = Blogs::where('user_id', Auth::id())->orderBy('created_at', 'desc')->paginate(3);
    $user = User::where('id', Auth::id())->get();

    return view('livewire.admin.blogs', [
        'blogs' => $blogs,
        'user' => $user
    ])->layout('layouts.admin');
}

Solution

  • It looks like you already know the user and want to return all the blog posts for that specific user? If that is the case you can do the following with the relationships you have defined. I'm also presuming you want the blog posts of the logged in user.

    public function render()
    {
        return view('livewire.admin.blogs', [
            // No need to add the posts here, get them from the user model
            'user' => auth()->user(),
        ])->layout('layouts.admin');
    }
    

    Then inside your blade to loop over the blog posts for the user:

    <p>The blog posts for {{ $user->name }}</p>
    @foreach ($user->blogs()->paginate(3) as $post)
    <h1>{{ $post->title }}</h1>
    <p>{{ $post->heading }}</p>
    @endforeach
    

    Update to fetch user

    If you want to fetch the user for a specific blog post you can then use the user relationship on the blog model itself.

    // From the Blog model access the User relationship and return 
    // the `name` for the specific user who created the blog post.
    $post->user->name