自定义路由不起作用 - 404 未找到

Custom Routes not working - 404 not found

我正在尝试创建自定义路线。必须采用这种格式:http://localhost:8000/home-back-to-school 但我却收到 404 未找到错误。 http://localhost:8000/posts/home-back-to-school 有效,但这不是我想要的。

我在 web.php 上的路线定义为:Route::resource('posts',PostsController::class); 我通过添加以下代码修改了路由服务提供商:

 parent::boot();

    Route::bind('post',function($slug){

        return Post::published()->where('slug',$slug)->first();
    });

已发布范围在 Post 模型文件 (Post.php) 中定义为:

  public function scopePublished()
{
    return $this->where('published_at','<=',today())->orderBy('published_at', 'desc');
}

我之前已经完成了 laravel 5.x,现在正在努力 laravel 8.x Link 到文档:Laravel 8 Documentation

您应该定义一个自定义路由,因为您不想为此方法使用足智多谋的路由。

在你的web.php

// Keep all your resource routes except the 'show' route since you want to customize it
Route::resource('posts', PostsController::class)->except(['show']);

// Define a custom route for the show controller method
Route::get('{slug}', PostsController::class)->name('posts.show');

在你的Post控制器中:

public function show(Post $post)
{
    return view('posts.show', compact('post'));
}

在您的 Post 模型中:

// Tell Laravel your model key isn't the default ID anymore since you want to use the slug 
public function getRouteKeyName()
{
    return 'slug';
}


您可能需要修复其他 Post 路由才能使它们适用于此更改,因为您现在使用 $post->slug 而不是 $post->id 作为模型密钥。

阅读更多关于自定义模型密钥的信息:

https://laravel.com/docs/8.x/routing#customizing-the-default-key-name

您还应该删除启动方法中的代码并改用控制器。

最后,出于明显的原因,请确保您的 post 别名始终是独一无二的。


注:

如果您的其他路由与 Post 模型无关,您可能 运行 会遇到问题。

想象一下,如果您有一条名为 example.com/contact-us 的路线。 Laravel 无法“猜测”此路由是否应该发送到 PostController 或 ContactController。 contact-us 可能是 Post slug 或者它可能是到您的联系页面的静态路由。这就是为什么以模型名称开始您的网址通常是个好主意。在您的情况下,您的 Post 路由以“/posts/”开头是个好主意,如下所示:http://example.com/posts/your-post-slug。否则你可能 运行 陷入各种意想不到的路由问题。

不要对抗框架:尽可能遵循最佳实践和命名约定。