Learning Laravel Models

Laravel models are based on the common MVC or Model-View-Controller principles. If you don’t know what MVC is at all, you can Learn More about MVC Here because I just want to get to the meat of learning how to use Laravel Models in this Laravel models tutorial.

Prerequisites

You may have learned from following my Laravel tutorials, that you often need parts of other Laravel tutorials to fully understand the current tutorial. Well guess what? this applies here as well. You should have an understanding of the following areas of Laravel before attempting to learn about models:

The User Model

Since the user model is necessary in almost any modern web application, Laravel has created a basic user model and provided it in  app/models/User.php  for you to manipulate and copy as needed.

Generally models will follow the same naming convention as the example User Model. So if you added a new model to your project called Cars that was a representation of cars owned by the site’s users then that model would also go in the app/models directory and would be named Cars.php so your complete path would of course be app/models/Cars.php.

Models and the Database

Each model in your project is directly related to a table in the database. By default that table will take the same name as the model, but  for the User model the table name is users, so for Cars, the table name would be cars. Follow that basic pattern and you should be okay. If you want to use a different name you can declare the table name for your model as you will see in the example code below.

Since every model interacts with a database table, the first thing we need to do is make our model class extend the Eloquent class. The Eloquent class is a database class Laravel uses with every model in order to interact with the database. So your first line of actual code should read:

class User extends Eloquent {}
Now we have started our class. Simply replace “User” with your class name if you are working on a different class.
To get an idea of how a model class should be written, you can follow the default User model that comes shipped with Laravel. Also while opening the class statement, the User model implements a couple interfaces:
implements UserInterface, RemindableInterface
so the complete first line of the User model looks like:
class User extends Eloquent implements UserInterface, RemindableInterface {

After that, as I mentioned above, is where you could change your table name, however since the User model doesn’t do so, the following line could have been left out. It was most likely left in as a way to demonstrate how to name a table other than the default one for those who have a need or desire to do so. Here is how the User model declares its table name:

protected $table = 'users';
As I mentioned, since the name is users and that would be automatically assumed since the name of the model is User, this line is not mandatory but does show you what to do if you wanted to use a table named something other than users which you could do if you wanted simply by replacing “users” with “table_name” for example.
The next line in Users.php looks like:
protected $hidden = array('password');
What the above line does is prevents the user’s password from being displayed when you might not want it to such as in a json API call. There are a couple of other measures that could be applied here to further protect your data such as the $fillable and the $guarded properties. $fillable tells Laravel which columns of your database table can be filled and guarded tells Laravel which ones cannot be filled basically. Here is an example of each:
protected $fillable = array('username', 'email');
protected $guarded = array('id', 'password');
The first line above tells us that username and email are allowed to be filled in the database by the user and the second line tells us that they cannot fill in the id and password fields.
Returning Data from a Model
The next practical thing the User.php Model allows us to do is return some data from the database with the following three functions:
    public function getAuthIdentifier()
    {
        return $this->getKey();
    }
    public function getAuthPassword()
    {
        return $this->password;
    }
    public function getReminderEmail()
    {
        return $this->email;
    }
That is all for the User class actually, so lets explain the last three functions. The first is for returning a unique identifier of the user. The second returns the user’s password and the third returns that user’s reminder email address. Pretty simple really!

How to Use a Model

Everything you have learned so far is great, but how about seeing it in action? Yes, let’s do that! In order to use the model, we need to define a route in the app/routes.php file, so open that file and append the following code to the end:
If the code worked, you will see:
bool(true)
only in the resulting page that opens. If it fails you will probably see a big long error page. in which case you will have to go back and check each step of this tutorial to see what you missed or make sure you set up the database and users table properly. If you have not done, so first, you need to create the users table by following this tutorial about database tables and Laravel:
When you are done and have successfully added a user to the users table, comment out the code in routes.php so you don’t recreate the user every time you or someone else lands on that url.

Summary

To learn more about Laravel, follow more tutorials I have written by CLICKING HERE!

Leave a Reply

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