Eloquent ORM queries in Laravel


Posted on 21 Jan 16 by Vickey

The Eloquent ORM is simple ActiveRecord implementation for working with database. For interact with 'database tables' we use a corresponding "Model"

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable

Here i did not tell which table will be used by this model because as specified in Laravel Eloquent the table name lower-case, plural and model name will be singular for example if model name is User the table name will be users

Retrieve records from users table

For retrieve all record from table users we will use User model because the corresponding table of User is users

$usersRecord = User::all();

Retrieve record by using primary key

$user = User::find($id);

Use where conditions

$usersRecords = User::where('age', '>', 30)->take(20)->get();

Count records

$noOfRows = User::where('age', '>', 30)->count();

Save record in databse

By using 'Eloquent ORM' we can insert and update record in database

Insert new record in database

$user = new User;

$user->name = 'abc';


Update record in database

$user = User::find(1);

$user->email = 'abc@gmail.com';


Delete records

Delete records by using primary keys


User::destroy(array(1, 2, 3));

User::destroy(1, 2, 3);

If we want to delete more than one record we can use primary keys comma seperated or in array

Delete record by using where conditions

$affectedIds = User::where('age', '>', 30)->delete();

These are some basic 'Eloquent ORM' queries in laravel. If this content help you please leave a comments


If this post help you reduce time to develop, you can help me to maintain this website :)