How to create model in Laravel 4.2

Okay right after we create a table, normally you need to create the model for that particular table, remember on the previous post we create two tables users and roles, now let's create the model.

Why we need to create model for table users and roles? because on laravel if we want to manipulate the records on that table we need to use a model.

A model is a class that represent that particular table on database, so in this case we need to create model for table users and model for table roles.

In laravel 4.2, we create model and place it under app/models/ directory, okay let's create two files called User.php and Role.php inside app/models/ of your laravel project.

User model (User.php)
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

 use UserTrait, RemindableTrait;

  * The database table used by the model.
  * @var string
 protected $table = 'users';
 protected $primaryKey = 'user_id';

  * The attributes excluded from the model's JSON form.
  * @var array
 protected $hidden = array('password', 'remember_token');

 public function role()
        return $this->belongsTo('Role', 'role_id', 'role_id');


Role model (Role.php)
Class Role extends Eloquent {

 protected $table = 'roles';

 protected $primaryKey = 'role_id';

 public function users()
        return $this->hasMany('User', 'role_id', 'role_id');

That's it, now we have two models we can work with, normally you create instance of a model inside controller, but that would be on another article.