2017-08-21 46 views
0

如何跳過通配符在將其返回爲404之前檢查其他路由的路由?Laravel - 檢查是否存在另一個URL前綴

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

認沽foopage {}用戶? – Scuzzy

回答

2

移動用戶路徑聲明上述聲明 Route::get('foopage', function(){ return view('templates.foo'); });

Route::get('{user}', function($user){ 
    ... 
}); 

這是因爲laravel優先級定義路由的順序,如果foopage路線定義的用戶路徑下面,將考慮foobar的是用戶的路線,並嘗試走這條路。

+0

感謝您的快速!我只是想着如果我有多個通配符檢查?'_ ,但它是無稽之談。 – vozaldi

0

以防萬一你需要多個通配符檢查,我把這個答案

Symfony\Component\HttpFoundation\ParameterBag去我只是建立一個運行ParameterBag::add()ParameterBag::get()

接下來的路線/ 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'); 

在應用程序\的Http創建自定義$routeMiddleware \ Kernel.php

protected $routeMiddleware = [ 
    'auth' => \Illuminate\Auth\Middleware\Authenticate::class, 
    .... 
    'userroute' => \App\Http\Middleware\WildcardRoutes::class, 
]; 

而且在應用程序\ HTTP協議處理程序\中間件\ 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); 
    } 
}