The complete Lavarel framework development tutorial

Powered by Blogger.

Sunday 14 August 2016

Eloquent ORM - Laravel Models Tutorial



As we all know that Laravel follows MVC (Model View Controller) architectural pattern. In this tutorial we will learn about Laravel Models called Eloquent ORM. The Eloquent ORM are used to interact with our database. Each table of the database needs a model for interaction. Using the Laravel Models we can perform all the CRUD operations. The Eloquent ORM provides a simple and beautiful implementation for interacting with our database.

Before learning about Laravel models, You can have a guide about laravel views and controllers.

Learn about Laravel Views- Laravel Views Tutorial- Creating a View

Learn about Laravel Controllers- HTTP Controllers- Laravel Controllers Tutorial

Laravel Models - Basics


Creating and Configuring Database


The very first thing we need is to create a database and a table inside the database. So, do it with whatever you use to create a database. Here, I'm using phpmyadmin.

I've created a database named store and a table named customers with columns id, name, email, created_at and updated_at. Create your own database and insert two or more row for a practical example.

Now you need to configure your database to your laravel web app. Open .env file located a the root folder of your web app and configure your database by changing some field like-

  1. DB_CONNECTION=mysql

  2. DB_HOST=127.0.0.1

  3. DB_PORT=3306

  4. DB_DATABASE=store

  5. DB_USERNAME=root

  6. DB_PASSWORD=root

Configure these according to your database configuration.

Creating a Model


For each table in our database we need to create a model. This model are for interacting with our tables. You can simply run this command to create a model.
php artisan make:model Customer

A new class will be created inside your app folder.
While creating a model, we don't need to specify the name of the table. The Laravel Models uses Snake Case plural name of the class as a table name. For example- Here I've created Customer model to interact with customers table of our database. You can also explicitly specify the name of the table by defining table property inside your class.
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    //
 protected $table = 'new_customers';
}


A quick Example


Let's have an quick example of Laravel Models. I'm going to  create a route that will display the details of customer whose id is 1.

Open your routes.php file located at apps -> Http folder and create a new route like this.
Route::get('customer', function () {
 $customer = App\Customer::find(1);
 echo $customer->name . '<br />';
 echo $customer->email;
});

Open the route to your web browser- http://localhost/model/public/customer (Model is the name of my project, replace it with your project).

This route will show the name and email of the customer whose id is 1.

Pass arguments to the route


We can also pass arguments to the route, so that we can directly access the customer by giving the id at the url.
Route::get('customer/{id}', function ($id) {
 $customer = App\Customer::find($id);
 echo $customer->name . '<br />';
 echo $customer->email;
});

Now try to access different customers with their id.

Customer with id 1- http://localhost/model/public/customer/1

Customer with id 2- http://localhost/model/public/customer/2

and so on...

Using where clause


Route::get('customer', function () {
 $customer = App\Customer::where('name', "Sunny Kumar")->first();
 echo $customer->id . '<br />';
 echo $customer->name . '<br />';
 echo $customer->email;
});

The first() function is used to retrieve only first occurrence. We can use get() instead of first() to get all the records and can display all the records using foreach loop. This will be covered later in this Laravel Models tutorial.

Laravel Models - Performing CRUD operations


Using Eloquent ORM model, we can easily perform CRUD (Create, Read, Update, Delete) operations. The Eloquent ORM provides very simple, easy and beautiful implementation for performing all the operations.

Creating a new record


To insert records to our database, we need to create a instance of model, set all the values or attributes and finally call the save() method.

Let's try to understand it using an example. The first thing we will do is will create a html form into our view.

So create a view (say newcustomer.blade.php) and inside the view create a HTML form with two fields name and email.
<form method="POST" action="newcustomer">
 <label for="name">Name</label>
 <input type="text" name="name">
 <label for="name">Email</label>
 <input type="text" name="email">
 <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
 <input type="submit">
</form>

Also create a controller that will have the code to store customer data to our database.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

class CustomerController extends Controller
{
    //
 public function newcustomer(Request $request){
  $customer = new \App\Customer;
  $customer->name = $request->name;
  $customer->email = $request->email;
  
  $customer->save();
 }
}

Inside the CustomerController class, I've created a function called newcustomer. The function contains a instance of model Customer. And then we are setting the attributes and finally save the data to our database using the save() method.
Here you should notice that we didn't set the attributes for created_at and updated_at columns. The reason is these attributes are automatically being managed by laravel. We can also disable this by setting the $timestamp property to false to our model class.
class Customer extends Model
{
    //
 public $timestamps = false;
}


And finally two routes. One for displaying the view that contains our HTML form and another a POST route that calls the newcustomer() method from CustomerController class.
Route::get('/', function () {
    return view('newcustomer');
});

Route::post('newcustomer', 'CustomerController@newcustomer');

The newcustomer route will be accessed from the action property of the HTML form.

Retrieving Records


Retrieving all records


To retrieve all records from a table all() method is used. Simply create a method on the controller.
public function listCustomers(){
 $customers = \App\Customer::all();
 return view('customers', ['customers'=> $customers]);
}

To print the records on the customer view, we can use a foreach loop.
<table>
 @foreach($customers as $customer)
  <tr>
  <td>{{$customer->name}}</td>
  <td>{{$customer->email}}</td>
  </tr>
 @endforeach
</table>

And finally create a route to call the controller method.
Route::get('customers', 'CustomerController@listCustomers');

Using where clause


public function listCustomers(){
 $customers = \App\Customer::where('id', 1)->get();
 return view('customers', ['customers'=> $customers]);
}

Using first() method


Whenever we use where clause, it returns all the records that satisfies the condition. We can retrieve the first record from a where clause by using first() method.
public function listCustomers(){
 $customers = \App\Customer::where('role', 'admin')->first();
 return view('customers', ['customers'=> $customers]);
}

Adding Additional Constraints


public function listCustomers(){
 $customers = \App\Customer::where('role', 'admin')->orderBy('name', 'desc')->get();
 return view('customers', ['customers'=> $customers]);
}

Retrieving Aggregates


$count = \App\Customer::where('role', 'admin')->count();

$max = \App\Customer::where('role', 'admin')->max('credits');

Updating Records


Remember while creating a new record, we were using the save() method. The save() method can also be used for updating a record in Laravel Models. What we need to do is just retrieve the record, set the attributes which we want to change or update and call the save() method.

Let's have an example of how we update record in Laravel models. Here I'm going to create a view in which users have to enter the id of a customer and new email address to change email id of the corresponding customer.

So, first create a view
<!DOCTYPE html>
<html lang="en">
<body>
 <form method="POST" action="updatecustomer">
  <label for="id">ID</label>
  <input type="text" name="id">
  <label for="email">New Email</label>
  <input type="text" name="email">
  <input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
  <input type="submit">
 </form>
</body>
</html>

Two routes. First get route to display view and second post route to update record.
Route::get('updatecustomer', function(){
 return view('updatecustomer');
});
Route::post('updatecustomer', 'CustomerController@updateCustomer');

And a function to the controller.
public function updateCustomer(Request $request){
 $customer = \App\Customer::find($request->id);
 $customer->email = $request->email;
 $customer->save();
}

While updating a record in Laravel Models, we don't need to set attribute for updated_at column as it is being managed by Laravel.

Deleting Records


In Laravel Models we can easily delete a record by calling delete() method. Simply, retrieve the record that you want to delete and call the delete() method.
$customer = \App\Customer::find(1);
$customer->delete();

Conclusion


So, I'm ending up with Laravel Models tutorial. If you stuck anywhere you can use comment box below, I'll be there with and solve the problem together.

And don't forget to share the 'Eloquent ORM - Laravel Models Tutorial' to help other needy also.

0 comments:

Post a Comment