24 C
Jaipur
Saturday, October 24, 2020

Laravel Eloquent ORM Tutorial – Linux Hint

Must read

How to watch Khabib vs Gaethje: live stream UFC 254 right now

It's Fight Island's final bout of the year, and what a clash to be ringing that final bell to. UFC 254 plays host to...

US sanctions Russian institute linked to dangerous malware – Latest News

Washington imposed sanctions on a Russian research institute tied to the development of a dangerous computer program capable of causing catastrophic industrial damage, a...

Dell: Data is fuel, 5G fabric for digital transformation: Michael Dell – Latest News

Reiterating that technology has never been more central than it is in the pandemic times, Dell Technologies chairman and CEO Michael Dell has said...

8K TV: Samsung launches The 8K Festival with QLED 8K TVs

Samsung has launched 'The 8K Festival' under which its super premium QLED 8K TVs will be available at special prices with discounts. The...

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:

A. Install a new copy of the Laravel project
B. 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 databasemigration 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 databasemigration 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.

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.

<?php

namespace App;
use IlluminateDatabaseEloquentModel;

class Manufacturer extends Model
{
    protected $fillable = [
        ‘name’, ‘address’, ‘phone’,
    ];
    public function products()
    {
        return $this->hasMany(‘AppProduct’);
    }
}

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

<?php

namespace App;
use IlluminateDatabaseEloquentModel;

class Product extends Model
{

    protected $fillable = [
        ‘name’, ‘price’,‘manufacturer_id’
    ];

    public function manufacturers()
    {
        return $this->belongsTo(‘AppManufacturer’);
    }
}

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 routesweb.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 routesweb.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 “<b>Manufacturer: $manu->name</b><br/>”;
        foreach ($products as $pro)
        {
            echo “<p style=”padding-left:20px”>Product Name:$pro->name</p>”;
            echo “<p style=”padding-left:20px”>Product Price:$pro->price</p><br/>”;
        }
    }

}

Add the following route in the routesweb.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:<br/>”;
    echo “<p style=”padding-left:20px”>Product Name:$product->name</p>”;
    echo “<p style=”padding-left:20px”>Product Price:$product->price</p><br/>”;
   
    $product->name = ‘Walton Blender’;
    $product->price = 1000;
    $product->save();

    echo “Product details after update:<br/>”;
    echo “<p style=”padding-left:20px”>Product Name:$product->name</p>”;
    echo “<p style=”padding-left:20px”>Product Price:$product->price</p><br/>”;

}

Add the following route in the routesweb.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 routesweb.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

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.

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article

How to watch Khabib vs Gaethje: live stream UFC 254 right now

It's Fight Island's final bout of the year, and what a clash to be ringing that final bell to. UFC 254 plays host to...

US sanctions Russian institute linked to dangerous malware – Latest News

Washington imposed sanctions on a Russian research institute tied to the development of a dangerous computer program capable of causing catastrophic industrial damage, a...

Dell: Data is fuel, 5G fabric for digital transformation: Michael Dell – Latest News

Reiterating that technology has never been more central than it is in the pandemic times, Dell Technologies chairman and CEO Michael Dell has said...

8K TV: Samsung launches The 8K Festival with QLED 8K TVs

Samsung has launched 'The 8K Festival' under which its super premium QLED 8K TVs will be available at special prices with discounts. The...