Table of Contents

Laravel Models

Laravel Models

A zombie developer creates complex SQL queries, whereas a Laravel developer extends the Eloquent Model Class and benefits from beautiful and readable database interaction.

Zombie Developers often use complicated queries that can lead to bad and infectious code. As a Laravel developer we must keep our queries strong & healthy.

We must MODEL some good behavior.


Models

A model is a PHP class that handles all the interaction between the code and the database. When using Laravel we can extend the Eloquent Model class and all our interaction will automatically be built-in.

Take a look at what an example zombie model would look like (this file would be placed inside of the /app folder):

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Zombie extends Model {

    protected $table = 'zombies';

}

In the code above we are saying that the class Zombie extends from the Illuminate Eloquent Model. And we are saying that our database table name is zombies. So, to map the zombie model with the database, we create a simple zombies table in our database that looks like the following:

zombies

|Field |Type |Length|

|id |INT |11 |

|name |VARCHAR |50 |

|strength |VARCHAR |20 |

|health |INT |3 |

|updated_at |TIMESTAMP | |

|created_at |TIMESTAMP | |

In the zombies table we have a unique ID, the name of the zombie, their strength, and their health. Let's assume that we have this table in our database. In a future section, we will be talking about migrations, which allow us to easily create database tables in our code.

After we have a table like the one above, we are free to interact with the database using the Eloquent Model class.

Quick Note: Before interacting with the database you will need to add your database credentials to your .env file (briefly covered in section 3).

Let's move on to learning more about this Eloquent Model class.


Eloquent

Models in Laravel extend from the Eloquent class that make your database interactions as clean and easy to use as possible. Eloquent is appropriately named, because, that's exactly how it feels to interact with the database, "Very eloquent." You might remember this code from the previous section:

<?php

use App\Zombie as Zombie;

Route::get('/zombie/{id}', function($id){
    $zombie = Zombie::find($id);
    echo 'Name: ' . $zombie->name . '<br />';
    echo 'Strength: ' . $zombie->strength . '<br />';
    echo 'Health: ' . $zombie->health . '<br />';
});

Before we would not be able to run our application because our code would not know where to access the Zombie class, but now that the Model is created we can access it.

A> Note that we are telling our app that when we call Zombie we want to use the zombie class located at App\Zombie. This is referred to as namespaces, something that we will dig further into in a future section.

We still have a problem, though.

We will not be able to access the route from above because we do not have any zombies in our database, so let's go ahead and create a new zombie with the following route.

<?php

Route::get('/admin/zombies/create', function(){

  echo '<form method="POST" action="/admin/zombies/create">
            <input type="text" name="name" placeholder="Name"><br>
            <input type="text" name="strength" placeholder="Strength"><br>
            <input type="text" name="health" placeholder="Health"><br>
            <input type="hidden" name="_token" value="' . csrf_token() . '">
            <input type="submit" value="Create New Zombie">
        </form>';

});

And if we visited that route in our browser (site.com/admin/zombies/create), we would end up with a simple form.

When this form gets submitted it will post to the site.com/admin/zombies/create POST route, which should look like the following:

<?php

Route::post('/admin/zombies/create', function () {
    // create a new zombie
});

So, if we added the following functionality:

<?php

use App\Zombie as Zombie;
use Illuminate\Http\Request;

Route::post('/admin/zombies/create', function(Request $request){

  // create a new zombie
  $zombie = new Zombie();
  $zombie->name = $request->name;
  $zombie->strength = $request->strength;
  $zombie->health = $request->health;
  $zombie->save();

  echo 'Zombie Created';
});

After submitting the form with the following data:

  • Name: Johnny Bullet Holes
  • Strength: Strong
  • Health: 70

You should see the message 'Zombied Created' displayed on the screen. Next, if we check our database should see the following row.

How easy is that! We just created our first Zombie. So, if we were to visit the following route (site.com/zombie/1), we would be directed to the following route from above:

Route::get('/zombie/{id}', function($id){
    $zombie = Zombie::find($id);
    echo 'Name: ' . $zombie->name . '<br />';
    echo 'Strength: ' . $zombie->strength . '<br />';
    echo 'Health: ' . $zombie->health . '<br />';
});

And we would see the following output in our browser.

Awesome, right? How much easier could it be? Well, it gets a little easier, instead of creating a zombie by adding the name, strength, and health manually we could always do this in one line.

Check out the following:

<?php

use App\Zombie as Zombie;
use Illuminate\Http\Request;

Route::post('/admin/zombies/create', function(Request $request){

  // create a new zombie from all the data posted from the form
  $zombie = Zombie::create($request->all());

  echo 'Zombie Created';
});
?>

If we tried to submit to the route above, we would probably get an error message saying 'MassAssignmentException'. This means that we are trying to assign a mass amount of data to our Zombie class, but we have not specified what is ok to add when creating a new Zombie.

This is a level of security that Laravel offers.

To tell our zombie class that we want to be able to create a zombie and allow name, strength, and health all at once we would add the following in our Zombie class:

protected $fillable = ['name', 'strength', 'health'];

So, the full class would look like:

<?php namespace App;

use Illuminate\Database\Eloquent\Model;

class Zombie extends Model {

    protected $table = 'zombies';
    protected $fillable = ['name', 'strength', 'health'];

}

And now, if we submitted our form with the new create route above we would not get that mass assignment error. Instead, we would have successfully created another new Zombie.

Let's say that we created another new zombie with the following data:

  • Name: Ted Manwalking
  • Strength: Weak
  • Health: 90

We would now have the following two rows in our database:

Using Eloquent makes it super easy to create, read, update, and delete data from our database. Let's move onto relationships, which allow us to easily bind data between tables in a database.