Laravel’s Eloquent ORM (Object-Relational Mapper) is an ActiveRecord implementation that allows one to work with database objects and relationships with expressive and verbose syntax!
Suppose you want a query to retrieve all posts with the title ‘laravel’,
Using Query Builder, you would do this,
DB::table('posts')->where('title', 'like', 'laravel')->get();
However, with Eloquent, you can do this,
App\Post::where('title', 'like', 'laravel')->get();
To shorten it further, you can import use App\Post; at the top of your file,
Post::where('title', 'like','laravel')->get();
To retrieve only the created date of all the posts,
Post::pluck('created_at');
A neat way to find all posts that have status of archived.
-
In Post.php
Model,public static function archived() { return static::where('status', 'archived')->get(); } -
Now in your controller or routes, you can make an easy call to find all archived posts,
Post::archived();
Find all
archived posts with the author of Paul,
-
In Post.php
Model, We use scope query. Because we prefixed it with ‘scope’ in the function name, Laravel knows to treat it as a scope query.public function scopeArchived($query, $val) { return $query::where('status', 'archived'); } -
Now, we can customize our query,
Post::archived()->where('title', 'Paul')
Beautiful.