Home >>Laravel Tutorial >Laravel Eloquent

Laravel Eloquent

Laravel Eloquent

Eloquent ORM (object-relational mapping) is basically an advanced method of PHP implementation of the active record pattern that is known to provide the time internal methods for enforcing constraints on the relationships between the database objects at the same time.

 

Developers and programmers can generally work in the Laravel Eloquent with multiple databases in a very efficient way just by using an Active Method implementation.

In order to fully appreciate the utility of the Laravel Eloquent ORM one has to understand the ecosystem of it and that is a must.

This Laravel Eloquent Tutorial will help you in understanding the concept from a deeper level and will explain everything about the topic.

Working with database with a implementation of simple and beautiful active record. Database table has a corresponding Model which is used to interact with that table. Queries for data can be made using Model and new insertion of records into table are also made with model. Make sure to configure database connetions in

config/database.php

(check out laravel databse topic)

Defining Model

Models are defined inside app folder but it can be placed anywhere that can be autoloaded according to composer.json file and all eloquent model extend Illuminate\Database\Eloquent\Model class.

Commands for creating models are shown below:

php artisan make:model Feed
Model In Laravel

Database Migration

If migrations are needed while creating model -m or --migration option can be used as shown below:

php artisan make:model Feed --migration

php artisan make:model Feed -m
Model In Laravel

Structure of Feed Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
    //
}

Table Names:

We do not tell Eloquent which table to use for feed model. By 'Snake Case' convention it is automatically set to plural of the class. And in this case Feed Model will assume to store data in feeds table, but custom table can be created by defining table property as shown below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Feed extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'my_feeds';
}

Primary Keys

Eloquent Model assumes that each table has a primary key associated with it named as id. You can change this by overriding the convention by using protected $primaryKey the syntax shown below:

<?php  
  
namespace App;  
  
use Illuminate\Database\Eloquent\Model;  
  
class Feed extends Model  
{  
    /** 
     * The primary key associated with the table. 
     * 
     * @var string 
     */  
    protected $primaryKey = 'feed_id';  
}  
?>

In Addition Eloquent assumes that primary key is incremented integer value i.e. by default primary key will cast int value. Which can be changed by making incrementation false and using int as a primary key.

Shown below the method of making non-incremented and non-numeric primary key.

<?php

class Feed extends Model
{
    /**
     * Indicates if the IDs are auto-incrementing.
     *
     * @var bool
     */
    public $incrementing = false;
	
	/**
     * The "type" of the auto-incrementing ID.
     *
     * @var string
     */
    protected $keyType = 'string';
}

In the above code $incrementing boolean is used for making incrementation false and $keyType is used to set the primary key other than int.

Retrieving Data

Reading data with eloquent is easier as reading with the old sql qyuery convention. Eloquent model is a powerful query builder allow you to fluently query DB table associated with model. Let's add some attributes to our model.

namespace App;  
use Illuminate\Database\Eloquent\Model;  
class Feed extends Model  
{  
	protected $table='feeds';  
	protected $primaryKey='id';  
}  

Define route in web.php file to retrieve data

<?php  
use App\Feed;  
Route::get('/retrieve',function(){  
$feeds=Feed::all();  
foreach($feeds as $feed)  
{  
  echo $feed->name;  
  echo '<br>';  
}  
});  

all() method reads all the records from the DB, and foreach loop used to read the name of all the rows available in the DB.

Output:
Model In Laravel
Model In Laravel

Additonal Query constraints can be added as shown below:

find() method

This method helps in finding the particular record as shown below.

Route::get('/find',function(){  
$feeds=Feed::find(2);  
return $feeds->name;  
});  
Output:
Model In Laravel

first() method

It is used to retrieves the data of single row.

Route::get('/first',function(){  
$feeds=Feed::where('id',1)->first();  
return $feeds;  
});  
Output:
Model In Laravel

value() method

It is used to read the value of a column directly.

Route::get('/value',function(){  
$feeds=Feed::where('id',1)->value('password');  
return $feeds;  
});  
Output:
Model In Laravel

Data Insertion

Below shown an example to insert data in to DB.

Route::get('/insert',function(){  
$feed=new Feed;  
$feed->name='Three Feed';  
$feed->password='three';  
$feed->save();  
}); 
Output:
Model In Laravel

Data Updation

Records can also be updated using save method. Shown below the example for updating data one.

Route::get('/update',function(){  
$feed=Feed::find(1);  
$feed->name='First Feed';  
$feed->password='First';  
$feed->save();  
});  
Output:
Model In Laravel

Update using eloquent

Here is the Example of updating data with Eloquent shown below.

Route::get('/updateEloquent',function(){  
Feed::where('id',2)->update(['name'=>'Second feed','password'=>'Second']);  
});   
Output:
Model In Laravel

Data Deletion

We can directly use delete() method available in the eloquent model class to delete the data.

Example shown below shows how to delete data.

Route::get('/delete',function(){  
$feed=Feed::find(3);  
$feed->delete();  
});  
Output:
Model In Laravel

Note :We have destroy() method also for deleting.

Route::get('/destroy',function(){  
Feed::destroy(2);  
});  

OR

Route::get('/destroy',function(){  
Feed::destroy([1,2]);  
});  

Or by using simple query.

Route::get('/delete1',function(){  
Feed::where('id',5)->delete();  
});  

And this also includes the CRUD operations in laravel by Eloquent Model. These simple CRUD methods are easy to use and implement in projects by fast EloquentModel technique.


No Sidebar ads