How-to articles, tricks, and solutions about ELOQUENT

Eloquent model mass update

To update multiple records in the Eloquent ORM (Object-Relational Mapping) in Laravel, you can use the update() method on the query builder or on a model instance.

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To alias a table in a Laravel Eloquent query, you can use the as method on a DB facade.

How to delete multiple records using Laravel Eloquent

You can use the destroy() method in Laravel Eloquent to delete multiple records.

How to get all rows (soft deleted too) from a table in Laravel?

In Laravel, you can use the withTrashed() method to retrieve all the rows, including the soft deleted ones, from a table.

How to get last insert id in Eloquent ORM laravel

In Laravel, you can use the save method provided by Eloquent to insert a new record and retrieve the last insert ID.

How to Make Laravel Eloquent "IN" Query?

You can use the whereIn method on a query builder instance to create an "IN" clause for a given column and values.

How to reload/refresh model from database in Laravel?

In Laravel, you can use the refresh method on a model instance to reload the model's attributes from the database.

How to select year and month from the created_at attributes of database table in laravel 5.1?

In Laravel 5.1, you can use the selectRaw method to select the year and month from the created_at attribute of a database table.

Laravel - Eloquent or Fluent random row

In Laravel's Eloquent ORM, you can use the inRandomOrder method to retrieve a random row from the database.

Laravel 5.2 - pluck() method returns array

The pluck method is used to retrieve a list of a single column from a database table.

Laravel Check If Related Model Exists

In Laravel, you can use the exists method on a relationship to check if it has any related models.

Laravel Eloquent - Attach vs Sync

Here's an example that demonstrates the difference between using attach() and sync() in Laravel Eloquent:

Laravel Eloquent inner join with multiple conditions

To perform an inner join with multiple conditions using Laravel's Eloquent ORM, you can use the join method on a query builder instance.

Laravel Eloquent LEFT JOIN WHERE NULL

In Laravel, you can use the leftJoin method on a query builder instance to perform a left join, and then use the whereNull method to only include records where a column from the right-hand table is null:

Laravel Eloquent Sum of relation's column

You can use the sum method on an Eloquent relation to get the sum of a column's values.

Laravel: How to get last N entries from DB

You can use the latest method on a query builder instance to get the last N entries from the database.