Chose Language:
Author: Admin/Publisher |not checked

Laravel Eloquent

This Post is an introduction to Laravel Eloquent. You must read Laravel Eloquent and Query Builder official documentation to learn the best way in how to interact with your database. This is just a fast glace for beginners.

Post content:

¿ What is an ORM ?

Is programming technique for converting data between incompatible type systems using object-oriented programming languages

Wikipedia

Eloquent uses some patterns like Active Record pattern.

Active record -Its a pattern design created with the objective of using objects to represent data and its relations(table relations) in relational databases.

The ORM permit to us change our database, for example our client want a base in MySQL, but change the idea and now wants a different DBMS for example PostgreSQL.

Our querys in Laravel are the same and migrations are the same we have to change our database and Laravel do the rest for us.

Eloquent

The use of Laravel ORM(Object–relational mapper) start from our model creation, I know that’s not written on Laravel official documentation. Without a model you couldn’t use Eloquent.

using Eloquent

First we have to create a model, model are the easiest way to relate with the database(see models in Laravel).

You will see a lot of words in Spanish that is because this is a post translated to English, and images are in Spanish. If something mismatch or its not work correctly you can inbox me on twitter

Suppose we have a model Cliente, gonna create the client model to use it in the example.

project-folder
php artisan make:model Cliente

Lets create a Cliente table in our database(example) with the following datatypes

  • id(auto-incremental int)
  • nombre( string)[name]
  • apellido(string)[surname]
  • telefono(string 17) – 15 is the max that use thelephones so17 is ok.[phone]
  • direccion(string)[address]

In this case cause its an example Ihave made it via phpmyadmin but is convinient to create tables with migrations, this ones permits you to not totally depend in the database becouse you could creates all the tables via PHP.

This table has not a timestamp and id is a key, in this case we have to write in our model that has no timestamp and id is guarded.

Remember: if you use guarded do not use fillable and viceverse
app/Client.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Cliente extends Model
{
    public $timestamps = false;
    protected $guarded = ["id"];
} 

Insert some data to interact with:

la tabla clientes

We will need some routes, so add the routes depending in your laravel version 8:

To check your laravel version you can use the following command:

php artisan --version

depending on your version use one of the following code fragments:

versiones anteriores a laravel 8 routes/web.php
Route::get('cliente/save',"ClienteController@save");
Route::get('cliente/show',"ClienteController@show");
Route::get('cliente/update',"ClienteController@update");
Route::get('cliente/delete',"ClienteController@delete");
Route::get('cliente/update2',"ClienteController@update2");
Laravel 8 o superior routes/web.php
use App\Http\Controllers\ClienteController;// ponlo junto a las otras importacioens
Route::get('cliente/save',[ClienteController::class,'save']);
Route::get('cliente/show',[ClienteController::class,'show']);
Route::get('cliente/update',[ClienteController::class,'update']);
Route::get('cliente/delete',[ClienteController::class,'delete']);
Route::get('cliente/update2',[ClienteController::class,'update2']);

Getting Data

I going to create a controller ClienteController to use eloquent. Eloquent have a lots of methods that you can use (Eloquent collections). In the following examples we will use some of these methods to select data from cliente(client) table.

When we use all(), we will get all clients on the table clientes(clients), this method is not the most used, but is a good starting point, generally we use paginate() instead.

With paginate you could create the pagination of a page. For example we show 25 items at the page and next 25 in next page.

We could use all() for a list for example sites in your city. Ok lets go with the example:

app/Http/Controllers/ClientController.php[fragment]
public function show()
{
        $clientes = \App\Cliente::all(); 
        foreach($clientes as $cliente){
            echo $cliente->nombre."</br>";        
        }       
}

Something that you probably need in a project is showing something by id. Lets get the cliente(client) with id = 1. I going to modify show to do this this time.

app/Http/Controllers/ClientController.php[fragment]
public function show()
{
        $cliente= \App\Cliente::find(1);
        echo "$cliente->nombre<br>";
        echo "$cliente->apellido<br>";
        echo "$cliente->telefono<br>";
        echo "$cliente->direccion<br>";
}

I will not give how to make a form here cause i dont want to extend to much this post. If you want to see how to do the form part check making a form in laravel.

To insert, delete, modify I going to put data directly, yo can check via phpmyadmin or your database if it works or not after running the query.

Insert data

In order to insert data with eloquent you have to use cliente(client) model, we can do that including in our ClienteController(or ClientController) using use, use key is part of composer autoload.

use App\Cliente;

if you use this aproach please run dump-autolaod

composer dump-autoload

In the case you not use use key you can create a new instance of Cliente(Client) using the full path:

app/Http/Controllers/ClientController.php[fragment]
public function save(){
        $cliente = new \App\Cliente;//using use this line as follow
        //$client= new Clinete;
        $cliente->nombre    = "Jhon";
        $cliente->apellido  = "Kremer";
        $cliente->telefono  = "099876532";
        $cliente->direccion = "Peru 1978";
        $cliente->save();
    }

this is a basic way you can use your methods in laravel, for example you can use constructor injection and method injecton.

But now underestand the basics.

Update data

have 2 posible things you could want to to do when you are modifing data.

  • select a row by the id and modify it.
  • modify multiples rows by other value

Remember that we use find to select data, lets select the client with id = 1, after select the client we could add the new data to it and save it as we do in insert data.

Whats the difference?

the diference is that we are selcting the client. The method is the same, internally does diferent things.

app/Http/Controllers/ClientController.php[fragment]
public function update(){
        $cliente = \App\Cliente::find(1);
        $cliente->nombre    = "Marcos";
        $cliente->apellido  = "Kremer";
        $cliente->telefono  = "099876532";
        $cliente->direccion = "Peru 1978";
        $cliente->save();
}

In fact we do not need to charge all the data to the client to update it only the one we want to modify, for example nombre(name):

app/Http/Controllers/ClientController.php[fragment]
public function update(){
        $cliente = \App\Cliente::find(1);
        $cliente->nombre    = "Marcos";
        $cliente->save();
    }

Another way to do this:

app/Http/Controllers/ClientController.php[fragment]
public function update2(){
        $cliente = \App\Cliente::where("id", 1)
        ->update([
            'nombre'    => "Marcos",
        ]);
}

Modify data in mass(mass assignment)

Supouse that we have clients in with the same address ‘peru 1978’ and you need to change this, if you want to change it you ll need to do something like this:

app/Http/Controllers/ClientController.php[fragment]
public function update3(){
         $cliente = \App\Cliente::where("direccion", "peru 1978")
         ->update([
             'direccion'    => "peru 1988",
         ]);
 }

Remember if you are using $guarded on the field this will not work, you are protecting this field, in this case id is marked as $guarded cause is a PRIMARY KEY.

Do not abuse of $guarded or $fillable doing something like this ‘*’ instead of set the fields that need to be guarded or fillable, you can do it ? yes but its not recommended

Delete data

To erase data is very simple, just select the id of the row you want to delete and call delete() method:

app/Http/Controllers/ClientController.php[fragment]
public function delete(){
    $cliente = \App\Cliente::find(1);
    $cliente->delete();
}

References:

Category: en-laravel
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category