【问题标题】:Custom Routes not working - 404 not found自定义路由不起作用 - 找不到 404
【发布时间】:2021-09-04 00:52:26
【问题描述】:

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

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

 parent::boot();

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

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

发布的范围在 Post Model 文件(Post.php)中定义为:

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

我以前用过 laravel 5.x,现在用 laravel 8.x 文档链接:Laravel 8 Documentation

【问题讨论】:

  • 所以定义一个匹配home-back-to-school模式的路由。

标签: laravel routes


【解决方案1】:

您应该定义一个自定义路由,因为您不想为此方法使用资源丰富的路由。

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

在您的 PostController 中:

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-&gt;slug 而不是 $post-&gt;id 作为模型键,因此您可能必须修复您的其他 Post 路由以使它们与此更改一起使用。

阅读有关自定义模型键的更多信息:

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

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

最后,确保您的帖子 slug 始终是独一无二的。


注意:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多