I write this blog based on laravel version 5.4 But all of its functions are still supported laravel 5.x – 7.x

What is Laravel Eloquent

Laravel is one of mostly known MVC based PHP framework. As we know MVC based frameworks have a simple way of querying data to and from the table in the database. Like these frameworks, Also laravel has its own way of querying data using Eloquent ORM (Object-Relational Mapping). Eloquent ORM provides an extremely easy way to communicate with a database for any kind of CRUD operations. While using Eloquent ORM There is no need to write SQL queries. Just define database tables and relations between them, and leave the rest for Eloquent ORM.

Creating Model

To start diving into eloquent ORM, first of all we will see how to start creating a model. In order to create a model open CMD and navigate to your project folder. If you are using VS Code you can get terminal right inside vs code from the upper tabs. Open it and the write the following command.

php artisan make:model User

After running this command you will get this message.

Model created successfully
Model created successfully

As the result, One file will be created inside app directory with the name User.php. Its content will look like…

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //
}

After creating a Model the next step will be,… Yes! as you are thinking it is about How can you make a CRUD operation.

Where should we write these CRUD operations?

If you are familiar with MVC based frameworks you know where to implement these CRUD operations. But if you are a new start up with MVC framework you will write these commands on a controller. Each model can have their own controllers. To create controller for our the User Model run the following model.

php artisan make:controller UserController

as a result you will find this message

Controller created successfully
Controller created successfully

It’s file content looks like as follows

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
   //
}

Let’s see them one by one.

First lets imagine that our table has 3 columns (name,email,password).

Create/Insert

Once you have created your model Inserting a data is the simplest task.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
       // C
  public function create() { 
    $data = array(
      'name' => 'Luckyman',
      'email'=>'zluckyza@gmail.com', 
      'password'=>bcrypt('123456'), 
    ); 
    User::create($data);   
    echo "Create Successful!";   
  } 
}  

don’t forget to import the User model around the beginning of the file under the namespace.

namespace App\Http\Controllers;
 use App\User;

Read/Retrieve

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  // R
  public function index() { 
    $users = User::all();
    return view(compact('users'));  
  }
  //Retrieving using where clause
  public function readById($id) { 
     $users = User::all()->where('id',$id);
     return view(compact('users'));  
  }
}

Update

In order to update a record first we should retrieve it from database since we are going to update an existing database. To retrieve the record we will use find() function. The code to update a will be as follows.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  // U
  public function update() { 
    $user = User::find(1);
    $user->name = 'Luckyman Zeinu';
    $user->save();
    echo "Update Successful!";   
  } 
}  

Delete

Here we will use the find() function to retrieve the row that we want to delete from the database. The function find() will accept one parameter Id which is the primary key of the table. And finally to remove the data we will use the delete() function.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
  // D
  public function delete() { 
    $user = User::find(1); 
    $user->delete();
    echo "Delete Successful!";   
  } 
}  

Below I have combined all of them in to one place

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\User;

class UserController extends Controller
{
       // C
  public function create() { 
    $data = array(
     'name' => 'Luckyman',
     'email'=>'zluckyza@gmail.com', 
     'password'=>bcrypt('123456'), 
    ); 
    User::create($data);   
    echo "Create Successful!";   
 } 
 // Read
 public function index() { 
   $users = User::all();
   return view(compact('users'));  
 }
 //Retrieving using where clause
 public function readById($id) { 
   $users = User::all()->where('id',$id);
   return view(compact('users'));  
 }
 // U
public function update() { 
  $user = User::find(1);
  $user->name = 'Luckyman Zeinu';
  $user->save();
  echo "Update Successful!";   
} 
 // D
 public function delete() { 
   $user = User::find(1); 
   $user->delete();
   echo "Delete Successful!";   
 } 
} 

The above content is about model and controller part of laravel MVC framework. Now let’s create a view for the above controller.

 Create a view with the name ‘user.blade.php’ in the ‘resources/views’ directory and paste the below code in that file.

<!DOCTYPE html> 
<html> 
<head> 
	<title>Easy Code</title> 
 
</head> 
<body> 

	<h2>Users list</h2> 
	<table>
          <thead>
            <th>Name</th>
            <th>Email</th>
          </thead>
          <tbody>
            @foreach($users as $user) 
		<td>{{ $user->name}}</td> 

		<td>{{ $user->email}}</td> 
	    @endforeach 
          </tbody>
        </table> 
	</ol> 

</body> 
</html> 

The next is to define these routes in web.php file which is found in the ‘/routes’ directory. Because, if you don’t define your routes laravel will not identify your request as valid and it returns with error 404(resource Not Found). You can read more about routing in laravel here.

Route::get('/insert', 'UserController@create'); 
Route::get('/', 'UserController@index'); 
Route::get('/update', 'UserController@update'); Route::get('/delete', 'UserController@delete');

Done!

Now run your project.

Please don’t forget to share us your feelings in the comment section.

Reference: Laravel Official Documentation


0 Comments

Leave a Reply

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