我如何在 laravel 的 readmore 中传递博客的标题而不是 id

How can i pass the title of the blog instead of the id in readmore in laravel

单博打开路径:

Route::get('/blog/{title}', 'EdificController@showblog');//single blog view

列出所有博客的主博客博客路由

Route::get('/blog', 'EdificController@blog')->name('blog');//blog view

显示单个博客的控制器(front-end)

public function showblog( $title)
     $blog = Blog::find($title);
        return view('edific.show-blog', compact('blog', 'blogcomments', 'blogreplies'));
}

阅读更多调用单博客的代码:

<a href="/blog/{{$blog->title}}" class="post-meta">Read More</a>

当我点击 link 时出现错误

Trying to get property 'image' of non-object (View: C:\laragon\www\edi-fic-1.0.0\resources\views\edific\show-blog.blade.php)

我想要的是,而不是调用 id 例如 1 (http://127.0.0.1:8000/blog/**1**) 它应该使用 blog.The 的标题打开 id should not be seen

您的路线似乎没问题,需要更改控制器和 blade 文件

您需要检查博客标题是否有效,出现图片错误的原因是没有博客 ($blog is null) 包含您传递的标题,因此您需要更改函数

public function showblog( $title)
     $blog = Blog::where('title', $title)->first();
     if (!$blog)
        abort(404);

    return view('edific.show-blog', compact('blog', 'blogcomments', 'blogreplies'));
}

在上面的代码中,我将 $blog = Blog::find($title); 更改为 $blog = Blog::where('title', $title);。因为 find 函数搜索主键,所以 title 是你的主键的情况很少见,它应该是 id

另外最好使用命名路由 改变我们的路线

Route::get('/blog/{title}', 'EdificController@showblog');

Route::get('/blog/{title}', 'EdificController@showblog')->name('blogs.show');

然后路由函数调用

<a href="{{ route('blogs.show', $blog->title) }}" class="post-meta">Read More</a>

如果以上功能不起作用,试试这个

<a href="{{ route('blogs.show', ['title' => $blog->title]) }}" class="post-meta">Read More</a>