首页 > 解决方案 > 如何在 Laravel 中检索和显示 Eloquent 关系

问题描述

我要完成的工作:

检索App\Post与经过身份验证的用户相关的所有模型并在视图中显示它们。


我收到的错误:

Undefined variable:以及Property [id] does not exist on this collection instance点击<a name="posts">标签时。


我一直在尝试的:

页面控制器

 public function show($id) {
    $user = User::find($id);
    return view('pages.index', compact('user'));
}

索引

@extends('layouts.app')

@section('content')
    <h1>Welcome to notesite!</h1>
    
        <a href="/notes/show/{{ Auth::user()->id }}" name="posts">Show your posts</a>

    
@endsection

路线

Route::get('/', function () {
    return view('welcome');
});
Route::get('/pages/index', 'PagesController@index');
Route::get('/pages/about', 'PagesController@about');
Route::get('/pages/services', 'PagesController@services');

Route::get('/notes/index', 'NotesController@index');
Route::get('/notes/show/{user}', 'NotesController@show');
Auth::routes();
    
Route::get('/home', 'HomeController@index')->name('home');

任何人都可以提供解决方案吗?

标签: laravelfilterviewfetch

解决方案


欢迎来到 SO!

我建议你阅读Eloquent 关系,特别是如果你打算处理大量记录,那么关于急切加载的部分。

您可以执行以下操作:

用户模型

// Add this bit to your existing model to define the relationship 
// ( assuming that 1 user can have many different posts )

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

后模型

// By default, Eloquent will automatically determine the proper foreign key column,
// noted here as user_id

protected $fillable = ['title', 'body', 'user_id'];

后控制器

public function show() {
    $posts = App\User::find(Auth::id())->posts; // Fetch the authenticated users posts

    return view('show-posts', compact('posts') ); // Pass them back to the view
}

路线/web.php

Route::view('/pages/index', 'index');
Route::get('/posts/show', 'PostController@show');

index.blade.php

<a href="/posts/show">Show user-specific posts!</a>

show-posts.blade.php

@foreach( $posts as $post )
    {{ $post->body }}
@endforeach

推荐阅读