Eloquent ORM - Eloquent Builder

It provides a convenient, fluent interface to creating and running database queries

 

Using dynamic condition under auth check and request query

$query = Post::query(); if ( Auth::check() ) { $category = Category::pluck('id')->toArray(); //dd($category); $categories = Category::get(); $recentPosts = Post::take(8)->orderBy( 'created_at', 'desc'...


Using "with" in eloquent query

This is generally used for eager loading for associated model in the main model which solves N+1 query problem.So, It...


Getting last inserted id

Following approach can be done to get the last inserted id of a model. Step 01: Using mass assignment in...


Selecting last row of a table

It can be done using latest() method. Here function parameter can be empty or it can have field name upon...


How to write multiple AND queries inside OR query using closure

Sometimes it requires to setup eloquent builder to create queries which has multiple ands inside a or query. For example,...


Returning rows where a column is between two values

If we were to get posts between ids of 5 and 8 including both of these values we can use...


Selecting rows if they are NULL or NOT NULL

Following snippet will help you to get rows from a table which are either NULL or NOT NULL // rows...


How to use whereHas to retrieve rows based on existence of relationship

whereHas() method is used to add further query constraints on top of has() method. Suppose,  there is user hasMany relationship...


Using withAggregates in Eloquent way

Suppose Post hasMany Rating and there is a field rating in ratings table. For this following snippet can be used...


Selecting fields inside eager loading method "with"

Suppose there is a relation Post belongsTo User. If we are retrieving posts with associated user relation, we can use...