Using Laravel Eloquent ORM

Introduction to Laravel Eloquent ORM

Introduction:

Eloquent ORM is an Object Relational Mapper that interacts with the database. It is a package separate from laravel so can be used outside the laravel too. It implements active record pattern. Laravel Eloquent ORM uses Object-Oriented models in your laravel app to connect to relational data. Eloquent models extend the Illuminate\Database\Eloquent\Model class.

Creating an Eloquent model:

Models are created in app directory by-default but we can place them anywhere from where they can be auto-loaded according to your composer.json file.

$ php artisan make:model Article

This command creates a model with name ‘Article.php’ in app directory and this will automatically use ‘Articles’ table (pluralizing model name) from the database connected. If you want to change table name we can explicitly give its name as:

class User extends Model 
{
    protected $table = 'my_articles';
}

Like table name, we can change other properties also. Here is the list:

Class Name singular of table name protected $table=’table_name’
Primary Key id protected $primaryKey=’code’
Timestamp created_at, updated_at protected $timestamp=false
Guarded Array of fields name protected $guarded=array(‘id’,’name’)
Fillable Array of fields name protected $fillable=array(‘id’,’name’)

Retrieving data using raw SQL statements

  • Select SQL Statement
  • 1.Select (Retrieving All Records)

$articles = Article::all();
This will return all the records from articles model. Sql for this is- select * from articles;

  • 2.Select (Retrieving a Record using primary key)

$articles = Article::find(1);

This will return row having primary key=1 ie- select * from articles where id=1;

  • 3.Select (Throw An Exception if finds nothing)

$articles = Article::findOrFail(1);

This will return result same as Article::find(1); if id=1 exist in table otherwise it will return ModelNotFoundException.

  • 4.Select (with where condition and aggregate function)

$articles = Article::where(‘price’, ‘>’, 100)->count();

This will return number of articles having prices greater than 100. Sql statement for this is- Select count(*) from articles where price>100;

  • 5.Select (Chunking Results)
		User::chunk(200, function($users)
				{
    					foreach ($users as $user)
    					{
       						//
   					 }
				});

This will return large records into chunks passed in first argument.

  • Insert SQL Statement
  • 1.Saving (using save() method)
				$article = new Article;
				$article>name = 'keyboard';
				$article>save();
                                $inserted_Id = $article->id;

This will create a model instance with auto-generated id and name in this. The last line will give us id of newly created row.

  • 2.Saving (using create() method)

$article = Article::create([‘name’ => ‘keyboard’]);

This will create a new row in db with id=[auto-generated id] and name=’keyboard’.

  • Update SQL Statement
  • 1.Update (update() and where() methods)
$updated_rows = Article::where(‘name’, '=', ‘keyboard’)->update(['price' => 2000]);

This will update all rows having name=’keyboard’ and change their price column value to 2000.

Update(using save() method and find() – with primary key)

$article = Article::find(1);
$article->price = ‘2000’;
$article->save();

This will find row with primary key ie id=1 and change price value for that instance and then save new value.

  • Delete SQL Statement
  • 1.Delete (delete() and where() methods)

$deleted_rows = Article::where(‘name’, ‘=’, ‘keyboard’)->delete();

This will delete all the rows which fulfil the condition specified in where clause. Like in this example – It will delete all the rows which have value ‘keyboard’ in name column.

2.Delete (another way using find()- with primary key)

				$article = Article::find(1);
				$article->delete();

This will delete row having primary key ie id=1.

3.Delete (using destroy() method- with primary key)

	
				Article::destroy(1);			or
				Article::destroy([1, 2, 3]);		or
				Article::destroy(1, 2, 3);

This will delete row(s) on the basis of how many primary keys are passed in destroy method. It can also take array as a parameter.

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *