Category Archives: Laravel Tutorial

Laravel Tutorial

Laravel Views

What is View?

View is one of the key component in any Model-View-Controller(MVC) framework.Views are meant to hold the presentation logic in any Laravel
application. Views separates presentation logic from the application logic. A view file usually contains the information being presented to a user. View can be a complete web page or parts of page like header and footer.

In Laravel, views are stored in resources/views directory. View for a basic web page can be directly called from route.

Creating a view

Step 1:- Create a new file hello.php and save it at resources/views directory.

Step 2:- Copy and paste following code in the hello.php

Step 3:- Copy and paste following code in the app/Http/routes.php to configure the route for the view created above.

Step 4:- Now open the following URL in the browser to see the output.

http://localhost:8000/hello

Passing Data to a view

If you want to pass some data to a view, it is possible by simply passing a data array consist in key/value pair.

Example:-

Step 1:- Open the “hello.php” file we created above, and update it with following code.

Step 2:- Open app/Http/routes.php and re-configure the route as below –

Step 3:- Inside the view, we can retrieve each of the data value by its corresponding key. In “hello.php”, $name will be replaced by it’s value.

Step 4:- Again open the following URL in the browser to see the output.

http://localhost:8000/hello

Sharing Data with all Views

Sometimes we may want to share some common data across all the views. In Laravel, we can do it using share() method. Typically share() method is called from boot method of service provider.

Example:-

Step 1:- Create two new views as exp1.php and exp2.php, sharing the common variable $name.

Step 2:- Open the exp1.php and exp2.php, and copy the following code in corresponding files.

resources/views/exp1.php

resources/views/exp2.php

Step 3:- Open app/Http/routes.php and define corresponding routes exp1 and exp2.

Step 4:- Open app/Providers/AppServiceProvider.php file and call share() method inside the boot method as following.

Here we have defined a common variable $name, that can be shared across both the views we created.

Step 5:- Now visit the following URLs in the browser to see the output.

http://localhost:8000/exp1

http://localhost:8000/exp2

 

Laravel Migrations

Web application development is an iterative process and it cannot be denied that database schema constantly evolves throughout the course of development. There are situations we may want to add or drop a table, drop or rename a column, drop an index etc. Migrations gives you a way to keep track of the changes we made in database schema during the development process. In collaborative development environment migrations helps you to keep database schema in sync without having to drop and re-create the database each time a change happens.

We can think of migrations as a version control system for database schema, which allows us to keep track of changes made in the database schema. This way it simplifies the development, deployment and updating of any web application.

In Laravel, migrations are simply PHP files stored in /database/migrations directory. Migration files are created over time as we build and modify our application database schema. Each of the migration file contains distinct set of changes to the associated database. In Laravel at any point of time you can switch or migrate to any specific version of the data model.

Artisan Migration Command

Laravel comes with set of migration related commands that can be run from artisan command line interface.

migrate:install
This command is used to create the migration table in the application’s database, this table is used to keep track of migations which have already executed.

migrate
This command is used to run all of the pending migrations for your application.

migrate:make
This command is used to create new migration, the newly created migration is saved in database/migrations directory. A timestamp will be added to the beginning of the migration file name, which allows Laravel to determine the order of the migrations.

migrate:rollback
This command is used to rollback the last migration applied.

migrate:reset
This command is used to rollback all of the migrations applied.

migrate:refresh
This command is used to roll back all of your database migrations, and then re-creates your database schema.

Creating a New Database Migration

Step 1:- In laravel, before creating any migration first thing is to run the following command to create migrations table.

As command executed successfully, you will notice a new table “migrations” is created in database.

Step 2:- Run following command to generate new migration file that will create a new table “posts” in database.

Once the above command executed you will see new migration file is created in the database/migrations directory named as [timestamp]_create_posts_table.php

Structure of a Migration

Let’s open the newly generated migration file, to take a look over the migration structure

Note that every migrations we create extends the Migration class, and must contains two methods “up” and “down”, here –

up() – The up () method includes the set of operation that is executed when the migration is run.

down() – The down () method includes the set of operations that is executed when you rollback migration , it usually reverse the operations performed by the up () method.

In the example, up () method contains a Schema::create function, used to create the “posts” table.

In both of the above methods we can define set operations to create and modify database table using the Laravel schema builder.Laravel’s schema builder provides you the set functions to make any possible database update that you wish to apply.

Please take a look at additional Laravel Schema Builder methods –

Table-level Operations

Laravel Method Purpose
create() Create the table with a name. The second argument is a closure which contains table definitions.
drop() Drops the table, all of its columns and any indexes will also be removed.
dropIfExists() Drops the table if it exists.
rename() Rename the table to a given name.

Column-level Operations

Laravel Method Purpose
dropColumn($columns) It drops the specified column or columns (must be passed as array). Keep in mind that any index associated with that column will also be removed.
renameColumn(‘from’, ‘to’); This command is used to rename the column name

Index-level Operations

Laravel Method Purpose
primary($columns) This command is used to specify the primary key or the composite (must be passed as array)
unique($columns) This command is used to specify a unique index for the table.
index($columns) This command is used to specify an index for the table.
foreign($columns) This command is used to specify a foreign key for the table.
dropPrimary($index) This command is used to drop the given primary key.
dropUnique($index) This command is used to drop given unique key.
dropIndex($index) This command is used to drop the give index.
dropForeign($index) This command is used to drop foreign key.

Step 3:- Finally run the following command to apply the migration to actual database.

Laravel Models

What is Model?

In MVC framework, the letter “M” stands for Model. Model are means to handle the business logic in any MVC framework based application. In Laravel, Model is a class that represents the logical structure and relationship of underlying data table. In Laravel, each of the database table has a corresponding “Model” that allow us to interact with that table. Models gives you the way to retrieve, insert, and update information into your data table.All of the Laravel Models are stored in the main app directory.

Creating a Model

Model can be created simply using make:model artisan command as following –

Syntax:-

Replace <model-name> with name you like for model you are creating.

Once the above command is executed, a model class file with some basic model code will be created in the App directory.

Example:-

Step 1:- Open the command prompt and execute the following Artisan command –

Step 2:- As the above command is executed, a model will be generated named Post as app/Post.php. Let’s open the newly generated model file, at this point your model should look like as following –

Note that every Eloquent models we create extends the Illuminate\Database\Eloquent\Model class.

Table Name

The plural form of the model name is used as the default table name for the corresponding, custom table name can also be defined explicitly using $table property as following –

Primary Key

In Laravel, it is assumed that each of model table by default has a primary key column named id, it can be overridden explicitly using $primaryKey property as following –

Timestamp

In Laravel, each of the Eloquent Model have added the two columns (created_at and updated_at) in all of your database tables, If you do not want to have these columns added to your database table, set the $timestamps property on your model to false as following -<?php

 

 

 

 

Laravel Controllers

What is Controller?

In MVC framework, the letter “C” stands for Controller. Controller is the entry point for any MVC framework based application, it receives the incoming HTTP requests and process it communicating with models and views, then return the results back to the web browser. In Laravel, controllers is completely responsible for handling the application logic.

In Laravel, all of the controllers stored in the Controllers folder, located in App/Http/Controllers.

Creating Basic Controller

Controllers can be created using following artisan command –

Syntax:-

Replace <controller-name> with name you like for controller you are creating.

Once the above command is executed, a controller class file with some basic controller code will be created in the controllers folder, located in App/Http/Controllers.

Once the controller created, it can be invoked by defining route in routes.php.

Syntax:-

Example:-

Step 1:- Open the command prompt and execute the following Artisan command –

Step 2:- As the above command is executed, an empty AuthorController class will be generated under App/Http/Controllers with the name AuthorController.php. At this point, your controller should look like as following –

Step 3:- Now create a new method inside the AuthorController to show all posts, method should look like as following –

Step 4:- Create a view file dashboard.php inside resources/views/ directory, and put the following code inside it –

Step 5:- Open app/Http/routes.php and configure the route as below –

Step 6:- Now open the following URL in the browser to see the output.

http://localhost:8000/dashboard

Passing Parameters to Controllers

If you want to pass parameters to controller, it can be done easily in following way –

Step 1:- Open app/Http/routes.php and re-configure the route as below –

Step 2:- Open the “AuthorController.php” file we created above, and update “index” method as following.

Step 3:- Open “dashboard.php” we created above, and update the code as following –

Step 6:- Now open the following URL in the browser to see the output.

http://localhost:8000/dashboard/john

Creating Restful Resource Controllers

In any web application CRUD (Create, Read, Update and Delete) are the basic operations on a resource. With a resource controllers you get a generic controller structure that includes all the methods for performing CRUD operations. In Laravel, using a single command you can create a resource controller. In Laravel,you don’t need setup different routes for CRUD operations. Single route declaration can handle all of the RESTful operations for specified resource.

Create a Resource Controller

In Laravel, the command used to create a resource controller is same as normal controller, just at the end we have to add suffix “resource”.

Once the above command is executed, a controller class file PostController.php with index, create, store, show, edit, update, and destroy methods will be created in the controllers folder, located in App/Http/Controllers.

app/Http/Controllers/PostController.php

Once the controller created, the route declaration for the above resource controller in routes.php looks as following –

This resource route declaration creates multiple routes to handle a variety of RESTful operations on the post resource.

Actions Handled By Resource Controller

Below is the list of different URI’s created for the resource –

HTTP Verb Path (URL) Action (Method) Route Name
GET /post index post.index
GET /post/create create post.create
POST /post store post.store
GET /post/{id} show post.show
GET /post/{id}/edit edit post.edit
PUT/PATCH /post/{id} update post.update
DELETE /post/{id} destroy post.destroy

Partial Resource Routes

We can specify a resource route to handle set of actions as following –

Similarly, we can exclude the actions that we do not want a resource route to handle, it can be declared as following –

 

Laravel Response

In Laravel, a response is what sent back to the user’s browser when a request made. All routes and controllers are meant to return some response as per the request. In Laravel, a response can be return in various ways.

Basic Response

In Laravel, simplest response is just to return a string from a controller or route.

Example:-

Attaching Headers

Headers can also be attached to a response using “header” or “withHeaders” method.

Syntax:-

Example:-

Attaching Cookies

Cookies can also be attached to response using “cookie” helper method.

Syntax:-

Example:-

JSON Response

If you want to return a JSON response it can be done using “json” method.

View Response

If you want to return a view in response with custom status and headers, to do this “view ” helper method can be used in following way –

Force File Download

If you want to generate a force download response it can be done using “download” method.

 

Laravel Request

Retrieving Request Information

In Laravel, by instantiating Illuminate\Http\Request we can retrive information about the current HTTP request. We can instantiate Illuminate\Http\Request via dependency injection. The Illuminate\Http\Request instance provides us a rich set of methods to get information about the current HTTP request.

Request URI

Request URI can be retrieved using the “path” method.

Example:-

So, if the full URL is http://xyz.com/foo/bar, the path method will return foo/bar

Example:-

The “is” method is used to retrieve the requested URI that matches the specified pattern.

It matches the specified URL pattern passed as method argument, in the above code snippet (*) is used as a wildcard.

Example:-

The “url” method returns full url ignoring query string.

Example:-

The “fullUrl” method returns full url including query string.

Example:-

The “fullUrlWithQuery” method return full url and appends the query string based on the arguments passed to it.

So, if the full url is http://xyz.com/foo the following method will return http://xyz.com/foo?arg=val. Arguments must be passed in key value pair as above.

Request Method

The “method” method is used to retrieve HTTP verb or Request Method for the current request, and “isMethod “ method is used to check HTTP verb for the current request.

Retrieving Input

In Laravel, input values can also be easily retrieved using the same Illuminate\Http\Request instance. You don’t need to care about the request method(“get” or “post”) used to send the input. Same method is used to retrieve input values from both the request methods.

The Illuminate\Http\Request instance offers you following methods for accessing input values.

“input” Method

Example 1:-

It returns value for input variable specified in method argument.

Example 2:-

It returns “John” as default value for “student_name” if it is not present in request.

Example 3:-

The “input” method can also be used to retrieve JSON inputs, and “dot” is used to access individual elements inside JSON array.

“has” Method

The “has” method is used to determine the presence of the specified value in the request, it returns true if the specified value is present and is not an empty string.

“all” Method

The “all” method is used to retrieve all the input data available in the current request.

“only” Method

The “only” method is used to retrieve selected input data from the request, it accepts array or list of input elements for which you want to retrieve value.

“except” Method

The “except” method is used to retrieve selected input data from the request same as “only” method, but it accepts array or list of input elements that you want to ignore.

Retrieving Input as Property

In Laravel, it is also possible to retrieve input data as property of Illuminate\Http\Request instance.

 

 

 

Laravel Middleware

What is Middleware?

In Laravel, Middleware is a filtering mechanism that facilitates filtering of incoming HTTP request before it is routed to particular controller for further processing. Laravel framework includes several in-built middleware, including authentication and CSRF protection. All of these middleware are located in the app/Http/Middleware directory. In addition to the built-in middleware, custom middleware can also be created.

Creating Middleware

Middleware can be created by executing the following artisan command –

Syntex:-

Replace <middleware-name> with name you like for middleware you creating.

For example, we create a middleware that that only allow to admin user to access into admin panel.

Step 1 – So first we create IsAdminMiddleware middleware using following command –

Step 2 – After successful execution of the above command, IsAdminMiddleware.php will be created at app/Http/Middleware. The newly created IsAdminMiddleware.php will have the following code in it –

Step 3 – Ok, now open IsAdminMiddleware.php file and put bellow code on that file.

Registering Middleware

Once our middleware is created, we have to register it before we use it. The middleware is registered at app/Http/Kernel.php. There are two ways we can register a middleware in Kernel.php.

Global Middleware

If you want your middleware to be run on every HTTP request handled by your application, you need to list your middleware class at the end of $middleware array of your app/Http/Kernel.php class.

Route Middleware

If you want your middleware to be run on some specific routes, you need to list your middleware in the $routeMiddleware array of your app/Http/Kernel.php class.

Example:-
We have created IsAdminMiddleware in the above example. Now we can register it in route specific middleware property and create alias for it in Kernel.php file.

Our app/Http/Kernel.php file looks as following –

Once middleware has been created and registered, you can assign it to any route using middleware key in following ways –

Middleware Parameters

Sometime you may want to pass parameters to a Middleware, this can be achieved by passing our custom argument after the $next argument.
The standard middleware funcation looks like as following-

Imagine, if our application has different type of user roles like author, editor, publisher and admin, and now you want to authenticate the request based on user role, this can be achieved by passing user role as parameter to middleware.

In this case our middleware function will look like as following –

We can specify middleware parameters when defining the route by separating the middleware name and parameters with a : and multiple parameters should be delimited by commas(,).

Add the following line of code in app/Http/routes.php file.

Before & After Middleware

Whether a middleware runs before or after a request depends on the middleware itself.

For example, let’s define a middleware that runs before a request –

Now, let’s define a middleware that perform its task after the request –

Terminable Middleware

Terminable middleware allows you to perform some task even after the HTTP response is already been sent to the browser.This can be done by defining a middleware as “terminable” middleware. A middleware can be defined as “terminable” by adding a terminate method to it.The terminate method accepts two arguments $request and $response. Once a terminable middleware is created it should be registered as global middleware in app/Http/Kernel.php file.

Example:-

Laravel Routing

What is Laravel routing?

Routing is one of the core components of Laravel framework, it is simply a mechanism that performs the mapping for your requests to a specific controller action. All Laravel routes are defined in the file located as app/Http/routes.php file, which is automatically loaded by the framework.

Basic Routing

A very basic Laravel routes is simply expressed as following-

It accept two parameters URL and Closure (Closure is basically a anonymous function can be passed as a parameter to other functions).

These are the simplest routes defined as they really don’t require you pass to anything other than corresponding view. You need not to login or pass any parameters in their route definition.

Basic routing mostly used to display static pages in our site. Suppose you have some static pages as Home, About Us, Services and a Contact page in your site, and you want them to be routed as following –

Home page:
http://localhost:8000/

About Us page:
http://localhost:8000/about

Services page:
http://localhost:8000/services

Contact page:
http://localhost:8000/contact

All our static pages (Home, About Us, Services and Contact) will be routed as following in our app/Http/routes.php file.

 

Route Parameters

Sometime you may want to pass some parameters along with the URL, it can be either required or optional to pass parameters. There are two ways to pass the parameters along with the URL –

Required Parameters

As per this route definition, it is mandatory to pass the specified parameters in the URL. For example, if you want ID must be passed within the URL to perform some action based on that ID. Route definition for this will be as following –

Optional Parameters

As per this route definition, it is optional to pass the specified parameters in the URL. Optional parameters can be indicated by placing a ? mark after the parameter name, make sure to set default value for the corresponding parameter. Route definition with optional parameter will be as following –

As per the above route definition it is optional to pass “name“, default value for “name” is “Mark“.

Regular Expression Constraints

Sometime you may want to constrain or specify your route parameter’s value, it can be simply done using the where method. The where method simply accepts two parameters that is the name of the parameter and a regular expression to match parameter’s value.

Let’s have look on following route definitions –

Global Constraints

If you want a route parameter to be constrained by a given regular expression globally for all route definitions. It can be defined using pattern method in the boot method of your RouteServiceProvider.

For example if you want route parameter id to be numeric for all route definitions, it can done as following –

Named Routes

Named routes gives you a way to assign easy to remember alias/name for URLs. It can be simply using the as key while creating route definition.

Named route definition for controller actions –

Alternatively, you can define it using chain the name method at the end of the route definition –

Accessing Named Routes

Named routes can be access in your controller, view or anywhere in application as following –

Route Groups

Route groups gives you way to group a set of routes (Routes sharing common route attributes such as namespaces or middleware) in single route definition instead of defining those attributes individually.

Assign Middleware

Assign Namespaces

Route Prefixes

Route Prefixes allows you to define prefix for each route in a group by using prefix group array attribute. Suppose you are creating a CMS where you have a admin panel, you would prefer to have admin as prefix for set of routes belongs to admin panel. Then it can defined as following –

Router Methods for other HTTP Requests

Route::post(‘url’, ‘closure’) :- It is used to create an Item
Route::put(‘url’, ‘closure’) :- It is used to update an Item
Route::delete(‘url’, ‘closure’) :- It is used to delete an Item
Route::match(‘[‘get’, ‘post’]’,’url’, ‘closure’) :- It is used to define a route that responds to more than one type of HTTP requests.
Route::any(‘url’, ‘closure’) :- This responds to all types of HTTP requests.

Laravel Configuration

The config directory contains all of your application’s configuration files.

Directory Permissions

After installing Laravel it is required to set the write permission for the storage and bootstrap/cache directory otherwise laravel will not work.

Application configuration

The application configuration information is located in /config/app.php. You can set or change various parameters for your application from here.

Debugging mode

Locate the following code

From here you can set debug mode.

Time zone
Locate the following code

From here you can set your preferred time zone, default is UTC

Application Key

Locate the following code

from here you can set encryption key for your application, it required to generate application key for security purpose.

Environmental Configuration

After installing Laravel; .env file is automatically created in root directory of your application. If it is not created; simply rename the .env.example file to .env file. This file contains various environment variables for your application.

Your .env file should resemble something similar to this.

Note: The first line in the above code snippet APP_ENV=local has been set. It can further be changed to production or testing as per your requirement.

Authentication configuration

The authentication configuration file is located in /config/auth.php, you can change it as per your application requirements.

Database configuration

The database configuration file is located in /config/database.php. In this file you can set different parameters for database, based on the database engine you are using. Below is configuration code for MySQL Database –

Replace <host-name>, <database-name>, <user-name> and <password> with your hostname, database name, username and password correspondingly.

Naming the Application

The default namespace for laravel application is App; but if you want to change it to match your application name, which can be easily done using app:name Artisan command.

Replace <application-name> with the application name of your choice.

Maintenance Mode

Sometimes, you may need to put your application into maintenance mode for upgrades. This will make your application temporarily unavailable for public access. You don’t want errors to pop up when you are going through the important updates in the background, right?
Laravel made it easier for you, there are artisan commands available to start and stop the maintenance without any hassle.

Command to start Laravel Maintenance Mode

To put application into maintenance mode, execute the following command.

Command to stop Laravel Maintenance Mode

Once you are done with upgrading application or making changes to it and want to make it live again, execute the following command.

There is a default template for maintenance mode is located in resources/views/errors/503.blade.php. You are free to customize it as per your application requirement.

 

Laravel Application Structure

Laravel Root Directory

S.No. Directory/File Description
1 /app This directory contains all of your application’s core code
2 /bootstrap This directory contains all those files required to bootstrap the framework and configure auto-loading
3 /config This directory contains all the application configuration files
4 /database This directory contains all the database migrations and seeds. It can also be used to store the SQLite DB
5 /public This directory contains the front controllers and all the application assets such as images, CSS and JavaScript
6 /resources This directory contains views , language files and un-compiled assets such as LESS, SASS or JavaScript
7 /routes This directory contacins all of the route definitions for your application.
8 /storage This directory contains compiled blade templates, filed based sessions and file cache
9 /tests This directory contains all your automated unit tests for application
10 /vendor This directory contains all the composer dependencies

Laravel App Directory

S.No. Directory/File Description
1 /app/Console This directory contains all of your artisan commands
2 /app/Events This directory contains all your event classes, though it is not created by default
3 /app/Exceptions This directory contains all your exception handlers
4 /app/Http This is directory contains all your controllers, middleware and form requests
5 /app/Jobs This directory contains all queueable jobs, though it is not created by default
6 /app/Listeners This directory contains event handler classes, though it is not created by default
7 /app/Mail This directory contains all your classes required to send emails, though it is not created by default
8 /app/Notifications This directory contains all the notifications sent by application, though it is not created by default
9 /app/Policies This directory contains all the authorization policy classes for your application, though it is not created by default
10 /app/Providers This directory contains all of the service providers for your application.

Laravel Framework Files

S.No. Directory/File Description
1 .env It contains environment variables for application
2 .env.example It contains environment variables for application
3 .gitattributes It is Git configuration files
4 .gitignore It is Git configuration files
5 artisan It allows you to run Artisan commands
6 composer.json It is configuration file for Composer
7 composer.lock It is configuration file for Composer
8 gulpfile.js It is configuration file for Elixir and Gulp
9 package.json It is like composer.json but for frontend assets
10 phpunit.xml It is is a configuration file for PHPUnit
11 readme.md It contains general information about framework
12 server.php It works as internal web server

Laravel History

Back in 2011 codeIgniter was one of the most popular and widely used web application development framework written in PHP. Codeigniter was the most preferred PHP framework that time, because it was easy to learn, well documented and had great support from its community and creators. Web developers could quickly start developing applications using codeigniter. But codeigniter was lacking some of very essential features that time such as user authorization and authentication. Taylor Otwell, started the development of Laravel as to find more advanced alternative to the CodeIgniter framework, as Taylor Otwell believed that codeigniter is lacking certain essential features required in building web applications.

Laravel 1
In June 9, 2011 Laravel’s first beta version was released and just within a month Laravel 1 released. Laravel 1 came with built-in support for all the major features like authentication, routing, localization, sessions, models, views.

Laravel 2

Laravel 1 was lacking support for controllers which prevented it to be considered as true MVC framework. In September 2011, Laravel 2 released with built-in support for controllers, templating system called Blade and inversion of control principle.Laravel 2 was considered as fully MVC compliant framework. But in Laravel 2 support for third-party packages is removed.

Laravel 3

In February 2012, Laravel 3 released with some great new features included such as Artisan command line interface, migration system for database, event handling, more session drivers and database drivers and a packaging system called Bundles. Laravel 3 was the most stable release of Laravel framework at that time, from this point of time Laravel framework started to gain popularity and user base.

Laravel 4

In May 2013, Laravel 4 was released and is codenamed as Illuminate. Laravel 4 was considered to be completely re-written version of Laravel framework. It was a major release of the framework included features like Composer, database seeding and support for message queues.

Laravel 5

In February 2015, Laravel 5 was released with majorly internal changes in core framework.

The latest stable version of Laravel is 5.4

 

Laravel Installation

Server Requirements

  • PHP >= 5.6.4
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension

Installing Laravel Using Composer

Step 1 – Download composer and install it on your system from the link given below

Step 2 – Open command prompt and browse to web server root directory or localhost folder (Assuming you have installed WAMP server in C:\wamp , open C:\wamp\www).

Step 3 – Type the following command there to create new Laravel project using composer

Replace mylaravel with your project name.

Step 4 – Test the installation

Open the following link in your web browser.

Replace mylaravel with your project name.