Eloquent advanced

Contents
Query scopes
Accessors
Casts
Touches parents

Query scopes

Scopes pack a common where clause into a named reusable method. Prefix the method with scope, then call the rest of the name on any query as if it were built in.

class Post extends Model { public function scopePublished($query) { return $query->where("status", "published"); } } $posts = Post::published()->get();

Accessors

Accessors compute a value each time an attribute is read, without storing it in the table. The Attribute return object defines a get callback that formats the raw value on the fly.

use Illuminate\Database\Eloquent\Casts\Attribute; class Author extends Model { protected function name(): Attribute { return Attribute::make( fn ($value) => strtoupper($value), ); } }

Casts

The casts map converts raw database strings into rich PHP types on read. Booleans, integers, arrays, and dates all come back ready to use with no manual conversion.

class Order extends Model { protected $casts = [ "paid" => "boolean", "meta" => "array", ]; }

Touches parents

Child updates should refresh the parent timestamp so lists sort correctly. The touches list names relations to bump, and saving the child then touches each parent automatically.

class Comment extends Model { protected $touches = ["post"]; public function post() { return $this->belongsTo(Post::class); } }

Next: Transactions and locks

Article author: Arthur Isaev

Related articles
Development with PHP
What is Laravel and where it runs
Install Laravel
Your first route
Controllers
Blade basics
Blade advanced
Migrations
Eloquent models
Relationships
Query builder
Seeders and factories
Validation
Auth intro
Hand-rolled login
Middleware
Service container
Config and env
Artisan commands
Events and listeners
Queues
Mail
Cache
Sessions in Laravel
CSRF
Hashing
Sanctum tokens
API resources
Gates and policies
Notifications
Scheduler
Filesystem
Localization
Testing
HTTP tests
Collections
Carbon dates
Pagination
File uploads
Eloquent advanced
Transactions and locks
Deployment
Debugbar and dd
Broadcasting
Full-text search
Capstone: blog
Capstone: JSON API
Capstone: shop cart
Performance: kill N+1
Modern Laravel tour
Hero roadmap: the whole course on one page

Search this site

Channel @aofeed Chat @aofeedchat

Contacts and cooperation:
I recommend our hosting beget.com
Write to info@aredel.com if you:
1. Want to write an article for our site or translate an article into your native language.
2. Want to place thematically relevant ads on the site.
3. Ads on my site pass maximum censorship. If you see an ad block unsuitable for school-age children, shocking or misleading - please contact us by e-mail
4. Found a mistake, inaccuracy, bug, etc. on the site. ... .......
5. Articles can be shared on social media by clicking a network icon: