Eloquent

Table des matières

1. Create a model

With Eloquent, a table is represented by class which is an extension of a model.

To work with a model, there is an artisan command that will generate for us the model. By convention, if the table is called Articles, the model will be Article (no plural form)

php artisan make:model Article

This done, a new file will be created : /app/Article.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    //
}

Now, just update and add our fields

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $table = 'articles';
    public $timestamps = true;
    public $title = '';
    public $content = '';
}

If, when creating the table, we’ve foresee $table->timestamps(); in the up() function, then Laravel has create two fields :

This automatically. In order to ask to Eloquent to manage these fields, the Model should set the $timestamps variable to true, false otherwise.

2. Use the model

Once the model has been created, we then have a class that is, in fact, our table.

To add a new request f.i., we can, in a controller, have something like:

<?php

namespace App\Http\Controllers;

use App\Article;    // use our model
use App\Http\Requests\ArticleRequest;

class ArticleController extends Controller
{
  public function getForm()
  {
    return view('article');
  }

  public function postForm(ArticleRequest $request)
  {
    $article = new Article;
    $article->title = $request->input('title');
    $article->content = $request->input('content');
    $article->save();

    return view('article_ok');
  }

}

Thanks the model, fields like title and content are now properties of the object. Just assign values to them and call the save() method.