Middleware is a class that have special function in Laravel.
Middleware placed in between the User and Apps.
Before you can access the Apps, Middleware will do his job first.
We can use Middleware to do several thing
- Do you authenticated?
- What is your role?
- Do you authorized?
- Can you perform this action?
- etc
class MemberMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { //1. User must be authenticated //2. User must should be a "member" if(Sentinel::check() && Sentinel::getUser()->roles()->first()->slug == 'member') return $next($request); else return redirect('/login')->withErrors('Please login to access this area.'); } }
Another example
class ProfileMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { 1. Get Profile Id 2. Get Profile User Id 3. User must own the Profile //$ProfileId = $request->segments()[1]; //boleh pakai //$profileId= Profile::find($this->route()->parameter('profileShow')); $ProfileId = $request->route()->parameter('id'); //boleh pakai $profile = Profile::findOrFail($ProfileId); if ($profile->user_id !== Sentinel::getUser()->id) { // dd($request->user()->id); // abort(403, 'Unauthorized action.'); // return redirect('/profile')->withError('Permission Denied'); return redirect()->back()->withErrors('Permission Denied!'); } return $next($request); } }
Another finest!
class ProfileMiddleware { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * @return mixed */ public function handle($request, Closure $next) { //get User Id $UserId=$request->id; //get User Profile $profile=Profile::whereUserId($UserId)->first(); if ($profile->user_id !== Sentinel::getUser()->id) { return redirect()->back()->withErrors('Permission Denied!'); } return $next($request); } }