为了账号安全,请及时绑定邮箱和手机立即绑定

我的帖子不会路由到他们的详细信息页面

我的帖子不会路由到他们的详细信息页面

PHP
梦里花落0921 2023-11-04 21:03:39
我正在尝试用 laravel 制作一个博客应用程序。我的问题是,我已在 allnews.blade.php 视图中列出了我的帖子,并且我将文本描述为可路由到帖子的详细信息页面,但它不起作用allnews.blade.php@foreach ($posts as $post) // this is allnews.blade.php view        <li>            <div class="media wow fadeInDown">               <a href="{{$post->slug}}" class="container"> <img width="100%" height="auto" alt=""                src="/storage/{{ $post->image}}"> </a>              <div class="media-body"> <h3 src="" class="catg_title">{{$post->title}}</h3> </div>            </div>          </li>        @endforeach但是当我尝试转到我的帖子详细信息(通过使用 href $post->slug)时,我遇到了“404 页面未找到”问题。按照我的逻辑,一切看起来都很完美。但我无法路由。这是我的PostController.php public function DetailofPost($id) {   $PostDetails  = Post::where('slug' , $id)->first();   return view('PostDetail', compact ('PostDetails')); }这是我的PostDetail.blade.php视图         @foreach($PostDetails as $PostDetail)            <h1>{{PostDetail->title}}</h1>        <div class="single_page_content"> <img class="img-center" src="/storage/{{ $PostDetail->image}}" alt="">          <blockquote> {{PostDetail->body}}</blockquote>         @endforeach    这是我的路由页面,又名web.php  Route::get('/', function () { return view('welcome');                             }); Route::get("/tumhaberler" , 'PostController@ListAll'); Route::group(['prefix' => 'admin'], function () { Voyager::routes();                                                 }); Route::get('/{slug}', 'PostController@DetailofPost');
查看完整描述

3 回答

?
芜湖不芜

TA贡献1796条经验 获得超7个赞

您将 slug 传递到 URL 中:

<a href="{{$post->slug}}"

但尝试使用 ID 在控制器中查找帖子:

public function DetailofPost($id)

如果你想始终使用 slug 作为标识符,你需要通过将你的路由更改为以下方式来告诉 Laravel:

Route::get('/{post:slug}', 'PostController@DetailofPost');

然后更改控制器功能以自动加载带有该 slug 的帖子:

public function DetailofPost(App\Post $post)

然后在控制器中,您不需要设置,$PostDetails因为您将拥有变量$post

这称为路由模型绑定。


查看完整回答
反对 回复 2023-11-04
?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

href应该包含完整的网址,而不仅仅是您的$post->slug.

更改hrefurl("/{$post->slug}"),假设您想要的网址类似于http://yoursite.com/title-of-my-post

请参阅文档: https: //laravel.com/docs/7.x/urls#introduction


查看完整回答
反对 回复 2023-11-04
?
白板的微信

TA贡献1883条经验 获得超3个赞

     @foreach($PostDetails as $PostDetail) //this is my detail page

     <h1>{{PostDetail->title}}</h1>

    <div class="single_page_content"> <img class="img-center" src="/storage/{{ 

     $PostDetail->image}}" alt="">

     <blockquote> {{PostDetail->body}}</blockquote>

     @endforeach    

我的逻辑是错误的。在我的控制器中,我将其设置为我的控制器从数据库中获取帖子的ID,而不是通过ID相关的数据库列(例如“slug”或“title”)在详细信息页面上填充它们,正如你们所看到的,不需要使用@foreach,这里是我从 PostDetail.blade.php 更新的代码


       <div class="single_page">

        <h1>{{$PostDetails->title}}</h1>

        <div class="single_page_content"> <img class="img-center" src="/storage/{{ 

        $PostDetails->image}}" alt=""> </div>

        <a>  {{$PostDetails->body}} </a>


查看完整回答
反对 回复 2023-11-04
  • 3 回答
  • 0 关注
  • 102 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信