Eloquent models
Eloquent is the ORM built into Laravel. Every table has a model class, and every row is an object of that class. Instead of SQL queries you call methods on the model.
Creating a model
php artisan make:model PostThe class appears at app/Models/Post.php. By default the Post model works with the posts table — the plural name.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
}Reading records
use App\Models\Post;
$posts = Post::all(); // all records
$post = Post::find(1); // the record with id = 1, or nullTable columns are available as object properties:
echo $post->title;Conditions and sorting
A query is built as a chain of methods and finished with get() or first():
$posts = Post::where('is_published', true)
->orderBy('created_at', 'desc')
->limit(10)
->get();
$post = Post::where('slug', 'hello')->first();Creating a record
$post = new Post();
$post->title = 'First post';
$post->body = 'Post text';
$post->save();Laravel fills the created_at and updated_at columns itself.
Mass assignment
A record can be created with a single create() call. For that, the model lists the columns that may be filled from an array:
class Post extends Model
{
protected $fillable = ['title', 'body'];
}$post = Post::create([
'title' => 'Second post',
'body' => 'Post text',
]);Updating and deleting
$post = Post::find(1);
$post->title = 'New title';
$post->save();
$post->delete();A record or a 404 error
The findOrFail() method returns the record, or shows a 404 page if it does not exist. In a controller this removes the need for a null check:
public function show(string $id)
{
$post = Post::findOrFail($id);
return view('posts.show', ['post' => $post]);
}Common mistake
Calling create() on a model without $fillable makes Laravel throw a MassAssignmentException. This is a safeguard: without it a user could send an extra form field, such as is_admin, and it would end up in the database. List in $fillable only the columns that may be filled from a form.