2
votes

I have a Laravel application with following routes:

  1. http://site-name/ (auth)
  2. http://site-name/home (public)
  3. http://site-name/about (public)

As http://site-name/ needs authorized user, it needs a login check. I have written a following route for this

Route::get('/', 'SiteController@index');

Where SiteController is,

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class SiteController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('play');
    }
}

Above __construct() will redirect the user to http://site-name/login view.

Now, the tricky part starts. I need to modify my laravel application such that, for login, it would show the login view to unauthorized user on http://site-name/ instead of redirecting to http://site-name/login for login.

2

2 Answers

1
votes

If you want to change your unauthorized user redirect path. Go to the :

app\Exceptions\Handler.php

inside the unauthenticated method you can change your redirect path onhttp://site-name/ instead of http://site-name/login this.

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

        return redirect()->guest('/login');  // Here you should be specify your unauthorized redirect url path.
    }
0
votes

as you asked in the comment section, here is a way to not redirect, instead just render a Template!

But I think you want to stay on the same page and show an error or something ? Check out this link: Laracasts Ajax call login Laravel

If you render a view be sure it's a web route and not an api route. If it's an api route be sure to deactivate throttling in

app/Http/Kernel.php

Example of Rendering a template on unauthenticated():

app\Exceptions\Handler.php

/**
 * @param                         $request
 * @param AuthenticationException $exception
 *
 * @return \Illuminate\Contracts\View\View|\Illuminate\Http\JsonResponse
 */
protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return \View::make('login',['title' => 'unauthenticated']);
}