Select Page

Overview:

Laravel is a PHP based web framework for building robust web solutions quickly.  It includes tools that help automate some of the low-level tasks in creating a website so that you don’t have to build them from scratch.  Many things are ready to go almost immediately and require little to no setup.

Pros include:

  • It is free and open-source
  • You can work with the database directly from the command line with ‘Artisan’, Laravel’s library of db interactive functions
  • There is built in unit testing features and versioning
  • It is relatively easy to set up and configure
  • It includes built in security
  • It is scalable, allowing your web applications to grow over time
  • You save time because you don’t have to worry about a lot of the website must-haves as they are already included, such as mail setup and form validation
  • Includes namespaces and interfaces to help better organize / manage resources

Features:

  • Built in libraries and modules
  • Testability features
  • The use of routes to allow easy Create, Read, Update and Delete (CRUD) implementation
  • Query Builder and Eloquent ORM to help with database management and interaction 
  • A built-in mail class that helps in sending mail with rich content and attachments
  • Authentication help with things like registration, forgot password, send password reminders etc
  • Redis – connects to existing sessions and general-purpose cache
  • Queues – like emailing large number of users or using specified cron jobs

Useful Packages

(You can install these through Composer)

  • Cashier
    • Interface for managing subscription billing services from Stripe, like coupons and invoices
  • Envoy
    • Helps define common tasks you can run on remote servers.  Set up tasks for deployment, Artisan commands etc.
  • Socialite
    • Allows you to authenticate with different OAuth providers
  • Passport 
    • Full OAuth2 server implementation
  • Scout
    • Adds full-text search functionality
  • Dusk
    • Easy-to-use browser automation and testing APIs
  • Horizon
    • Dashboard for Redis queues
  • Telescope
    • Gives insight into incoming requests, exceptions, log entries, db queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps and more
  • Sanctum
    • Authentication system for Single Page Applications (SPAs), mobile apps, and APIs
  • Jetstream and Fortify
    • Application scaffolds for Laravel that work well together

Artisan

  • What it is:
    • This is the Command Line Interface (CLI) that Laravel uses.  It contains a lot of functionality now all accessible directly from the CLI.
  • What it does:
    • Use it to manage database migrations and seed the database, publish package assets, build boilerplate code and much more

Full list of available Artisan commands is available here.  https://laravel.com/docs/8.x/artisan

List of helpful commands to know is here.  https://8bityard.com/artisan-commands-in-laravel/

Routing

Is essential in Laravel. It lets you pass all your application requests to the right controller. The main and primary routes in Laravel accept a URI (Uniform Resource Identifier) and a closure.

Middleware

Lets you filter HTTP requests entered into your project. Let us assume a situation where this middleware of Laravel checks for an authenticated user of your software or project. In case the authentication is verified as valid, the middleware feature will let the user proceed with your project. There is another middleware name CORS in charge of adding appropriate headers to all of your responses.

It’s a middle-man acting in coordination between a request and a response. As mentioned in the above test scenario, if the user is not authenticated, your project may redirect that user from the login.php to index.php page.

Syntax:

php artisan make:middleware<middleware_name>

Here, you have to replace the <middleware_name> with your middleware. You can see this path location app/Http/Middleware the middleware that you will be creating your project.

Example:

php artisan make:middleware CheckUser

Root directory structure is as follows:

DirectoryDescription
appHolds your base code.
bootstrapHas all bootstrapping scripts.
configHolds all project configuration files (.config).
databaseHolds project database files.
publicHolds necessary files such as JavaScript, CSS, and images of your project.
resourcesHolds all the Sass files, language files and templates.
routesHas all the definition files for routing, such as console.php, api.php, channels.php, etc.
storageHolds session files, cache, compiled templates as well as miscellaneous files generated by the framework.
testHolds all test cases.
vendorHolds all composer dependency files.

The app directory structure is as follows:

DirectoryDescription
ConsoleContains all project artisan commands.
EventsHolds event files that laravel may pop up. Used to send messages to other parts of the project.
ExceptionsContains the project’s exception handling files, handling all exceptions thrown.
HttpHolds different filters, requests, and controllers.
JobsHolds all jobs. Created when you type artisan command: make:job
ListenersHolds all handler class to receive and handle events.
MailHolds all emails sent through the project. Create with command: make:mail
NotificationsHas all transactional notifications sent through the project. Create with command: make:notification
PoliciesHolds different policies for the project.
ProvidersContains different service providers.
RulesHold all objects used for custom validation rules. Create with command: make:rule

Directory Structure

By default, the directory structure of Laravel is meant to meet the requirement for both large and small application development. But there is a provision to organize your application according to the way you like. Laravel doesn’t put up any compulsion and restriction on locating your given class anywhere – providing the composer can is free to load that class automatically. So in this chapter, you will be learning about the two different directories of Laravel. So let us dig deep into it.

App Structure

The configuration of the Laravel application deals through the ‘config’ subdirectory, which holds the entire configuration file related to your Laravel project. This subdirectory keeps files like a database, mailing, services, and session-based configuration files with an extension of .config. The configuration of the Laravel project permits you to define configuration per-environment. In this tutorial, you will learn about the different configurations and how the basic setup is done in Laravel.

Installation

Laravel framework needs few requirements for getting installed on your system. A virtual machine has fulfilled each of these system requirements, Laravel’s Homestead, hence it is a must to implement Homestead as the Laravel development environment for your local system.

Moreover, in case you do not use this virtual machine, the following requirements must be fulfilled:

  • PHP having version 7.0 or upper version
  • An OpenSSL extension for PHP
  • A PDO extension for PHP
  • Mbstring extension for PHP
  • Tokenizer extension for PHP
  • XML extension for PHP

Composer

Laravel implements a composer for managing dependencies within it. Hence, before the use of Laravel, it needs to check whether you have a composer setup on your system or not.

If you don’t have Composer installed on your computer, first visit this URL to download Composer:

https://getcomposer.org/download/

When you are done installing the Composer, cross-check whether it is installed or not by typing in the command prompt the composer command. You can see the Composer screen in that CMD only.

It needs to be kept in mind to put the Composer’s system-wide vendor in the bin directory within your $PATH; as a result, your system can locate the executable of laravel. Depending on which operating system you are using, this directory will exist. Still, for PCs having OS like MAC and Linux, it will be:

macOS: $HOME/.composer/vendor/bin

Linux OS: $HOME/.config/composer/vendor/bin

Setup Laravel using Installer

First of all, you have to download the Installer of Laravel with the help of Composer, like this:

composer global require “laravel/installer”

When the installation is done, a new command of laravel will start a new fresh installation in that directory you provide.

laravel new directory_name

Create a Project

The next thing you have to do is make a new folder in some specific path within your system for keeping your Laravel projects. Move to that location where the directory is created. For installing the Laravel, the following command you have to type:

composer create-project laravel/laravel – prefer -dist

The command mentioned above will make Laravel installed on that specific directory. Type the next command:

php artisan serve

This above code will start the Laravel service. A black screen will appear showing the message: Laravel Development server started on http://localhost:8080.

Copy and paste: http://localhost:8080 in your browser, and you can see the Laravel home screen appears in your browser.

Composer

Laravel implements a composer for managing dependencies within it. Hence, before the use of Laravel, it needs to check whether you have a composer setup on your system or not.

If you don’t have Composer installed on your computer, first visit this URL to download Composer:

https://getcomposer.org/download/

When you are done installing the Composer, cross-check whether it is installed or not by typing in the command prompt the composer command. You can see the Composer screen in that CMD only.

It needs to be kept in mind to put the Composer’s system-wide vendor in the bin directory within your $PATH; as a result, your system can locate the executable of laravel. Depending on which operating system you are using, this directory will exist. Still, for PCs having OS like MAC and Linux, it will be:

macOS: $HOME/.composer/vendor/bin

Linux OS: $HOME/.config/composer/vendor/bin

Setup Laravel using Installer

First of all, you have to download the Installer of Laravel with the help of Composer, like this:

composer global require “laravel/installer”

When the installation is done, a new command of laravel will start a new fresh installation in that directory you provide.

laravel new directory_name

Create a Project

The next thing you have to do is make a new folder in some specific path within your system for keeping your Laravel projects. Move to that location where the directory is created. For installing the Laravel, the following command you have to type:

composer create-project laravel/laravel – prefer -dist

The command mentioned above will make Laravel installed on that specific directory. Type the next command:

php artisan serve

This above code will start the Laravel service. A black screen will appear showing the message: Laravel Development server started on http://localhost:8080.

Copy and paste: http://localhost:8080 in your browser, and you can see the Laravel home screen appears in your browser.

Configuring the Basic in Laravel Project

If you are new to Laravel, you should know that you can create a configuration file for the Laravel application. And after installing Laravel, you need to perform the permission writing for your storage directory along with the bootstrap/cache.

Next, you have to generate the application key for session securing and encrypted data keys. In case the root directory doesn’t have the .env file, in that case, you will have to rename the file .env.example to .env and run the command mentioned below where you’ve installed the Laravel:

php artisan key: generate

You can see in the .env file the newly generated key. Moreover, it is also possible to configure the time zone as well as a locale in the config/app.php file of your project.

Configuring the Environment

Laravel allows us to run an application for diverse environments like testing, production, etc. For configuring your application’s environment, you will need the .env file in the project’s root directory. When you install the composer for Laravel, this file is generated or created automatically by the composer. If you don’t install, then rename the specific file with the name .env.example to .env only.

Configuring the Database

You can configure the database for your application using the config/database.php file of your project. Setting the configuration constraint utilized by various databases can also be done, and Laravel also allowed us to use the default one.

Maintenance Modes

Websites are regularly modified. As s a developer for this, you have to put your site in maintenance mode. In this advanced framework, it becomes easier to do that by using two artisan commands. Let’s see how to use the commands:

For starting your project maintenance approach, the following command is required:

php artisan down

After changing the required stuff, when it is time to re-run your project, the following command is needed:

php artisan up

Routing

Routing is one of the essential concepts in Laravel. Routing in Laravel allows you to route all your application requests to its appropriate controller. The main and primary routes in Laravel acknowledge and accept a URI (Uniform Resource Identifier) along with a closure, given that it should have to be a simple and expressive way of routing. In this chapter, you will learn about the routing concept of Laravel.

Create Routes in Laravel

All the routes in Laravel are defined within the route files that you can find in the routes sub-directory. These route files get loaded and generated automatically by the Laravel framework. The application’s route file gets defined in the app/Http/routes.php file. The general routing in Laravel for each of the possible request looks something like this:

http://localhost/

Route:: get (‘/’, function () {

return ‘Welcome to index’;

});

http://localhost/user/dashboard

Route:: post(‘user/dashboard’, function () {

   return ‘Welcome to dashboard’;

});

http://localhost/user/add

Route:: put(‘user/add’, function () {

//

});

http://localhost/post/example

Route:: delete(‘post/example’, function () {

//

});

The Routing Mechanism in Laravel

The routing mechanism takes place in three different steps:

  1. First of all, you have to create and run the root URL of your project.
  2. The URL you run needs to be matched exactly with your method defined in the root.php file, and it will execute all related functions.
  3. The function invokes the template files. It then calls the view() function with the file name located in resources/views/, and eliminates the file extension blade.php at the time of calling.

Example:

app/Http/routes.php

<?php

Route:: get (‘/’, function () {

   return view(‘laravel’);

});

resources/view/laravel.blade.php

<html>

<head>

   <title>Laravel5 Tutorial</title>

</head>

<body>

   <h2>Laravel5 Tutorial</h2>

   <p>Welcome to Laravel5 tutorial.</p>

</body>

</html>

The Routing Mechanism in Laravel

The routing mechanism takes place in three different steps:

  1. First of all, you have to create and run the root URL of your project.
  2. The URL you run needs to be matched exactly with your method defined in the root.php file, and it will execute all related functions.
  3. The function invokes the template files. It then calls the view() function with the file name located in resources/views/, and eliminates the file extension blade.php at the time of calling.

Example:

app/Http/routes.php

<?php

Route:: get (‘/’, function () {

   return view(‘laravel’);

});

resources/view/laravel.blade.php

<html>

<head>

   <title>Laravel5 Tutorial</title>

</head>

<body>

   <h2>Laravel5 Tutorial</h2>

   <p>Welcome to Laravel5 tutorial.</p>

</body>

</html>

Route Parameters

In many cases, within your application, a situation arises when you had to capture the parameters send ahead through the URL. For using these passed parameters effectively, in Laravel, you have to change the routes.php code.

Laravel provides two ways of capturing the passed parameter:

  • Required parameter
  • Optional Parameter

Required Parameters

At times you had to work with a segment(s) of the URL (Uniform Resource Locator) in your project. Route parameters are encapsulated within {} (curly-braces) with alphabets inside. Let us take an example where you have to capture the customer’s ID or employee from the generated URL.

Example:

Route :: get (’emp/{id}’, function ($id) {

    echo ‘Emp ‘.$id;

});

Optional Parameter

Many parameters do not remain present within the URL, but the developers had to use them. So such parameters get indicated by a “?” (question mark sign) following the parameter’s name.

Example:

Route :: get (’emp/{desig?}’, function ($desig = null) {

    echo $desig;

});

Route :: get (’emp/{name?}’, function ($name = ‘Guest’) {

    echo $name;

});

Middleware

Middleware is another essential component of Laravel and provides the method to filter HTTP requests that get entered into your project. Let us assume a situation where this middleware of Laravel checks for an authenticated user of your software or project. In case the authentication is verified as valid, the middleware feature will let the user proceed with your project. There is another middleware name CORS in charge of adding appropriate headers to all of your responses.

Define Middleware

Middleware can be defined as a middle-man or interface acting in coordination between a request and a response. As mentioned in the above test scenario, if the user is not authenticated, your project may redirect that user from the login.php to index.php page.

You can create your middleware by running the syntax mentioned below:

Syntax:

php artisan make:middleware<middleware_name>

Here, you have to replace the <middleware_name> with your middleware. You can see this path location app/Http/Middleware the middleware that you will be creating your project.

Example:

php artisan make:middleware CheckUser

Registering Middleware

Before using any middleware, you have to register it.

Laravel provides two types of Middlewares. These are:

  • Global Middleware
  • Route Middleware

Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app/Http/Kernel.php class, you can list all the global middleware for your project.

When you want a middleware to specific routes, you have to add the middleware with a key for your app/Http/Kernel.php file, and such middlewares are called route middleware. $routeMiddleware, by default, holds entries for the middleware that are already incorporated in Laravel. For adding your custom middleware, you need to append them to the list and add a key of your choice.

Example:

rotected $routeMiddleware = [

   ‘auth’ => \Illuminate\Auth\Middleware\Authenticate::class,

   ‘auth.basic’ => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,

   ‘guest’ => \App\Http\Middleware\RedirectIfAuthenticated::class,

   ‘userAuth’ => \Illuminate\Routing\Middleware\UserAuthRequests::class,

];

Middleware Parameters

Parameters can also be passed to middlewares. Various parameterized situations can be when your project has attributes like a customer, employee, admin, owner, etc. You want to execute different modules based on the user’s roles; for those situations, middlewares’ parameters become useful.

Example:

public function handle($request, Closure $next, $profile)

   {

       if (! $request->user()->hasProfile($profile)) {

           // Next page

       }

       return $next($request);

   }

}

It would help if you created the Profile middleware by running the code mentioned below:

php artisan make:middleware ProfileMiddleware

The newly created middleware can be handled using the code: app/Http/Middleware/ProfileMiddleware.php

Example:

<?php

namespace App\Http\Middleware;

use Closure;

class ProfileMiddleware {

   public function handle($request, Closure $next, $Profile) {

      echo “Role: “.$Profile;

      return $next($request);

   }

}

Terminable Middleware

These are special types of middlewares that start working right after any response is sent to the browser. The terminate method is used for achieving this. When a termination method is used in your project’s middleware, it gets called automatically after the browser response is sent.

Example:

<?php

namespace Illuminate\Session\Middleware;

use Closure;

class SessionBegin

{

    public function handle($request, Closure $next)

    {

        return $next($request);

    }

    public function terminate($request, $response)

    {

        // tasks assigned within terminate method

    }

}

Controllers

Controllers are another essential feature provided by Laravel. In place of defining the handling request logic in the form of Closures in route files, it is possible to organize this process with the help of Controller classes. So what the controllers do? Controllers are meant to group associated request handling logic within a single class. In your Laravel project, they are stored in the app/Http/Controllers’ directory. The full form of MVC is Model View Controller, which act as directing traffic among the Views and the Models.

Creating Controllers

Open your CMD or terminal and type the command:

Syntax:

php artisan make:controller <controller-name> –plain

Replace this <controller-name> in the above syntax with your controller. This will eventually make a plain constructor since you are passing the argument –plain.

The controller that you have created can be invoked from within the routes.php file using this syntax below-

Example:

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

A basic controller code-snippet will look something like this, and you have to create in the directory like app/Http/Controller/AdminController.php:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class AdminController extends Controller

 {

 //

 }

Controller Middleware

You can assign controllers to middlewares to route in the route files of your project using the command below:

Example:

Route::get(‘profile’, ‘AdminController@show’)->middleware(‘auth’);

Middleware methods from the controller help to easily assign middleware to the controller’s action and activity. Restrictions on implementing certain methods can also be provided to middlewares on the controller class.

class AdminController extends Controller

{

    public function __construct()

    {

        // function body

    }

}

Using closures, controllers may allow laravel developers to register middleware.

$this->middleware(function ($request, $next) {

    // middleware statements;

    return $next($request);

}

);

Resource Controllers

The resource route of Laravel allows the classic “CRUD” routes for controllers having a single line of code. This can be created quickly using the make: controller command (Artisan command) something like this”

Example:

php artisan make:controller PasswordController –resource

The above code will produce a controller in app/Http/Controllers/ location with file name PasswordController.php which will hold a method for all available tasks of resources.

Laravel developers also have the freedom to register multiple resource controllers at a time by passing an array to resource method something like this –

Route::resources([

    ‘password’ => ‘PasswordController’,

    ‘picture’ => ‘DpController’

]

);

Actions Handled by Resource Controllers

VerbURIActionRoute Name
GET/usersUsers listusers.index
POST/users/addAdd a new userusers.add
GET/users/{user}Get userusers.show
GET/users/{user}/editEdit userusers.edit
PUT/users/{user}Update userusers.update
DELETE/users/{user}Delete userusers.destroy

Implicit Controllers

These types of controllers allow developers to define a single route for handling multiple actions within the controller. The syntax of using this is by:

Example:

Route::controller(‘base URI’,'<class-name-of-the-controller>’);

It is where your Implicit controller file will get stored: app/Http/Controllers/ImplicitController.php; and will look have to script like:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class ImplicitController extends Controller {

   public function getIndex(){

      echo ‘starting method’;

   }

   public function getVal($id){

      echo ‘show value’;

   }

   public function getAdminData(){

      echo ‘admin data method’;

   }   

   public function adminPassword(){

      echo ‘password method’;

   }

}

Constructor and Method Injection

The service container of Laravel is used for resolving all Laravel Controllers. So, controller injection lets Laravel developers to type-hint the dependencies which your controller may require within its constructor. On the other hand, method injection allows you to type-hint dependencies for the controller’s action method in your Laravel project.

Emails

Another important feature of Laravel is providing clean and simple API use, which is free and rich in library features – “SwiftMailer,” which is used for sending emails. With the help of its library functions, Laravel developers find it easy to send emails without any hurdles. Developers can use blade syntax to inject data within a template because email templates are loaded in the same way as views.

The syntax looks something like this:

Syntax:

void send(string|array $view, array $data, Closure|string $callback)

Here void indicates that this will not return any value, string|array $view provides the view name which is having the email message. $data(array) is the set of data that has to be passed to view. $callback holds the capability to customize recipients’ subject and other mail details as a closure callback that gets received as message instance.

Different Methods of Mailing System

The third argument in the above function takes the instance of message and there are some following functions which helps performing the mailing interaction better. These are:

  • $message -> subject(‘Laravel Tutorial’);
  • $message ->from(‘testuser@example.com’, ‘anyname’);
  • $message ->to(‘alex@example.com’, ‘Alex’);

Other commonly used methods are:

  • $message ->sender(‘testuser@example.com’, ‘anyname’);
  • $message ->returnPath(‘testuser@example.com’);
  • $message ->cc(‘testuser@example.com’, ‘anyname’);
  • $message ->bcc(‘neha@example.com’, ‘Neha’);
  • $message ->replyTo(‘testuser@example.com’, ‘anyname’);
  • $message ->priority(4);

For sending plain text mail, you have to use the syntax shown below:

Mail::send([‘text’=>’text.view’], $data, $callback);

This entire syntax is in the form of an array-key-value format, where the first argument took in the form of the array followed by text and name-of-view as key-value pair.

Steps to Send Email in Laravel

So the theme is to send an email via Gmail account and need the Laravel environment file, which is .env file to configure with your Gmail account. The environment file contains the script:

MAIL_DRIVER = smtp

MAIL_HOST = smtp.gmail.com

MAIL_PORT = 587

MAIL_USERNAME = developers-Gmail-username

MAIL_PASSWORD = developers-password

MAIL_ENCRYPTION = tls

Next, you have to clear the cache and restart your Laravel server. For that, you have to use the following commands:

php artisan config:cache

Then for creating MailController, you have to type and run the command given below:

php artisan make:controller MailController –plain

Then you have to setup the inside content of the MailController.php file, and for this, you have to write the script mentioned below:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Mail;

use App\Http\Requests;

use App\Http\Controllers\Controller;

class SendMailController extends Controller

{

    public function txt_mail()

    {

        $info = array(

            ‘name’ => “Alex”

        );

        Mail::send([‘text’ => ‘mail’], $info, function ($message)

        {

            $message->to(‘alex@example.com’, ‘W3SCHOOLS’)

                ->subject(‘Basic test eMail from W3schools.’);

            $message->from(‘sender@example.com’, ‘Alex’);

        });

        echo “Successfully sent the email”;

    }

    public function html_mail()

    {

        $info = array(

            ‘name’ => “Alex”

        );

        Mail::send(‘mail’, $info, function ($message)

        {

            $message->to(‘alex@example.com’, ‘w3schools’)

                ->subject(‘HTML test eMail from W3schools.’);

            $message->from(‘karlosray@gmail.com’, ‘Alex’);

        });

        echo “Successfully sent the email”;

    }

    public function attached_mail()

    {

        $info = array(

            ‘name’ => “Alex”

        );

        Mail::send(‘mail’, $info, function ($message)

        {

            $message->to(‘alex@example.com’, ‘w3schools’)

                ->subject(‘Test eMail with an attachment from W3schools.’);

            $message->attach(‘D:\laravel_main\laravel\public\uploads\pic.jpg’);

            $message->attach(‘D:\laravel_main\laravel\public\uploads\message_mail.txt’);

            $message->from(‘karlosray@gmail.com’, ‘Alex’);

        });

        echo “Successfully sent the email”;

    }

}

In this file location resources/views/mail.blade.php, you have to type the below-mentioned command:

<h1> Hello, {{ $name }} </h1>

<p> Laravel MAIL System </p>

Also, add the script in routes.php files with the following commands:

Route::get(‘sendtxtmail’,’MailController@txt_mail’);

Route::get(‘sendhtmlmail’,’MailController@html_mail’);

Route::get(‘sendattachedemail’,’MailController@attached_email’);

For testing the setup and output, type the following URLs:

  1. http://localhost:8000/sendtxtmail
  2. http://localhost:8000/sendhtmlmail
  3. http://localhost:8000/sendattachedmail

Links

https://www.w3schools.in/laravel-tutorial/#