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:

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 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.

<?php

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


<?php

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', 'ManuController@create_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', 'ProductController@index');

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 routes\web.php file to execute the select_data() method.

Route::get('product_detail', 'ManuController@select_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 routes\web.php file to execute the update_data() method.

Route::get('update_data', 'ManuController@update_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', 'ManuController@delete_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.



from Linux Hint https://ift.tt/36hjhqs

Post a Comment

0 Comments