agyanadda@gmail.com

Laravel Scopes, Accessors and Casts

Database and Eloquent 1 min read Updated Dec 2, 2026 Topic 17 of 31

These Eloquent features move repeated logic into the model, so controllers stay short.

Local scopes

A method named scopePublished($query) becomes Post::published(). Scopes can be chained: Post::published()->latest()->get().

Accessors and mutators

Define a method returning Attribute::make(get: ..., set: ...):

  • get changes a value when you read it (e.g. a formatted name)
  • set changes a value before it is saved (e.g. lowercase email)

Casts

Casts convert columns automatically:

  • 'is_published' => 'boolean' — 0/1 becomes true/false
  • 'published_at' => 'datetime' — a Carbon date you can format
  • 'settings' => 'array' — JSON column becomes a PHP array
  • 'password' => 'hashed' — hashes the value when saving

In Laravel 11 and later casts go in a casts() method; older versions use a $casts property.

Soft deletes

Add $table->softDeletes() to the migration and the SoftDeletes trait to the model. Now delete() only sets deleted_at; the row is hidden from queries but can be brought back with restore(). Use withTrashed() to include deleted rows.

Example

Example — A cleaner Post model PHP
<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class Post extends Model
{
    use SoftDeletes;

    protected function casts(): array
    {
        return ['is_published' => 'boolean', 'published_at' => 'datetime'];
    }

    public function scopePublished($query)
    {
        return $query->where('is_published', true);
    }

    protected function title(): Attribute
    {
        return Attribute::make(set: fn (string $value) => Str::title($value));
    }
}

// Usage
$posts = Post::published()->latest()->get();
echo $posts->first()?->published_at?->format('d M Y');   // 01 Dec 2026

Saving the title "learn laravel scopes" stores "Learn Laravel Scopes". published_at is a Carbon date, so ->format() works directly.

Test Yourself With Exercises

Exercise 1 Multiple Choice

A method named scopeActive() is called as…

Exercise 2 True / False

With SoftDeletes, delete() permanently removes the row.

Exercise 3 Fill in the Blank

Use the ___ cast to turn a JSON column into a PHP array.

Frequently Asked Questions

Use them for data users might delete by mistake or that you must keep for records, such as orders, posts or users. Remember that unique columns (like email) still contain the soft-deleted values.