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 Illuminate\Auth\UserInterface; 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:
laravel Authentication and Security,布布扣,bubuko.com