mardi 12 mars 2019

Apply middleware when URL pattern matches in Laravel

I am trying to add a simple middleware to my project that checks if a user is allowed to access a project. My approach is:

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;


class UserProjectFit
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        if ($request->is('*/projects/*')) {

            $projectUserId = DB::table('project_user')
                ->where('project_id', '=', $request->project['id'])
                ->where('user_id', '=', Auth::user()->id)
                ->first();

            if (is_null($projectUserId)) {
                abort(404);
            }

        }

        return $next($request);
    }
}

It basically works, but I have also routes like e. g. projects/create and here the middleware kicks in too. The idea would be that the middleware only takes action in case the URL contains the string project and an id, e. g. …projects/1/…

What would be a good way to solve that? If my approach isn't good, I am happy to read your suggestions.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire