Laravel - Model

laravel

Where does Laravel keep the model files?

Laravel keeps the model files inside the app folder.

What kind of code can we keep inside the model file?

The model file is for application logic.

How can we create a model instance and persist it to the database?

$user = new User();
$user->email = $email;
$user->save();

When should we use $modelInstance->save() and when should we use $modelInstance->update()?

Use $modelInstance->save() for saving new record to the database. Use $modelInstance->update() for updating an existing record.

How can we specify a belongsTo relationship?

In our model class, we have to define a function:

class Post extends Model {
  public function user() {
    return $this->belongsTo('App\User');
  }
}

At the same time, we may want to also define a hasMany relationship in the corresponding model file.

How can we define a hasMany relation?

In our model class, we have to define a function:

class User extends Model implements Authenticable {
  use \Illuminate\Auth\Authenticable;
  public function posts() {
    return $this->hasMany('App\Post');
  }
}

How can we delete a model instance from the database?

$modelInstance->delete();
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License