This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

CloudwaysCDN — a powerful solution that offers superior performance and satisfied global audience for your business. Read More

Understanding Models and Views in Laravel 5.5

Updated on  5th February

8 Min Read
Reading Time: 8 minutes

In my previous article in this Laravel 5.5 series, I covered the Controller (the third part of the MVC) and Middleware in Laravel. Today, I will describe Model and View of the MVC architecture, and how these ideas are implemented in Laravel 5.5.

Laravel 5.5 Models and Views

Models in Laravel 5.5

Models in Laravel 5.5 are created inside the app folder. Models are mostly used to interact with the database using Eloquent ORM. Eloquent provides simple ActiveRecord implementations for database interaction.

The easiest way to create a model is the Artisan command:

Let’s first create a new table books in the database. Use the following schema:

Next, I will create a new model for the books table in Laravel. For this, run the following command.

Once the command is completed, a new model will be created in the app folder. At the moment, this model looks like:

In the above code, the model class Books is extended from Illuminate\Database\Eloquent\Model class of Laravel. You will be noticing that there is no database CRUD operation related functions in this model. You could use several prebuilt Eloquent functions for this purpose.

Working with Eloquent ORM

The best thing about Eloquent ORM is the ease with which you could perform CRUD operations on the database. Usually, Eloquent uses the class name of the model as the name of the table. However, you could also define the name of the table explicitly by defining a protected variable $table.

By default Eloquent will assume that each table have a primary key of column name id and that it autoincrements. If your primary key has a different name, you can easily set it by defining it in protected $primaryKey. This overrides the default settings. In addition, if your primary key does not autoincrement, you can easily set it off by defining public $incrementing to false.

For example, let’s use book ISBN number as a primary key in the table. Now, I can make the following changes in the model to tell Eloquent about this primary key and that it should not be auto-incremented.

Saving Data Using Eloquent

Saving data using Eloquent is super easy.

In the previous example, I created a resource BooksController.

Let’s start editing store(Request $request) method so that it can save my request to the database. The first method of saving data is:

And the second one is:

In order to save data using Create() method, you need to do two things first. You need to define fillable columns in the model:

Second, you need to make sure that the name of request parameter that you want to save in your database is same as the name of the column in the database.

laravel cta

Update Data Using Eloquent

Updating data using Eloquent is as easy as saving data.

I will now edit update(Request $request, Books $book) method so that it can update in the data.

So how does it work? When a user send a put request to book/{book}, the model in Laravel app will automatically get the book appropriate to {book}. If there is no match, it will return an error.The reason behind this is because the model is bound to the update method. Since, I have defined fillable, all the data will be saved easily.

Get All Data Items

Let’s now edit index() method of the controller so it can return all the data saved in the database.

Since I have used $books,  Laravel will return the JSON of the data, by default.

Get a Single Data Item

I will edit show(Books $books) method to return a specific book when the user sends a get request to book/{book}. It will return the book corresponding to the primary key.

Delete a Single Data Item

Let’s now edit the destroy(Books $books) method of the controller to delete the corresponding data to the primary key.

As you could see, Eloquent takes out much of the work from working with RDBMS. You can define table relationships in it and easily get data from different tables. To learn more about Eloquent and its magic, refer to the official Eloquent documentation.

Views in Laravel 5.5

Views in Laravel are created in the resources/views folder. You can change base path for views by editing config/view.php file and changing realpath(base_path('resources/views')) to the new location for the views.

Laravel offers a simple view that routes to home. Loading a view in the controller is easy. You just need to add view(‘viewname’) method while returning from the controller method.

view() is a global helper in Laravel. In this method, you just need to pass the name of the view. For example, if the full name of the view is home.blade.php,  you just need to pass home to the view() method.

What if you are saving your views inside a new directory in the views folders? No need to worry about that!

For example, if home.blade.php is saved inside the dashboard directory, then you just need to pass the folder name, add a dot “.” and then the name of the view to the view() method i.e. view(“dashboard.home”);

Passing Book Data to the View

Let’s create a new view in Laravel website with the name book.blade.php inside the views folder. This view will contain the following code:

This view will show a single book from the table. This is how this view works.

I will pass a book to this view in the show(Books $books) method of the controller.

Now whenever the user send a GET request to /book/{book}, it will return the view of the book. A large number of the view in Laravel are created using Blade Templating Engine. I will now show you how this engine works.

Blade Templating Engine

The blade is a simple and powerful templating engine for Laravel. You can also add your vanilla PHP code in it easily. Blade template files have the extension .blade.php and are save in the resources/views folder. You could create one master template and several child templates can be extended from this master template. In this example, I will start with defining a master layout and then extending it further. To learn more about creating layout from blade, I will suggest you to also read Create Layouts In Laravel Using Blade Templating Engine

Create a Master Layout

All master layouts are saved in the layouts folder inside resources/views folder.

I will create a simple layout with the name app.blade.php. This layout will contain the following code:

Inside the app view, I have used HTML markup and bootstrap for styling. I have used the @yield directive. This directive is used to display the content for the given section. You can pass a unique name to yield so that when this view is extended in another view, I could easily add new content to this section.

Extending a Master Layout

Now let’s extends the master layout. I have created a view to display books in the beginning of this tutorial. I will now extend it from the master layout.

Let’s see what I have done. First, I told Blade that I am extending from a previous layout using @extends. Next, I used @section, which bind content to the @yield that I created in the master layout. In the content section, I have defined the HTML markup code to view a single book.

What More You Can Do With Blade?

This was a very simple example that highlighted the functionality of Blade. You can also use if-else and loops in Blade. To learn more about Blade, refer to the official Blade documentation.

Winding Up The Series

I started this series with an introduction of Laravel 5.5, and discussed how MVC works with Laravel. Next, I covered how you can perform routing in Laravel 5.5. In this series, I covered the concepts of MVC in Laravel. I also discussed controllers and middlewares in Laravel. In the end, i.e., in this tutorial, I discussed models and views in Laravel. I also offered a short introduction to Blade templating engine and learn how to create a template in Blade.

 

Share your opinion in the comment section. COMMENT NOW

Ahmed Khan

Ahmed was a PHP community expert at Cloudways - A Managed PHP Hosting Cloud Platform. He is a software engineer with extensive knowledge in PHP and SEO. He loves watching Game of Thrones is his free time. Follow Ahmed on Twitter to stay updated with his works. You can email him at ahmed.khan@cloudways.com

Create Laravel apps without the worry of server management.

Deploy your app on optimized PHP hosting servers for Laravel.

Get Our Newsletter
Be the first to get the latest updates and tutorials.

THERE’S MORE TO READ.