【问题标题】:Pass two variable to method in Laravel将两个变量传递给 Laravel 中的方法
【发布时间】:2020-02-17 13:24:13
【问题描述】:

我也想在 url 中找到 slug 的帖子。 但是 cmets 必须通过 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');

【问题讨论】:

标签: mysql laravel laravel-5 laravel-6 laravel-6.2


【解决方案1】:
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'));
}

【讨论】:

  • 这个答案不处理错误。如果提供的 slug 未找到 Post 实体,您将收到通知和方法调用错误,未处理。
  • 只需更改$post = Post::where('slug',$slug)->first() or abort(404); 即可处理错误(未找到)
  • @WahyuKristianto 或者改用适当的模型绑定,这样可以直接处理这个问题,而无需向控制器添加额外的代码。
【解决方案2】:

给你:

$post 本身获取post_id

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

【讨论】:

  • @HamadEssa 您无需在 URL 中显示 $id。检查更新的答案。
【解决方案3】:

您可以使用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');

现在,另外,为了简化您对 cme​​ts 的引用,请将它们作为关系添加到您的 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

【讨论】:

    【解决方案4】:

    在 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'));
    }
    

    【讨论】:

    • 我编辑了我的答案,您可以通过slug 联系您的$post,然后像我的回答一样使用$post->id 联系它的cmets,这样在url 中您的ID 将不会显示
    猜你喜欢
    • 2016-04-20
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    相关资源
    最近更新 更多