【问题标题】:laravel 5.8: slug 404 Not Foundlaravel 5.8:未找到 slug 404
【发布时间】:2020-03-01 10:29:32
【问题描述】:

我想使用 slug,但是当我点击并跳转到特定帖子时,404 未找到出现。

网址运行良好,所以我不明白为什么我看不到 结果。

web.php

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

post.php

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

ResultsController.php

public function show(Post $post)
{
    $recommended_posts = Post::latest()
                        ->whereDate('date','>',date('Y-m-d'))
                        ->where('category_id','=',$post->category_id)
                        ->where('id','!=',$post->id)
                        ->limit(7)
                        ->get();


    $posts['particular_post'] = $post;
    $posts['recommended_posts'] = $recommended_posts;

    return view('posts.show',compact('posts'));
}

表格

Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('image');
        $table->unsignedBigInteger('category_id');
        $table->string('title');
        $table->string('slug');
        $table->string('place');
        $table->string('map');
        $table->date('date');
        $table->string('organizer');
        $table->string('organizer_link');
        $table->timestamp('published_at')->nullable();
        $table->text('description');
        $table->timestamps();
    });

PostsController.php

 public function store(CreatePostsRequest $request)
{
    //upload the image to strage
    //dd($request->image->store('posts'));
    $image = $request->image->store('posts');

    //create the posts
    $post = Post::create([
        'image' => $image,
        'category_id' => $request->category,
        'title' => $request->title,
        'slug' => str_slug($request->title),
        'place' => $request->place,
        'map' => $request->map,
        'date' => $request->date,
        'organizer' => $request->organizer,
        'organizer_link' => $request->organizer_link,
        'published_at' => $request->published_at,
        'description' => $request->description
    ]);

result.blade.php

<a href="{{ route('posts.show', [$post->id,$post->slug]) }}" class="title-link">{{ str_limit($post->title, 20) }}</a>

【问题讨论】:

    标签: php laravel model laravel-5.8 slug


    【解决方案1】:

    您已将模型定义为使用 slug 键进行隐式路由模型绑定。您定义的路由results/{post} 采用1 个参数post。您正在将 id 和 slug 传递给路由助手,使其使用 id 作为参数:

    route('posts.show', [$post->id, $post->slug])
    

    您不需要为此路由传递 Post 的 id,您希望使用 slug 作为参数:

    route('posts.show', $post->slug);
    // or
    route('posts.show', ['post' => $post->slug]);
    

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2019-10-20
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2020-02-21
      相关资源
      最近更新 更多