Laravel Basics: Routing and Controllers
Eloquent: Your First Model
2 min read
Last updated 46 minutes ago
Eloquent is Laravel's ORM. Each model maps to a database table, and each instance to a row.
Creating a model with migration
bash
php artisan make:model Post -m
This creates app/Models/Post.php and a migration.
The model
php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Post extends Model
{
protected $fillable = ['title', 'content', 'user_id'];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
!
Mass assignment
Always define $fillable (or $guarded) so users can't assign columns they shouldn't.
The migration
php
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('title');
$table->text('content');
$table->timestamps();
});
bash
php artisan migrate
Querying
php
$posts = Post::where('title', 'like', '%Laravel%')
->latest()
->paginate(10);
$post = Post::findOrFail(1); // 404 if missing
$recent = Post::with('user') // eager load to avoid N+1
->orderByDesc('created_at')
->take(5)
->get();
In the controller
php
public function index()
{
$posts = Post::with('user')->latest()->paginate(10);
return view('posts.index', ['posts' => $posts]);
}
Blade pagination
blade
@foreach ($posts as $post)
<article>
<h2>{{ $post->title }}</h2>
<p>By {{ $post->user->name }}</p>
</article>
@endforeach
{{ $posts->links() }}
✓
Avoid the N+1 problem
Without with('user'), listing 10 posts fires 11 queries. Eager loading reduces it to 2. This one habit makes Laravel apps dramatically faster.
Advertisement