Creating the user model
First of all, we need to define the model that is going to be used to represent the
users of our application. Laravel already provides you with sensible defaults inside
app/config/auth.php, where you change the model or table that is used to store
your user accounts.
It also comes with an existing User model inside app/models/User.php. For the
purposes of this application, we are going to simplify it slightly, remove certain
class variables, and add new methods so that it can interact with the Cat model:
use IlluminateAuthUserInterface; class User extends Eloquent implements UserInterface { public function getAuthIdentifier() { return $this->getKey(); } public function getAuthPassword() { return $this->password; } public function cats(){ return $this->hasMany('Cat'); } public function owns(Cat $cat){ return $this->id == $cat->owner; } public function canEdit(Cat $cat){ return $this->is_admin or $this->owns($cat); } }
Remember that an interface does not give any implementation details. It is nothing
more than a contract that specifies the names of the methods that a class should
define when it implements the interface, in this case, getAuthIdentifier()
and getAuthPassword(). These methods are used internally by Laravel when
authenticating a user. The next method, cats(), simply defines the has many
relationship with the Cat model. The last two methods will be used to check
whether a given Cat instance is owned or editable by the current User instance.
Creating the necessary database schema
Now that we have defined a User model, we need to create the database schema
for it and alter the existing cats table to add information about the owner. Start by
creating a new migration:
$ php artisan migrate:make create_users
And then define the up method with the necessary database columns:
Authentication routes and views
Let's now look at the new routes and views. We will start by making some amends to
the master layout (app/views/master.blade.php) to display the login link to guests
and the logout link to users who are logged in. To check whether a visitor is logged
in, we use the Auth::check() method:
<div class="container"> <div class="page-header"> <div class="text-right"> @if(Auth::check()) Logged in as <strong>{{{Auth::user()->username}}}</strong> {{link_to('logout', 'Log Out')}} @else {{link_to('login', 'Log In')}} @endif </div> @yield('header') </div> @if(Session::has('message')) <div class="alert alert-success"> {{Session::get('message')}} </div> @endif @if(Session::has('error')) <div class="alert alert-warning"> {{Session::get('error')}} </div> @endif @yield('content') </div>
This code replaces the contents of the <body> tag in our previous template file.
A section for any error messages was also included below the header.
The route to display this login form could not be easier:
Route::get('login', function(){
return View::make('login');
});
If you were curious as to where and why Laravel uses the make methods
in various places, it is only there to maintain PHP 5.3 compatibility, which
does not support class member access on instantiation, and therefore, does
not let you write return new View('login');.
The route that handles login attempts will simply pass the username and password
input values to the Auth::attempt method. When this method returns true, we
simply redirect the visitor to the intended location. If this fails, we redirect the user
back to where he came from with Redirect::back() with the input values and an
error message.
Route::post('login', function(){
if(Auth::attempt(Input::only('username', 'password'))) {
return Redirect::intended('/');
} else {
return Redirect::back()
->withInput()
->with('error', "Invalid credentials");
}
});
But how does Laravel know what our intended location was? If you open
app/filters.php and look at the auth filter, you will see that it redirects guests
to the login route with the Redirect::guest() method. This method stores the
requested path in a session variable, which is then used by the intended() method.
The parameter passed to this method is the fallback route to which users should be
redirected if there is no request path in the session information.
Note also that there is a filter called guest that does the opposite of
auth; you could use it on the login route if you wanted to prevent
logged-in users from accessing it. With this filter in place, logged-in users
will be redirected to the home page instead. You can change this behavior
inside app/filters.php.