在Laravel 5

时间:2015-12-26 18:37:37

标签: php laravel-5.1 laravel-middleware

我正在制作一个检查锦标赛所有权的中间件。

所以在网址中,我有:

  

http://laravel.dev:8000/tournaments/1/edit

我需要在$ tournamentId中获得“1”

在中间件中,我只有$ request和$ closure参数,所以我试过

$tournamentId = $request->get("tournaments");

和@Amir Bar说:

$tournamentId = $request->tournaments;

我用

检查了路线
php artisan route:list

我得到了

GET|HEAD | tournaments/{tournaments}        | tournaments.show         | App\Http\Controllers\TournamentController@show      | auth,roles,ownTournament |
DELETE   | tournaments/{tournaments}        | tournaments.destroy      | App\Http\Controllers\TournamentController@destroy   | auth,roles,ownTournament |
PATCH    | tournaments/{tournaments}        |                          | App\Http\Controllers\TournamentController@update    | auth,roles,ownTournament |
PUT      | tournaments/{tournaments}        | tournaments.update       | App\Http\Controllers\TournamentController@update    | auth,roles,ownTournament |
GET|HEAD | tournaments/{tournaments}/edit   | tournaments.edit         | App\Http\Controllers\TournamentController@edit      | auth,roles,ownTournament |          | auth,roles,ownTournament |

但没有任何作用......

我的中间件:

class OwnTournament
{
    /**
     * Check the ownership of tournaments
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        dd($request->route());
        return $next($request);
    }
}

知道我该怎么办?

2 个答案:

答案 0 :(得分:4)

如果您的路线如下:

 Route::get('tournaments/{tournamentId}/edit');

在中间件中执行此操作:

 $tournamentId =  $request->tournamentId

如果您的路线如下:

Route::resource('name')

这样做:

$tournamentId =  $request->name;

你也可以这样做以获得有关发生的更多信息:

dd($request->route()->parameters());

答案 1 :(得分:0)

这是我的解决方案。

public function handle($request, Closure $next)
{
    if (Auth::check()) {
        $user = Auth::user();
        $tournaments = $user->tournaments;
        $tournament = null;
        if ($request->tournaments != null || $request->tournamentId != null) {
            $tournament = $request->tournaments;
            if ($tournament != null) {
                if (!$tournaments->contains($tournament)) {
                    return "You don't have privileges to access this resource";
                }
            }
        }
    }


    return $next($request);
}

中间件被调用两次,第一次,它什么也没有访问权限。我不知道为什么......

所以基本上已经解决了,但是没有理解为什么会发生这种情况,所以解决了一半:(

感谢@Amir Bar帮助我!