laravel

Laravel Eloquent ORM Tutorial

Laravel Eloquent ORM Tutorial
Eloquent ORM (Object Relation Mapper) is easy to use for users who know how to use objects in PHP. The ORM is an important feature of the Laravel framework, considered a powerful and expensive feature of Laravel. The ORM works with database objects and is used to make relationships with database tables. Each table of the database is mapped with a particular eloquent model. The model object contains various methods to retrieve and update data from the database table. Eloquent ORM can be used with multiple databases by implementing ActiveMethod. This feature makes database-related tasks, such as defining relationships, simpler by defining the database tables. This tutorial explains how to apply Laravel Eloquent ORM in your Laravel projects.

Prerequisites

Before starting this tutorial, you must perform the following tasks:

  1. Install a new copy of the Laravel project
  2. Make the database connection

Create Tables

To complete the steps of the tutorial, you must create two tables in the database. These are the manufacturer's table and the products table. The relationship between these two tables will be one to many, respectively. Run the following command to create the migration file for creating the structure of manufacturers table.

$ php artisan make:migration create_manufacturer_table

Open the migration file from database\migration folder and modify the up() method with the following code. The table will contain six fields: ID, name, address, phone, created_at, and updated_at.

public function up()

Schema::create('manufacturers', function (Blueprint $table)
$table->id();
$table->string('name')->unique();
$table->text('address');
$table->string('phone');
$table->timestamps();
);

Run the following command to create a migration file for creating the structures of the products table.

$ php artisan make:migration create_product_table

Open the migration file from the database\migration folder and modify the up() method with the following code. The table will contain seven fields: ID, name, price, manufacturer_id, created_at, and updated_at. Here, manufacture_id is a foreign key for the products table.

public function up()

Schema::create('products', function (Blueprint $table)
$table->id();
$table->string('name')->unique();
$table->decimal('price', 10, 2);
$table->bigInteger('manufacturer_id')->unsigned();
$table->foreign('manufacturer_id')->references('id')->on('manufacturers');
$table->timestamps();
);

Run the following migrate command to create the tables in the database.

$ php artisan migrate

Create Models

You must also create two models, named Manufacturer and Product, for the previously created tables. Run the following command to create the Manufacturer model.

$ php artisan make:model Manufacturer

Open the model from the app folder and modify the code with the following code. $fillable is used to define the mandatory fields of the manufacture table. The products() method is used to set the relation type with the products table.

namespace App;
use Illuminate\Database\Eloquent\Model;
class Manufacturer extends Model

protected $fillable = [
'name', 'address', 'phone',
];
public function products()

return $this->hasMany('App\Product');

Run the following command to create the Product model.

Open the model from the app folder and modify the code with the following code. $fillable is used to define the mandatory fields of the products table. The manufacturers() method is used to set the relation type with the manufactures table.

$ php artisan make:model Product
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model

protected $fillable = [
'name', 'price','manufacturer_id'
];
public function manufacturers()

return $this->belongsTo('App\Manufacturer');

Create Controllers

Run the following commands to create ManuController and ProductController.

$ php artisan make:controller ManuController
$ php artisan make:controller ProductController

CRUD operations using Eloquent ORM

The CRUD operations are shown below by first adding methods to these two controllers.

Inserting Data

Manufacturer Table

Add the Manufacturer model at the top of the ManuController. Next, add the following code inside the ManuController model to insert two records into the manufactures table.

public function create_data()

Manufacturer::create([
'name' => 'ABC Trade',
'address' => '34, Mirpur, Dhaka',
'phone' => '01878562323'
]);
Manufacturer::create([
'name' => 'Rahim Afroze',
'address' => '123, Dhanmondi, Dhaka',
'phone' => '01878562900'
]);
echo "Manufacturer data inserted";

Add the following route in the routes\web.php file to execute the create_data() method.

Route::get('manu', '[email protected]_data');

The following output will appear after entering the URL below in the browser.

http://localhost:8000/manu

Product Table

Add the Product model at the top of the ProductController. Next, add the following code inside the ProductController to insert three records into the products table.

public function index()

Product::create([
'name' => 'TV 32 Inche',
'price' => 10000,
'manufacturer_id' => 1
]);
Product::create([
'name' => 'Walton Fridge',
'price' => 20000,
'manufacturer_id' => 1
]);
Product::create([
'name' => 'IPS 7832',
'price' => 25000,
'manufacturer_id' => 2
]);
echo "Product data inserted";

Add the following route in the routes\web.php file to execute the index() method.

Route::get('product', '[email protected]');

The following output will appear after entering the URL below in the browser.

http://localhost:8000/product

Select Data

Add the following method inside the ManuController to retrieve all records of the manufactures table and the related records of the products table.

public function select_data()

$manufacturers= Manufacturer::all();
foreach ($manufacturers as $manu)
$products= Product::where('manufacturer_id', $manu->id)->get();
echo "Manufacturer: $manu->name
";
foreach ($products as $pro)

echo "

Product Name:$pro->name

";
echo "

Product Price:$pro->price


";


Add the following route in the routes\web.php file to execute the select_data() method.

Route::get('product_detail', '[email protected]_data');

The following output will appear after entering the URL below in the browser.

http://localhost:8000/product_detail

Update Data

Add the following method inside the ManuController to update the record of the products table that contains id value 2.

public function update_data()

$product= Product::find(2);
echo "Product details before update:
";
echo "

Product Name:$product->name

";
echo "

Product Price:$product->price


";
$product->name = 'Walton Blender';
$product->price = 1000;
$product->save();
echo "Product details after update:
";
echo "

Product Name:$product->name

";
echo "

Product Price:$product->price


";

Add the following route in the routes\web.php file to execute the update_data() method.

Route::get('update_data', '[email protected]_data');

The following output will appear after entering the URL below in the browser.

http://localhost:8000/update_data

Delete Data

Add the following method inside the ManuController to delete multiple records from the products table and a single record from the manufacturers table.

public function delete_data()
//Delete multiple data
Product::destroy([1, 2]);
//Delete single data
Manufacturer::destroy(1);
echo "Data are deleted.";

Add the following route in the routes\web.php file to execute the delete_data() method.

Route::get('delete_data', '[email protected]_data');

The following output will appear after entering the URL below in the browser.

http://localhost:8000/delete_data

Video Tutorial

Conclusion

This tutorial showed you how to create relationships between tables and how to implement CRUD operations using Eloquent ORM. Even new Laravel users will be able to understand some basic uses of Eloquent OPM after reading this tutorial.

Kuinka käyttää GameConqueror-huijausmoottoria Linuxissa
Artikkelissa on opas GameConqueror-huijausmoottorin käytöstä Linuxissa. Monet Windows-pelejä pelaavat käyttäjät käyttävät "Cheat Engine" -sovellusta m...
Parhaat pelikonsoliemulaattorit Linuxille
Tässä artikkelissa luetellaan suositut pelikonsolin emulointiohjelmistot, jotka ovat saatavana Linuxille. Emulointi on ohjelmistojen yhteensopivuusker...
Best Linux Distros for Gaming in 2021
The Linux operating system has come a long way from its original, simple, server-based look. This OS has immensely improved in recent years and has no...