agyanadda@gmail.com

Laravel Eloquent Models

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 8 of 13

Eloquent is Laravel's ORM (Object-Relational Mapper). Each database table has a model class, and each row becomes an object.

Create a model

php artisan make:model Post -m creates app/Models/Post.php and its migration. By convention the Post model uses the posts table.

Reading data

  • Post::all() — every row
  • Post::find(1) — one row by id, or null
  • Post::findOrFail(1) — one row, or a 404 page
  • Post::where('is_published', true)->latest()->get() — filtered and sorted
  • Post::where('slug', $slug)->first() — first match
  • Post::count() — number of rows

Mass assignment

Post::create([...]) saves a row from an array. For safety, list allowed columns in $fillable; any other key is ignored. This stops users from setting fields like is_admin through a form.

Pagination

Post::latest()->paginate(10) returns 10 rows per page, and {{ $posts->links() }} in Blade prints the page links.

Example

Example — Model and queries PHP
<?php
// app/Models/Post.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    protected $fillable = ['user_id', 'title', 'body', 'is_published'];
}

// Anywhere in a controller:
$post = Post::create([
    'user_id' => 1,
    'title'   => 'Hello Eloquent',
    'body'    => 'My first post.',
]);

$published = Post::where('is_published', true)->latest()->get();
echo $post->title;   // Hello Eloquent

create() inserts a row and returns a Post object. Columns are read as properties, e.g. $post->title.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method returns a 404 page when the row is not found?

Exercise 2 True / False

By convention, the Post model uses the posts table.

Exercise 3 Fill in the Blank

Columns allowed for mass assignment are listed in the $___ property.

Frequently Asked Questions

get() returns a collection of all matching rows (possibly empty). first() returns only the first matching model, or null if none match.