Laravel MVC

Well now you have some rough idea for how to create basic site having 4 to 5 pages in Laravel after learning laravel routes. Now we will go ahead and learn real programming in laravel framework by utilizing it’s capabilities. You heard the word “MVC” since you have started developing the web-application and have eager to know:

  • what MVC stands for?
  • how i can use it in my programming approach?
  • How can i benefited by using it?

Well MVC’s full form Model View Controller. It’s not a programming language specific, but it’s design pattern and used in many programming languages like Java, C# and in PHP of course because we are looking and interested for the same in this blog post.
MVC

Responsibilities of each components in MVC are:

  • Model: Holds the data, container for data.
  • View: Displays/represents the data.
  • Controller: Process/Provides/Saves the data

Also we have some basic ideas about laravel directory structure as i mentioned in my previous post so now let’s use some of the directories for our model view and controller implementation in laravel.

Before we start implementing MVC let’s define some goals. So below are our customer requirements.

  • Let a customer wants to display list of categories and products on home page.
  • Product detail page which contains all necessary detail for the product.

You can see below image have some rough sketch for above 2 requirements.

There are 2 pages so we are creating 2 routes. so add below lines in routes.php

Now to satisfy above requirements we need to create below files.

File creation

In app/controllers directory create ProductCtrl.php file

In app/views directory create 2 files for presenting data as below:

  1. products.php
  2. product_detail.php

Up till now we have created necessary files for Controller and View. Now it’s time for Model which actually contains data to present in views. Yet we have not talked about how to interact with database using Laravel capabilities. So before we setup models which fetches data from database let’s configure our app to interact with database so that our models are full with data if it is there in database.

Create one database in mysql called my_app (You can give any name, this is just an example).
Create 2 tables inside my_app database.

  • categories: cat_id, category_name
  • products: product_id, product_name, price, cat_id

Database Connection Setup

Now open app/config/databse.php inside please make do below settings:

‘default’ => ‘mysql’, This says that your application will use mysql database.

inside connections array just fill mysql properties as below. Please use credential as you have in your system for database. I have default root/root in my system so i use it as username and password respectively.

‘driver’ => ‘mysql’,
‘host’ => ‘localhost’,
‘database’ => ‘my_app ‘,
‘username’ => ‘root’,
‘password’ => ‘root’,
‘charset’ => ‘utf8’,
‘collation’ => ‘utf8_unicode_ci’,
‘prefix’ => ”,

Now our app will use database connection using above configuration. We can access these settings in our app as below.

Config::set(‘database.default’, ‘sqlite’);

Now database is set for our app, it’s time to set some of the models for our app which can fetch data from the database and controller will pass that data in views so finally view can represent it.

Model Setup (M in MVC)

Inside app/models create 2 files for models.

  1. Category.php
  2. Product.php

Now open Category.php and paste below code snippet in it.

NOTE for above code:

  • Model class Category extends it using Eloquent class provided by the laravel. Eloquent is nothing but ORM layer developed by laravel framework for database interaction for application. So at this stage you do not need to worry about it. Later on you can study it.
  • We have given our model class name as Category, so it expects categories table in database given in config/database.php file. In our case it is my_app database. Now you have a question what if we want to give class name different and table name different. So the answer to your question is YES you can. Laravel gives you all freedom for this. For this you have to add below line in your Category class.

protected $table = ‘categories’; // table name in database

  • We have added public $timestamps = false; attribute, because by default laravel Eloquent expects created_at and updated_at attribute in database table referenced by Eloquent model (Category). If we don’t want these 2 fields we can simply add $timestaps = false.

Now open Product.php and paste below code inside.

Again in brief it expects products table in database.

Controller Setup (C in MVC)

Now open ProductCtrl.php and Paste below code in it.

Now let’s try to understand above code from Laravel perspective.
If you remember for displaying all products we are using below routes:

Route::get(‘products’,array(‘uses’=>’ProductCtrl@getProduct’));

which says that we are using
ProductCtrl
class as a Controller for this request
and getProduct method is specific method from ProductCtrl will be executed for this request.

So Controller responsibility is just server All Categories and Products list to views.
Laravel provide awesome database query interface by Eloquent feature. Eloquent is an ORM layer for database interaction between application and database.

You can see without writing for database connection and writing any select we can get all categories from category table using

$categories = Category::all();

Eloquent also provide for filtering the data using where condition we can see from below code

$products = Product::where(‘cat_id’,’=’,$id)->get();

View Setup (V in MVC)

Now we have categories and products available from the controllers to display in the views. Let see how to display it. In our view file we have all tags available which are required for a complete web page like HTML, TITLE and BODY but here i am just writing PHP logic which is responsible for generating dynamic HTML content sent by controller(Server).

Open file products.php in app/views

Notice in above code there URL::route is used basically it will generate complete URL like http://www.xyz.com/products/1 It requires as attribute for route entry. So for products foreach loop we have added below code

<a href=”<?php echo URL::route(‘product_detail’,$product->product_id);?>”>

It will look for route in routes.php having ‘product_detail’.

Open file product_detail.php and paste below code in it.
product_detail.php have product object available from Controller when user click on Product name he/she will navigate to product_detail.

So in conclusion we have now understanding of how mvc works in general and in context of laravel. MVC is nothing new in web stack but it is architectueral pattern that will seperate the concerns. We will see more on laravel so stay tuned.

Thanks,

-Ahesan

Advertisements

One thought on “Laravel MVC

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s