PHP Laravel Tutorial for Beginners: What Is Laravel Framework

This Laravel tutorial introduces the PHP Laravel Framework, explains what is Laravel, how to install it, MVC architecture, and various components:

Laravel Framework is a free and open-source web framework for PHP. It is used to develop complex web applications. It is based on the Model-View-Controller (MVC) architectural design pattern.

You will learn about the history, features, advantages, architecture, installation, and components of the Laravel Framework.

Laravel Tutorial for Beginners

List Of Laravel Tutorials

Tutorial #1: PHP Laravel Tutorial for Beginners (This Tutorial)
Tutorial #2: Laravel Database, Migrations, Eloquent ORM And Tinker
Tutorial #3: Laravel Forms And Validation Rules With Example 
Tutorial #4: Laravel Session, File Upload/Download And Permissions
Tutorial #5: Laravel Collection And Laravel Forge Tutorial
Tutorial #6: Laravel Interview Questions And Answers


What Is Laravel

History:

The Laravel Framework was developed by Taylor Otwell and released to the public in the year 2011.

The following table shows the different versions of Laravel.

VersionDate of ReleasePHP Version Support
1.0June 2011-------------------------------------------
2.0September 2011-------------------------------------------
3.0February 22nd, 2012-------------------------------------------
4.0May 28th, 2013Minimum 5.3.0
5.0February 4th, 2015Minimum 5.4.0
5.1June 9th, 2015Minimum 5.5.9
5.2December 21st, 2015Between 5.5.9 and 7.1.*
5.3August 23rd, 2016Between 5.6.4 and 7.1.*
5.4January 24th, 20175.6.4 or above
5.5August 30th, 20177.0.0 or above
5.6February 7th, 20187.1.3 or above
5.7September 4th, 20187.1.3 or above
5.8February 26th, 20197.1.3 or above
6.xSeptember 3rd, 20197.2.0 or above
7.xMarch 3rd, 20207.2.5 or above
8.xLaravel 8 is yet to be released (in 2020)7.3.0 or above

Note: In this Laravel tutorial, we have used Laravel version 7 in all the examples.

Popularity:

There are lots of frameworks available in the industry such as Laravel, Symfony, Codeigniter, Yii, CakePHP, and Zend framework for PHP.

So what do you think, which one is the most popular PHP Framework? The answer is Laravel.

The following screenshot of Google Trends shows the analysis of the popularity of different PHP frameworks.

analysis of the popularity of different PHP frameworks

[image source]

Advantages:

The following list shows some advantages of the Laravel Framework.

  • Follows MVC architectural design pattern
  • Free and open-source
  • Easy to learn
  • Good documentation support
  • Easy to integrate
  • High performance and efficiency
  • A high level of security

Features:

Laravel has a rich set of features. These are as follows:

  • Modularity: Laravel has many built-in libraries and modules which help developers to build responsive and modular PHP web applications. This feature also speeds up development.
  • Lazy Collection: It handles heavy loads of data with the minimum usage of memory.
  • Eloquent ORM: ORM stands for Object Relation Mapping. Laravel has a built-in ORM called Eloquent which handles database related operations.
  • Artisan: Artisan is the command-line interface used in Laravel.
  • Blade templates: Laravel has a concept called Blade, which creates a unique template to display data.
  • Unit testing: Test cases can be used to perform unit testing in Laravel.
  • Email support: Laravel has a built-in class called Mail, which helps to send emails.
  • Authentication: Authentication is used to identify the users of the system. It is usually achieved by identifying the username and password of the user.

MVC Architecture Of Laravel

The Laravel Framework follows MVC architecture. MVC is an architectural design pattern that helps to develop web applications faster. MVC stands for Model-View-Controller.

  • Model (M)–A model handles data used by the web application.
  • View (V)–A view helps to display data to the user.
  • Controller (C)–A controller interacts with the model to create data for the view.

The following screenshot shows the interactions between Model, View, and Controller.

 MVC Architecture

[image source]

Pre-requisites For Laravel

Before proceeding further with this tutorial, you need to be familiar with the following concepts.

  • HTML and CSS
  • Core PHP and Advanced PHP
  • Web application development using PHP and MySQL
  • MVC architecture (we have already covered some basics of MVC architecture in this tutorial)

Install Laravel Framework 7 For Windows

Prerequisites for Installing Laravel 7:

Before installing the Laravel Framework, install the following programs on your computer. PHP version 7.2.5 is the minimum compatible version of PHP for Laravel version 7.

  • Web Server such as Apache
  • PHP version 7.2.5 or above version
  • PHP extensions*
    • BCMath PHP Extension
    • Ctype PHP Extension
    • Fileinfo PHP extension
    • JSON PHP Extension
    • Mbstring PHP Extension
    • OpenSSL PHP Extension
    • PDO PHP Extension
    • Tokenizer PHP Extension
    • XML PHP Extension
  • MySQL
  • Composer (See the next topic for the URL to download and install Composer)

*Note: Above PHP extensions might be pre-installed on your system.

Composer

Composer is a dependency manager for PHP. Laravel uses the Composer to manage its dependencies.

You need to install the composer before installing Laravel. If you have not installed the composer, visit the following URL to download and install the composer.

Run the following command in the command prompt to check whether or not you have successfully installed the composer on your computer.

composer

If you have installed the composer successfully, a screen similar to below will be displayed. It also shows the installed version of the composer.

composer

Download Laravel Installer

Run the following command in the command prompt to download the Laravel installer on your computer using the composer.

composer global require laravel/installer

Creating First Laravel PHP Project

Run the following command in the command prompt to create a new Laravel PHP project named laravel-tutorial (you can use any name) using the composer. It will create the Laravel project in the current directory.

composer create-project --prefer-dist laravel/laravel laravel-tutorial

Running First Laravel PHP Project On Localhost

Go to the Laravel PHP project folder in the command prompt by running the following command.

cd laravel-tutorial

Then, run the following command in the command prompt to start the Laravel development server.

php artisan serve

The following screenshot shows the output of the above command.

php artisan serve

Copy the above URL: http://127.0.0.1:8000 and open it in a web browser.

If you have run the Laravel project successfully you will see a screen similar to below.

Laravel project successfully

Congratulations! You have successfully run your first Laravel project.

Laravel PHP Project Structure

The project structure consists of directories, sub-directories, and files.

Note: A directory is also known as a folder.

Open your project from the File Explorer to see the root directory structure of the Laravel project. You will see a screen similar to below.

project directory structure

The following list describes some important directories, sub-directories, and files in a typical Laravel project:

  • app directory: This directory is one of the most important directories in the root. The app directory contains the source code of the web application. It includes the following sub-directories and the User.php file.
    • Console directory: This directory contains artisan commands required for Laravel.
    • Exceptions directory: This directory contains exception handlers.
    • Http directory: This directory contains sub-directories for Controllers and Middleware.
    • Providers directory: This directory contains all the service providers.
    • User.php file: This is the default Model provided by Laravel.
  • bootstrap directory: This directory contains files related to bootstrap the Laravel PHP application.
  • config directory: This directory contains various configuration files required for the Laravel PHP application.
  • database directory: This directory contains files related to the database. It includes the following sub-directories and the .gitignore file.
    • factories directory: This directory generates many data records.
    • migrations directory: This directory contains files related to database migrations.
    • seeds directory: This directory contains classes used for the unit testing database.
  • public directory: This directory contains files that help to initialize the Laravel PHP application.
  • resources directory: This directory contains HTML files, CSS files, JavaScript files, and blade templates. It includes the following sub-directories.
    • js directory: This directory contains files related to JavaScript.
    • lang directory: This directory contains files for localization and internalization.
    • saas directory: This directory contains files such as SCSS files.
    • views directory: This directory contains HTML files or templates which help to display data to the user.
  • routes directory: This directory contains all the routes definitions for the Laravel PHP application.
  • storage directory: This directory contains cache files, session files, etc.
  • tests directory: This directory contains test files such as unit test files.
  • vendor directory: This directory contains all the composer dependency packages.
  • .env file: This file includes environmental variables.
  • composer.json file: This file is a configuration file that specifies dependencies.
  • package.json file: This file is similar to the composer.json file but it is for the frontend.
  • and few more files

Introduction To Laravel Routes

Routing accepts the request and redirects it to the relevant controller function.

There are two main route files in the Laravel Framework:

  • routes/web.php: This file is used to register web routes.
  • routes/api.php: This file is used to register API routes.

The following code segment shows the default web route registered by Laravel to display the welcome page.

Route::get('/', function () {
    return view('welcome');
});

In the above route, Route is the class used to define the function get(). The function get() has a parameter “/” which indicates the root URL of the Laravel application.

The following screenshot shows the output of the above route.

Route output

The following command can be run in the command prompt to get the full list of registered routes.

php artisan route:list

Creating a Route

Step 1: Add the following code segment in routes/web.php file to register a new route.

Route::get('/example', function () {
    return "Hello World!!!";
});

Step 2: Visit the URL: http://127.0.0.1:8000/example to see the output.

Step 3: The following screenshot shows the output.

route (output)

Routing Parameters

The Laravel Framework uses two types of route parameters.

#1) Required parameters

The required parameters are the parameters that pass to the URL as shown below.

Route::get('user/{name}', function ($name='Paul') {  
    return $name;  
});

#2) Optional parameters

Place “?” after the router parameter to make it optional as shown below.

Route::get('user/{name?}', function ($name='Paul') {  
    return $name;  
});

Named Routes

In the following route, the report controller will call the function showReport with parameters as the report.

Route::get(student/report, 'ReportController@showReport')->name(report);

Laravel Controllers

In MVC architecture, the character ‘C’ stands for Controller. A controller communicates with the relevant model if necessary and loads the view to display the content for the user.

All the controllers are stored in the app/Http/Controllers directory.

Creating a Controller

Run the following command in the command prompt to create a controller named UserContoller.

php artisan make:controller UserController

This command will create a file named UserController.php in the app/Http/Controllers directory. By default, the Controller.php file is included with the Laravel Framework.

Calling Controllers from Routes

The following syntax can be used to call controllers from routes.

Route::get(‘base URI’,’controller@method’);

Let’s see an example.

Step 1: Add the following code segment in the routes/web.php file to register a new route.

Route::get('/assessment', 'AssessmentController@index');

Step 2: Run the following command in the command prompt to create a controller named AssessmentController.

php artisan make:controller AssessmentController

This command will create a file named AssessementController.php in the app/Http/Controllers directory.

Step 3: Create the index function in the AssessementController as shown below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AssessmentController extends Controller
{
    public function index()
    {        
        return view('assessment');
    }
}

Step 4: Create a view named assessment.php in the resources/views directory and save the following code.

<!DOCTYPE html>
<html lang="en">
    <body>
        <h1>Laravel Assessment</h1>
    </body>
</html>

Step 5: Visit the URL: http://127.0.0.1:8000/assessment to see the output.

Step 6: The following screenshot shows the output.

calling controllers from routes (output)

Restful Resource Controllers

There are seven restful resource controllers in the Laravel Framework.

Run the following command in the command prompt to create restful resource controllers.

php artisan make:controller StudentController --resource

This command will create a file named StudentContoller.php in the app/Http/Controllers directory and it contains functions for each resource action.

The following route can be used to register a restful route.

Route::resource('/students', 'StudentController');

The following table shows the actions handled by the Restful Resource Controllers:

Request TypePath (URI)ActionRoute NameUse
GET/studentsindexstudents.indexget all students
GET/students /createcreatestudents.createcreate a new student
POST/studentsstorestudents.storestore student details
GET/students /{student}showstudents.showget student details
GET/students /{student}/editeditstudents.editedit student
PUT/PATCH/students /{student}updatestudents.updateupdate student
DELETE/students /{student}destroystudents.destroydelete student

What Is Middleware

In simple words, middleware is a bridge between a request and a response. It provides a mechanism to filter HTTP requests.

All the middleware files are stored in the app/Http/Middleware directory.

The Laravel Framework has a middleware to check whether the user of the Laravel application is authenticated or not. If the user is authenticated, it directs to the home page and if the user is not authenticated, it redirects to the login page.

Creating a Middleware

Step 1: Run the following command in the command prompt to create a middleware called CheckUser.

php artisan make:middleware CheckUser

This command will create a file named CheckUser.php in the app/Http/Middleware directory.

Step 2: Open the CheckUser.php file and modify the existing code as shown below.

<?php

namespace App\Http\Middleware;

use Closure;

class CheckUser
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
public function handle($request, Closure $next)
    {
        echo "Test Middleware <br>";
        return $next($request);
    }
}

Step 3: Open the Kernel.php file in the app/Http directory and add the path of the CheckUser middleware as shown below.

protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
    'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
    'check' => \App\Http\Middleware\CheckUser::class,
];

Step 4: Add the following code segment in the routes/web.php file to register a new route.

Route::get('/test, 'UserController@create')->middleware('check');

Step 5: We have already created the User Controller. Open the UserController.php file and modify the existing code as shown below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function create()
    {        
        return view('assessment');
    }
}

Step 4: Visit the following URL: http://127.0.0.1:8000/test to see the output.

Step 5: The following screenshot shows the output.

middleware (output)

Introduction To Terminable Middleware

Run the following command in the command prompt to create a terminable middleware named TerminateMiddleware.

php artisan make:middleware TerminateMiddleware

This command will create a file named TerminateMiddleware.php in the app/Http/Middleware directory.

Terminable middleware works right after any response sent to the browser.

Introduction To Views

In MVC architecture, the character ‘V’ stands for View. Views contain HTML, CSS and JavaScript. The Views represent the frontend of the Laravel application, and it is used to display the content for the user.

All the views are stored in the resources/views directory. By default, the Laravel Framework provides the welcome.blade.php file.

Creating a View

Step 1: Create a view named index.php in the resources/views directory and save the following code.

<!DOCTYPE html>
<html lang="en">
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

Step 2: Add the following code segment in the routes/web.php file to register a new route.

Route::get('/index', function () {
    return view('index');
});

Step 3: Visit the URL: http://127.0.0.1:8000/index to see the output.

Step 4: The following screenshot shows the output.

create a view (output)

Passing Data to Views

Let’s do an example to see how data can be passed to the view.

Step 1: Create a view named user.php in the resources/views directory and save the following code.

<!DOCTYPE html>
<html lang="en">
    <body>
        <p><?php echo 'My name is '.$name ?></p>
    </body>
</html>

Step 2: Add the following code segment in the routes/web.php file to register a new route.

Route::get('/user', function () {
    return view('user', ['name' => 'John']);
});

Step 3: Visit the URL: http://127.0.0.1:8000/user to see the output.

Step 4: The following screenshot shows the output.

passing data to views (output)

Introduction To Blade Templates

Blade templates use .blade.php extension. The blade templates stored in the resources/views directory.

Usage of Blade Templates

  • Usage 1: variable values

In blade templates, we can use {{ $variable }} to print the value of a variable instead of <?php echo $variable ?> As you see, there is no need to write PHP tags or the echo keyword.

Let’s do an example!

Earlier, we created the user.php file using the following code.

<!DOCTYPE html>
<html lang="en">
    <body>
        <p><?php echo 'My name is '.$name ?></p>
    </body>
</html>

Step 1: Rename the file user.php to user.blade.php (in the resources/views directory) and modify the existing code as shown below.

<!DOCTYPE html>
<html lang="en">
    <body>
        <p>My name is {{ $name }}</p>
    </body>
</html>

Step 2: Visit the URL: http://127.0.0.1:8000/user.

You will get the same output as the previous example as shown below.

Usage 1 – variable values

  • Usage 2: ternary operators

In blade templates, we can use {{ $variable or ‘default_value’ }} instead of <?phpisset($variable) ? $variable : ?default_value? ?> to write ternary operators.

Conclusion

The Laravel Framework is a popular, free, and open-source MVC based web framework for PHP. It is used to develop complex PHP web applications. In Laravel, registered routes direct the request to the relevant function of the controller. Then the controller communicates with the relevant model, if necessary, and loads the view to display the content for the user.

Middleware acts as a bridge between a request and a response. Laravel uses a special concept called Blade to design a unique layout to display data, and it can be used by other views.

We hope you found this Laravel tutorial helpful! In the next Laravel Tutorial, we will discuss database related functions of Laravel.

Happy learning!

NEXT Tutorial >>