Laravel 5.2 PHP Build a social network – Middleware & Route Protection



Build a complete Social Network Web Application with PHP Laravel. In this video you will learn how to apply middleware to routes and how to use it to make certain routes only accessible to authenticated users.

Complete source code: https://github.com/mschwarzmueller/laravel-basics-youtube

Complete Laravel-course on Udemy: https://www.udemy.com/modern-web-development-with-laravel/?couponCode=YOUTUBE1 (Coupon: YOUTUBE1)

In this course we’ll build a neat little social network and cover the…

Related Posts

50 Comments

  1. What if in authenticate.php i only have this by default:
    namespace AppHttpMiddleware;

    use IlluminateAuthMiddlewareAuthenticate as Middleware;

    class Authenticate extends Middleware

    {

    /**

    * Get the path the user should be redirected to when they are not authenticated.

    *

    * @param IlluminateHttpRequest $request

    * @return string

    */

    protected function redirectTo($request)

    {

    if (! $request->expectsJson()) {

    return route('login');

    }

    }

    }

    And I also have RedirectIfAuthenticated.php file with this code

    namespace AppHttpMiddleware;

    use Closure;

    use IlluminateSupportFacadesAuth;

    class RedirectIfAuthenticated

    {

    /**

    * Handle an incoming request.

    *

    * @param IlluminateHttpRequest $request

    * @param Closure $next

    * @param string|null $guard

    * @return mixed

    */

    public function handle($request, Closure $next, $guard = null)

    {

    if (Auth::guard($guard)->check()) {

    return redirect('/home');

    }

    return $next($request);

    }

    }

    As you sad in the previous videos' comments I deleted surrounding Route::group([
    'middleware' => ['web']],function(){
    ….

  2. he is really a awesome teacher and For those who is using laravel 5.7 just changed route name to home in Authenticate.php and in web.php give "/" route a name home And add auth middleware to /dashboard route , this things work for me

  3. Hey Guys, im using the newest version of Laravel (5.6.27) and i dont have the Authenticate.php file in my project tree. Maybe on the beggining it is optional and i have to create it somehow?

  4. This is in RedirectIfAuthentificated.php file
    public function handle($request, Closure $next, $guard = null)
    {
    if (!Auth::guard($guard)->check(){
    return redirect()->route('home');
    }

    return $next($request);
    }

    for the most of you, it doesn't work just because the session still exists, I think that is the right method to do it.

    //This the route code that you have to include in you're web.php file
    Route::get( '/dashboard', 'UserController@getDashboard')->name('dashboard')->middleware('guest');

  5. I'm using Laravel 5.6 and tried all the suggestions in the comments and dashboard can still be accessed through the url. Laravel makes it tougher to learn when it keeps changing things.

  6. To redirect to the route you want when trying to access the dashboard unauthenticated in laravel 5.5 do the following:

    protected function unauthenticated($request, AuthenticationException $exception)
    {
    return $request->expectsJson()
    ? response()->json(['message' => 'Unauthenticated.'], 401)
    : redirect()->guest(route('home')); //Set this route to where ever you want
    }

  7. For the guys having isses with Laravel 5.5.
    i took a look at the docs, and here is the solution:
    we have to add write the dashboard Route like this:

    Route::get('/dashboard', [
    'uses' => 'UserController@getDashboard',
    'as' => 'dashboard',
    ])->middleware('auth');;

    and also change the Route::group(['middleware' ..
    name('home); to name('login');

  8. I stopped following after this video, simply because things are getting really different in 5.5. Which is really a shame, coz I really like this tutorial and teachers style.
    Why things have to change so fast?? ))

  9. For laravel 5.4 (5.3, maybe) ,Change in code for everyone having problem authenticating users :

    ### web.php
    // Group of routes which require a user to be logged in . (Keep all other routes : signin, signup. etc. ……. outside this group)

    Route::group(['middleware' => ['auth']], function() {

    Route::get('/dashboard', [
    'uses'=>'UserController@getDashBoard',
    'as'=>'dashboard'
    ]);

    });

    ### AppExceptionshandler.php
    protected function unauthenticated($request, AuthenticationException $exception)
    {
    if ($request->expectsJson()) {
    return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('home')); //change from login to home

    }

  10. Your videos are so much helpful for me. Thanks for all your videos.

    I am using laravel 5.4 , in middleware folder you have mentioned about the authenticate.php but I can't locate this file in this folder. can you help me?

    Thanks in advance

  11. This method is not working on Laravel 5.4
    The SOLUTION is to go on app/Exceptions/Handlers.php and
    change the last line of code:
    return redirect()->guest(route('login'));
    to
    return redirect()->guest(route('home'));
    And this should WORK!

  12. Hey +Mindspace . Loving the tutorials, they're great. Sorry to bother you but I'm not being redirected to my dashboard when logging in but being redirected to the login page. The dashboard is inaccessible when typing the URL directly so it's working to an extent but just I'm not able to login. I'm using laravel 5.4 and the web.php and Handler.php files. I've tried logging in via chrome's incognito mode and this still doesn't work so I'm not certain what is happening. Any help would be great 🙂 Thank​ you.

  13. I am using Laravel 5.4 and i am not able to do authentication when going to dashboard.The
    ExceptionsHandler.php last function looks like this

    protected function unauthenticated($request, AuthenticationException $exception)
    {
    if ($request->expectsJson()) {
    return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->route('home');
    }

    and in my Routesweb.php, i have this

    Route::get('/dashboard',[
    'uses' => 'UserController@getDashboard',
    'as' => 'dashboard'
    ])->middleware('auth');

  14. I am new to laravel and I must say that your videos are awesome and are easy to follow. Keep up the great job! You earned yourself a new subscriber 🙂

  15. I want to ask something rly basic, what if I want to redirect to a page without that 'uses' => 'blah blah blah' line, i dont get what it excactly does and what will happen if i dont use something like that. cuz when I creat a page and than try to create route for it and use that line, it basicly crashes and says: Method AppHttpControllersUserController::SOMETHING() does not exist

  16. for people using laravel 5.3 instead of trying to find the authenticate.php file go into app/Exceptions/Handler.php

    once there scroll to the bottom and edit the bottom part into this

    protected function unauthenticated($request, AuthenticationException $exception)
    {
    if ($request->expectsJson()) {
    return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->route('home');
    }

    also make sure your using web.php for routes instead of routes.php for laravel 5.3

  17. Hi this has changed in laravel 5.3 the files are not the same. please help. I guess I stop here if there is no way around this because I am sure the rest of the videos pretty much depends on Authentication

  18. I cant make it to work, whenever i type "http://localhost/test/public/dashboard" it keeps landing in dashboard
    1. im on laravel 5.3 and theres no authenticate but i found this RedirectIfAuthenticated.php
    public function handle($request, Closure $next, $guard = null)
    {
    if (Auth::guard($guard)->guest()) {
    return redirect()->route('home');
    }

    return $next($request);
    }
    can still make it to work

    2. I saw that i can use handler.php but i still cant make it work
    please help me thanks

  19. I am currently using laravel 5.3 . I cant find the Authenticate.php under middleware? DO i have to create it manually or there is another file here that i can use that has the same function from 5.2?

  20. In my Middleware folder I don't have Authenticate.php! Doing a search in my directory I have an Authenticate.php in vendor/laravel/framework/src..etc. I haven't seen anyone else have this problem in the comments so far.. Everything else works except it tries to redirect to /login by default I suppose.

  21. I missed the edit made @2:31 while I was looking at my IDE and couldn't figure out what was going wrong. At first I had the problem with previous cookies keeping me logged in — so authentication succeeded (failed to lock me out) anyway and there was no difference until I cleared them, but I was getting an exception. I searched the comments to see if anyone else had the same problem and saw the:

    "redirect()->route('home')"

    edit in a reply to someone's question. Not knowing that this was what I was supposed to have done in the first place. So I looked up the difference between RedirectResponse::guest() & RedirectResponse::route(). It looks as though guest() is intended to record where they were trying to go before being caught by the authentication. I imagines this is for redirecting them back there after authentication.

    Anyway, I started experimenting, so to those that are interested; here's what I have in my Laravel v5.2 – AppHttpMiddlewareAuthenticate::handle()

    public function handle($request, Closure $next, $guard = null)
    {
    if (Auth::guard($guard)->guest()) {
    if ($request->ajax() || $request->wantsJson()) {
    return response('Unauthorized.', 401);
    } else {
    //original code below. Does not work as intended.
    // return redirect()->guest('home');
    //throws NotFoundHttpException in RouteCollection.php line 161:
    //experiments
    // return redirect()->guest();//500 Error
    // return redirect()->guest('');//works -> home / index.php
    // return redirect()->guest('/');//works -> home / index.php

    //manually added redirects that work as intended
    // return redirect()->home();//works as was intended (send to home route)
    return redirect()->route('home');//works as intended.
    }
    }

    return $next($request);
    }

  22. if after doing all this you still can access the dashboard page then you need to clear the cookies as the user session is already made when we tried to login earlier and we never logged out as we dont have that functionality yet.

  23. Hai sir,
    Till the login process it works great 🙂 and now am in confusion sir..
    As u told in earlier tutorial about group middleware is not needed anymore I've removed my 'group middleware['web']' without that it works fine
    and now in this tutorial should I want to include the '26th line'? which is in your tutorial ? as middleware
    Reference & Routing
    (NOTE:Refresh after visited the link)
    http://tinypic.com/view.php?pic=k173vk&s=9#.V5Ncd0Z94dU
    http://tinypic.com/view.php?pic=28vww&s=9#.V5NboUZ94dU

  24. +Mindspace , not getting into the Dashboard through signin & signup process. Pls help me out of this. route file:-
    Route::group(['middleware' => ['web']], function(){
    Route::get('/', function () {
    return view('welcome');
    })->name('home');
    Route::post('/signup',[
    'uses' => 'UserController@postSignUp',
    'as' => 'signup'
    ]);
    Route::post('/signin',[
    'uses' => 'UserController@postSignIn',
    'as' => 'signin'
    ]);
    });
    Route::get('/dashboard', [
    'uses' => 'UserController@getDashboard',
    'as' => 'dashboard',
    'middleware' => 'auth'
    ]);

Leave a Reply

Your email address will not be published.

© 2022 Code As Pro - Theme by WPEnjoy · Powered by WordPress