本文介绍了检查模型是否存在,如果在Laravel中找不到模型,则继续进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,我不想在其URL前面加前缀.例如.用户和帖子

I have two models that I don't want to have a prefix in front of its URLs. E.g. Users and Posts

如果我有一个URL https://example.com/title-of-the- post https://example.com/username

If I have a URL https://example.com/title-of-the-post and https://example.com/username

我将在web.php路由文件中执行以下操作:

I will do something like this in the web.php routes file:

// User
Route::get('{slug}', function ($slug) {
    $user = User::whereSlug($slug)->get();
    return view('users.show', $user);
});

// Post
Route::get('{slug}', function ($slug) {
    $post = Post::whereSlug($slug)->get();
    return view('posts.show', $user);
});

现在我面临的问题是,即使没有模型带有匹配的塞子,也要输入第一个路径,并且永远不会到达第二个路径.

Now the issue I am facing is that the first route is entered and will never reach the second even if there is no model with a matching slug.

如果找不到$user,如何退出下一条路线(邮政)?

How can I exit to the next route (Post) if $user is not found?

注意:我尝试了许多不同的退出策略,但似乎都没有用.

Note: I have tried many different exit strategies but none seem to work.

return;
return false;
return null;
// and return nothing

提前谢谢!

更新:

另一个问题是,如果我有其他resource路由,它们也会被第一条路由阻塞.

Another issue is that if I have other resource routes they too get blocked by the first route.

例如如果我有Route::resource('cars', 'CarController'),它将生成一个与{slug}相匹配的/cars路径,并且该路径也被第一条用户路由阻止.

E.g. If I have Route::resource('cars', 'CarController') it generates a /cars path which matches the {slug} and is also being blocked by first User route.

推荐答案

不确定这是否是最佳实践,但这是为了完成我所需要的工作.

Not sure if this is best practice but here is what was done to accomplish what I needed.

在Post模型上创建了一个函数,用于检查子弹是否正在调用帖子.它同时使用正则表达式和数据库查找.

Created a function on the Post model that checks if the slug is calling a post. It uses both a regex and database lookup.

public static function isRequestedPathAPost() {
    return !preg_match('/[^\w\d\-\_]+/', \Request::path()) &&
        Post::->whereSlug(\Request::path())->exists();
}

然后,将路由包裹在这样的if语句中.

Then I wrap the Route in a if statement like this.

if (\App\Models\Post::isRequestedPathAPost()) {
    Route::get('{slug}', 'PostController@show');
}

现在仅在实际存在的情况下使用该路由.您可以将其放在路由文件的底部,以减少对数据库的不必要查找.

Now the route is only used if it actually exist. You can put this at the bottom of the route file to reduce unnecessary lookups to the database.

这篇关于检查模型是否存在,如果在Laravel中找不到模型,则继续进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 04:05