如何在将其返回为404之前跳过通配符路径来检查另一条路线?
Route::get( '{user}', function( $user ){
// Checking for existing user
if( $user = User::getUser( $user ) )
return view( 'templates.user', [ 'user' => $user ] );
// Should check another prefixes before return 404
return abort( 404 );
});
Route::get( 'foopage', function(){ return view( 'templates.foo' ); });
从上面的代码中,如果我访问/foopage
,它会返回404,因为没有用户名“foopage”。
但它应该显示view( 'templates.foo' )
答案 0 :(得分:2)
移动声明
Route::get( '{user}', function( $user ){
...
});
在用户路线声明上方。
100,0
74,8103
51,15304
24,23407
2,30609
23,33286
55,37360
76,40064
100,44132
这是因为laravel优先考虑定义的路由顺序,如果foopage路由定义在用户路由下方,则会将foobar视为用户路由并尝试沿着该路径前进。
答案 1 :(得分:0)
万一你需要多个通配符检查,我带来了这个答案
使用Symfony\Component\HttpFoundation\ParameterBag
我只需构建一个运行ParameterBag::add()
的新别名ParameterBag::get()
接下来在routes / web.php
中// Create the wildcard route
Route::get( '{user}', function( $user ){
$template = ParameterBag::get( 'template' );
$userdata = ParameterBag::get( 'userdata' );
return view( $template, [ 'userdata' => $userdata ] );
})->middleware( 'userroute' );
在App \ Http \ Kernel.php
中创建自定义$routeMiddleware
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
....
'userroute' => \App\Http\Middleware\WildcardRoutes::class,
];
App \ Http \ Middleware \ WildcardRoutes.php中的处理程序
<?php
namespace App\Http\Middleware;
use Closure;
use ParameterBag; // I have this alias in app.php
use User; // alias about Users
use Group; // alias about Groups
class WildcardRoutes{
public function __construct(){ /* do anything */ }
/* Handle an incoming request. */
public function handle($request, Closure $next){
// Check if user exists
if( $user = User::getUser( $request->user ) ){
// When exist store the information
ParameterBag::add( [ 'userdata' => $user, 'template' => 'templates.user' ] );
return $next($request); // means everything going well
}
// Checking in the group
if( $group = Group::getGroup( $request->user ) ){
// When exist store the information
ParameterBag::add( [ 'userdata' => $group, 'template' => 'templates.group' ] );
return $next($request);
}
// When nothing found
return abort(404);
}
}