Laravel’s routing works fantastically, except when you don’t want to use it. Laravel works as a great back end to single page applications but some of the cool stuff like Laravel’s ability to handle authentication doesn’t work quite right if it’s not serving out the pages.

So in Laravel you can do stuff like make parts of your controllers that are available to the public but force other parts of the controllers to be authenticated.

class DomainController extends \BaseController {

	public function __construct() {
		$this->beforeFilter("auth", ["except" => ["index", "search"]]);
	}
....

So if you were to access any route other than DomainController@index or DomainController@search you’ll be redirected to /login by Laravel.

So we need to have a route to handle that:

Route::get("login", "SessionController@create");

And then that page would normally be submitted as a normal request and then you could use Laravel’s Redirect::intended to take the user to whatever the address was they were trying to get to before they were being prompted to log in.

But if you want to use AJAX for your login then that won’t work because the JSON data would be doing the redirecting so we needed to mine for that intended URL and found it stored in Laravel’s session data.

So before we build the login page, we can add this little bit of code to place it into the form being posted and then we can hand it back with the JSON so that the successful login request can still be sent to the correct location.

	public function create()
	{
		if (Auth::check())
		{
			return Redirect::intended("dashboard");
		}
		$session = Session::get("url");
		return View::make("session.create")->with(["intended" => $session["intended"]]);
	}

then you’d do something like:

<input type="hidden" id="intended" name="intended" value="{{ $intended }}">

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>