Laravel Eloquent(ORM) – Interact With Your Database

laravel eloquent relation

Laravel Eloquent

In this article, you have learned about creating relations in Laravel Eloquent and inserting data into the database. I hope this article will be useful for you.

Introduction:

Eloquent is a relational manager in the Laravel framework. This is an operational mapper that creates a relationship with the database.
  • In PHP we create a connection with the database whose query we interact with the table.
    But Laravel makes this thing very easy. In Laravel, there is ORM (object-relational mapper) which interacts with database tables with the help of a model.
  • The first thing to do in Laravel is to connect to the database. To connect to the database, we give the name of the database in the .env file.

Laravel Eloquent Model

The Eloquent model is a file in Laravel which contains many such properties and keys that interact with the table. Model is an important part of Laravel Eloquent(Object-relational mapper)

The model is created with the make:model command and then the keys and properties are defined by going to the file directory.

With examples, let us know what is Laravel Eloquent and how does it work in Laravel?

Table Of Content

  • Create a connection with the database
  • Create Eloquent Model
  • Create a Migration(table)
  • Create view file
  • Create controller
  • Create Route
#Database – Create a connection with the database in the .env file
For example: –
DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=laravel

DB_USERNAME=root

DB_PASSWORD=
#Create an eloquent model – Each table has a unique model. Whenever we create a migration(table), we need a model to create data in it.
Both model and migration (table) can be created together with a single command and also with different commands
Create model and migration with one command :
php artisan make:model ModelName  –m
-m  makes migration and with the above command, the name of the migration is saved as the plural of the model name in the database.

app\Models\Customer.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Database\Eloquent\Model;

class Student extends Model

{

    use HasFactory;

    protected $table = 'students';

}

The table can also be interacted with using the table property in the model.

Protected $table = ‘table_name’;

Create eloquent model with single command :
php artisan make:model ModelName
Create migration(table) with single command :
php rtisan make:migration migration_name
#Create Migration (table): – database\migrations
public function up()

    {

        Schema::create('students', function (Blueprint $table) {

            $table->id();

            $table->string('first_name');

            $table->string('last_name');

            $table->string('email');

            $table->integer('phone_number');

            $table->text('address');

            $table->text('image');

            $table->timestamps();

        });

    }
#View file – resources\views\index.blade.php
<!DOCTYPE html>

<html>

<head>

    <meta name="csrf-token" content="{{ csrf_token() }}">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <title>Student Form</title>

</head>

<body>

    <div class="container mt-4">

        <div class="card">

            <div class="card-header text-center font-weight-bold">

                Student Form Data Save Into Database

            </div>

            <div class="card-body">

                <form method="post" action="{{route('store')}}" enctype="multipart/form-data">

                    @csrf

                    <div class="row">

                        <div class="col-6">

                            <label for="firstName">First Name</label>

                            <input type="text" name="first_name" placeholder="Enter Your First Name"

                                class="form-control">

                        </div>

                        <div class="col-6">

                            <label for="LastName">Last Name</label>

                            <input type="text" name="last_name" placeholder="Enter Your Last Name" class="form-control"

                                required="">

                        </div>

                    </div>

                    <div class="row">

                        <div class="col-6">

                            <label for="email">Email</label>

                            <input type="text" name="email" placeholder="Enter Your Email" class="form-control"

                                required="">

                        </div>

                        <div class="col-6">

                            <label for="phone_number">Phone Number</label>

                            <input type="text" name="phone_number" placeholder="Enter Your Phone Number"

                                class="form-control" required="">

                        </div>

                    </div>

                    <div class="form-group">

                        <label for="address">Address</label>

                        <input type="text" name="address" placeholder="Enter Your Address" class="form-control"

                            required="">

                    </div>

                    <div class="form-group">

                        <label for="address">Image</label>

                        <input type="file" name="image" placeholder="Enter Your image" class="form-control" required="">

                    </div>

                    <button type="submit" class="btn btn-primary btn-block">Submit</button>

                </form>

            </div>

        </div>

    </div>

</body>

</html>
Form view

laravel eloquent form

#Insert Record into database after create model and migration
app\Http\Controllers\StudentController.php
    public function store(Request $request)

    {
        $request->validate([
            ‘first_name’  => ‘required’,
            ‘last_name’   => ‘required’,
            ’email’     => ‘required’,
            ‘phone_number’ => ‘required’,
            ‘address’    => ‘required’,
            ‘image’     => ‘required’,
        ]);
        // Image upload $image = $request->file(‘image’);
        $imageName = time() . ‘.’ . $image->extension();
        $imagePath = storage_path(‘app/public’) . ‘/student-image/’;
        $image->move($imagePath, $imageName);
        Student::create([
            ‘first_name’  => $request->first_name,
            ‘last_name’  => $request->last_name,
            ’email’    => $request->email,
            ‘phone_number’ => $request->phone_number,
            ‘address’   => $request->address,
            ‘image’   => ‘/student-image/’ . $imageName
        ]);
        return redirect()->route(‘index’)->with(
            ‘success’,
            “student data created successfully”
        );
}
#Create routes
Route::get('/', function () {

    return view('index');

});

Route::get('/', 'StudentController@index')->name('index');

Route::post('/', 'StudentController@store')->name('store');
Output :
laravel eloquent database
Retrieving data from table
public function index()

    {

        $students = Student::all();

        return view('index', compact('students'));

    }

Retrieving A Record By Primary Key

public function index()

    {

        $students = Student::find(1);

        return view('index', compact('students'));

    }

I hope in this article you have come to know about what is Laravel Eloquent

Leave a Comment

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