将两个变量传递给 Laravel 中的方法

Pass two variable to method in Laravel

我想在 url 中通过 slug 找到 post .. 但评论必须被post_id

找到

控制器

public function post($slug,$id)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$id)->get();
    return view('content.post',compact('post','comments'));
}

路线

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

给你:

$post 本身获取 post_id

public function post($slug){
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    ...
}

在web.php中:

Route::get('post/{slug}', 'PagesController@post')->name('post.show');

在控制器中:

public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
    return view('content.post',compact('post','comments'));
}
Route::get('post/{slug}', 'PagesController@post')->name('post.show');
public function post($slug)
{
    $post = Post::where('slug',$slug)->first();
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}

您可以使用 Route Model Binding 来确保路由会根据提供的键找到您的模型。

您的 Post 模型将要求您添加以下方法:

public function getRouteKeyName()
{
    return 'slug';
}

然后,在你的路由中,你可以直接引用模型,绑定会自动发生:

public function post(App\Post $post)
{
    $comments = Comment::where('post_id',$post->id)->get();
    return view('content.post',compact('post','comments'));
}

这使您能够使用以下路线:

Route::get('post/{post}', 'PagesController@post')->name('post.show');

现在,另外,为了简化您对评论的引用,将它们作为关系添加到您的 Post 模型中:

public function comments() 
{
    return $this->hasMany(Comment::class);
}

和您的 Comment 模特:

public function post()
{
    return $this->belongsTo(Post::class);
}

这将允许您进一步缩短控制器方法:

public function post(App\Post $post)
{
    return view('content.post',compact('post'));
}

并在您的 Blade 视图中执行以下操作:

@foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
@endforeach