Category: Tutorial

https://cdn3d.iconscout.com/3d/premium/thumb/blog-writing-3d-icon-download-in-png-blend-fbx-gltf-file-formats–creative-content-article-marketing-pack-business-icons-6578772.png?f=webp

  • Authentication

    Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated.

    Command

    Laravel uses the following command to create forms and the associated controllers to perform authentication −

    php artisan make:auth
    

    This command helps in creating authentication scaffolding successfully, as shown in the following screenshot −

    Authentication

    Controller

    The controller which is used for the authentication process is HomeController.

    <?php
    
    namespace App\Http\Controllers;
    
    use App\Http\Requests;
    use Illuminate\Http\Request;
    
    class HomeController extends Controller{
       /**
    
      * Create a new controller instance.
      *
      * @return void
    */ public function __construct() {
      $this-&gt;middleware('auth');
    } /**
      * Show the application dashboard.
      *
      * @return \Illuminate\Http\Response
    */ public function index() {
      return view('home');
    } }

    As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below −

    Login

    Login Page

    Registration

    Register

    Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

    Manually Authenticating Users

    Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password.

    Consider the following lines of code for LoginController which includes all the functions for authentication −

    <?php
    
    // Authentication mechanism
    namespace App\Http\Controllers;
    
    use Illuminate\Support\Facades\Auth;
    
    class LoginController extends Controller{
       /**
    
      * Handling authentication request
      *
      * @return Response
    */ public function authenticate() {
      if (Auth::attempt(&#91;'email' =&gt; $email, 'password' =&gt; $password])) {
      
         // Authentication passed...
         return redirect()-&gt;intended('dashboard');
      }
    } }
  • CSRF Protection

    CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized activities which the authenticated users of the system perform. As such, many web applications are prone to these attacks.

    Laravel offers CSRF protection in the following way −

    Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These tokens verify that the operations or requests are sent by the concerned authenticated user.

    Implementation

    The implementation of CSRF protection in Laravel is discussed in detail in this section. The following points are notable before proceeding further on CSRF protection −

    • CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below −
    <form method = "POST" action="/profile">
       {{ csrf_field() }}
       ...
    </form>
    
    • You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request.
    • The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library.

    Form without CSRF token

    Consider the following lines of code. They show a form which takes two parameters as input: email and message.

    <form>
       <label> Email </label>
    
      &lt;input type = "text" name = "email"/&gt;
      &lt;br/&gt;
    <label> Message </label> <input type="text" name = "message"/> <input type = ”submit” name = ”submitButton” value = ”submit”> </form>

    The result of the above code is the form shown below which the end user can view −

    Contact Form

    The form shown above will accept any input information from an authorized user. This may make the web application prone to various attacks.

    Please note that the submit button includes functionality in the controller section. The postContact function is used in controllers for that associated views. It is shown below −

    public function postContact(Request $request) {
       return $request-> all();
    }
    

    Observe that the form does not include any CSRF tokens so the sensitive information shared as input parameters are prone to various attacks.

    Form with CSRF token

    The following lines of code shows you the form re-designed using CSRF tokens −

    <form method = ”post” >
       {{ csrf_field() }}
       <label> Email </label>
       <input type = "text" name = "email"/>
       <br/>
       <label> Message </label>
       <input type = "text" name = "message"/>
       <input type = ”submit” name = ”submitButton” value = ”submit”>
    </form>

    The output achieved will return JSON with a token as given below −

    {
       "token": "ghfleifxDSUYEW9WE67877CXNVFJKL",
       "name": "TutorialsPoint",
       "email": "[email protected]"
    }
    

    This is the CSRF token created on clicking the submit button.

  • Contracts

    Laravel contracts are a set of interfaces with various functionalities and core services provided by the framework.

    For example, Illuminate\Contracts\Queue\Queue contract uses a method which is needed for queuing jobs and Illuminate\Contracts\Mail\Mailer uses the method for sending emails.

    Every contract defined includes corresponding implementation of the framework. All the Laravel contracts are available in the GitHub repository as mentioned below −

    This repository provides a variety of contracts available in the Laravel framework which can be downloaded and used accordingly.

    Important Points

    While working with Laravel contracts, please note the following important points −

    • It is mandatory to define facades in the constructor of a class.
    • Contracts are explicitly defined in the classes and you need not define the contracts in constructors.

    Example

    Consider the contract used for Authorization in Laravel which is mentioned below −

    <?php
    
    namespace Illuminate\Contracts\Auth\Access;
    
    interface Authorizable{
       /**
    
      * Determine if the entity has a given ability.
      *
      * @param string $ability
      * @param array|mixed $arguments
      * @return bool
    */ public function can($ability, $arguments = []); }

    The contract uses a function can which includes a parameter named ability and arguments which uses the user identification in the form of an array.

    You will have to define a contract as shown in the syntax below −

    interface <contract-name>
    

    Contracts are used like facades for creating robust, well-tested Laravel applications. There are various practical differences with usage of contracts and facades.

    The following code shows using a contract for caching a repository −

    <?php
    
    namespace App\Orders;
    use Illuminate\Contracts\Cache\Repository as Cache;
    
    class Repository{
       /**
    
      * The cache instance.
    */ protected $cache; /**
      * Create a new repository instance.
      *
      * @param Cache $cache
      * @return void
    */ public function __construct(Cache $cache) {
      $this-&gt;cache = $cache;
    } }

    Contract contains no implementation and new dependencies; it is easy to write an alternative implementation of a specified contract, thus a user can replace cache implementation without modifying any code base.

  • Facades

    Facades provide a static interface to classes that are available in the application’s service container. Laravel facades serve as static proxies to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods.

    How to create Facade

    The following are the steps to create Facade in Laravel −

    • Step 1 − Create PHP Class File.
    • Step 2 − Bind that class to Service Provider.
    • Step 3 − Register that ServiceProvider toConfig\app.php as providers.
    • Step 4 − Create Class which is this class extends tolluminate\Support\Facades\Facade.
    • Step 5 − Register point 4 to Config\app.php as aliases.

    Facade Class Reference

    Laravel ships with many Facades. The following table show the in-built Facade class references −

    FacadeClassService Container Binding
    AppIlluminate\Foundation\Applicationapp
    ArtisanIlluminate\Contracts\Console\Kernelartisan
    AuthIlluminate\Auth\AuthManagerauth
    Auth (Instance)Illuminate\Auth\Guard
    BladeIlluminate\View\Compilers\BladeCompilerblade.compiler
    BusIlluminate\Contracts\Bus\Dispatcher
    CacheIlluminate\Cache\Repositorycache
    ConfigIlluminate\Config\Repositoryconfig
    CookieIlluminate\Cookie\CookieJarcookie
    CryptIlluminate\Encryption\Encrypterencrypter
    DBIlluminate\Database\DatabaseManagerdb
    DB (Instance)Illuminate\Database\Connection
    EventIlluminate\Events\Dispatcherevents
    FileIlluminate\Filesystem\Filesystemfiles
    GateIlluminate\Contracts\Auth\Access\Gate
    HashIlluminate\Contracts\Hashing\Hasherhash
    InputIlluminate\Http\Requestrequest
    LangIlluminate\Translation\Translatortranslator
    LogIlluminate\Log\Writerlog
    MailIlluminate\Mail\Mailermailer
    PasswordIlluminate\Auth\Passwords\PasswordBrokerauth.password
    QueueIlluminate\Queue\QueueManagerqueue
    Queue (Instance)Illuminate\Queue\QueueInterface
    Queue (Base Class)Illuminate\Queue\Queue
    RedirectIlluminate\Routing\Redirectorredirect
    RedisIlluminate\Redis\Databaseredis
    RequestIlluminate\Http\Requestrequest
    ResponseIlluminate\Contracts\Routing\ResponseFactory
    RouteIlluminate\Routing\Routerrouter
    SchemaIlluminate\Database\Schema\Blueprint
    SessionIlluminate\Session\SessionManagersession
    Session (Instance)Illuminate\Session\Store
    StorageIlluminate\Contracts\Filesystem\Factoryfilesystem
    URLIlluminate\Routing\UrlGeneratorurl
    ValidatorIlluminate\Validation\Factoryvalidator
    Validator (Instance)Illuminate\Validation\Validator
    ViewIlluminate\View\Factoryview
    View (Instance)Illuminate\View\View

    Example

    Step 1 − Create a service provider called TestFacadesServiceProvider by executing the following command.

    php artisan make:provider TestFacadesServiceProvider
    

    Step 2 − After successful execution, you will receive the following output −

    FacadesServiceProvider

    Step 3 − Create a class called TestFacades.php at App/Test.

    App/Test/TestFacades.php

    <?php
       namespace App\Test;
       class TestFacades{
    
      public function testingFacades() {
         echo "Testing the Facades in Laravel.";
      }
    } ?>

    Step 4 − Create a Facade class called “TestFacades.php” at “App/Test/Facades”.

    App/Test/Facades/TestFacades.php

    <?php
    
    namespace app\Test\Facades;
    
    use Illuminate\Support\Facades\Facade;
    
    class TestFacades extends Facade {
       protected static function getFacadeAccessor() { return 'test'; }
    }

    Step 5 − Create a Facade class called TestFacadesServiceProviders.php at App/Test/Facades.

    App/Providers/TestFacadesServiceProviders.php

    <?php
    
    namespace App\Providers;
    
    use App;
    use Illuminate\Support\ServiceProvider;
    
    class TestFacadesServiceProvider extends ServiceProvider {
       public function boot() {
    
      //
    } public function register() {
      App::bind('test',function() {
         return new \App\Test\TestFacades;
      });
    } }

    Step 6 − Add a service provider in a file config/app.php as shown in the below figure.

    config/app.php

    Service Provider

    Step 7 − Add an alias in a file config/app.php as shown in the below figure.

    config/app.php

    Alias

    Step 8 − Add the following lines in app/Http/routes.php.

    app/Http/routes.php

    Route::get('/facadeex', function() {
       return TestFacades::testingFacades();
    });
    

    Step 9 − Visit the following URL to test the Facade.

    http://localhost:8000/facadeex
    

    Step 10 − After visiting the URL, you will receive the following output −

    Testing Facades
  • Event Handling

    Events provide a simple observer implementation which allows a user to subscribe and listen to various events triggered in the web application. All the event classes in Laravel are stored in the app/Events folder and the listeners are stored in the app/Listeners folder.

    The artisan command for generating events and listeners in your web application is shown below −

    php artisan event:generate
    

    This command generates the events and listeners to the respective folders as discussed above.

    Event Generator

    Events and Listeners serve a great way to decouple a web application, since one event can have multiple listeners which are independent of each other. The events folder created by the artisan command includes the following two files: event.php and SomeEvent.php. They are shown here −

    Event.php

    <?php
    namespace App\Events;
    abstract class Event{
       //
    }

    As mentioned above, event.php includes the basic definition of class Event and calls for namespace App\Events. Please note that the user defined or custom events are created in this file.

    SomeEvent.php

    <?php
    
    namespace App\Events;
    
    use App\Events\Event;
    use Illuminate\Queue\SerializesModels;
    use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
    
    class SomeEvent extends Event{
       use SerializesModels;
       /**
    
      * Create a new event instance.
      *
      * @return void
    */ public function __construct() {
      //
    } /**
      * Get the channels the event should be broadcast on.
      *
      * @return array
    */ public function broadcastOn() {
      return &#91;];
    } }

    Observe that this file uses serialization for broadcasting events in a web application and that the necessary parameters are also initialized in this file.

    For example, if we need to initialize order variable in the constructor for registering an event, we can do it in the following way −

    public function __construct(Order $order) {
       $this->order = $order;
    }

    Listeners

    Listeners handle all the activities mentioned in an event that is being registered. The artisan command event:generate creates all the listeners in the app/listeners directory. The Listeners folder includes a file EventListener.php which has all the methods required for handling listeners.

    EventListener.php

    <?php
    
    namespace App\Listeners;
    
    use App\Events\SomeEvent;
    use Illuminate\Queue\InteractsWithQueue;
    use Illuminate\Contracts\Queue\ShouldQueue;
    
    class EventListener{
       /**
    
      * Create the event listener.
      *
      * @return void
    */ public function __construct() {
      //
    } /**
      * Handle the event.
      *
      * @param SomeEvent $event
      * @return void
    */ public function handle(SomeEvent $event) {
      //
    } }

    As mentioned in the code, it includes handle function for managing various events. We can create various independent listeners that target a single event.

  • Error HandlingError Handling

    Most web applications have specific mechanisms for error handling. Using these, they track errors and exceptions, and log them to analyze the performance. In this chapter, you will read about error handling in Laravel applications.

    Important Points

    Before proceeding further to learn in detail about error handling in Laravel, please note the following important points −

    • For any new project, Laravel logs errors and exceptions in the App\Exceptions\Handler class, by default. They are then submitted back to the user for analysis.
    • When your Laravel application is set in debug mode, detailed error messages with stack traces will be shown on every error that occurs within your web application.
    Error Log
    • By default, debug mode is set to false and you can change it to true. This enables the user to track all errors with stack traces.
    App Debug
    • The configuration of Laravel project includes the debug option which determines how much information about an error is to be displayed to the user. By default in a web application, the option is set to the value defined in the environment variables of the .env file.
      • The value is set to true in a local development environment and is set to false in a production environment.
      • If the value is set to true in a production environment, the risk of sharing sensitive information with the end users is higher.

    Error Log

    Logging the errors in a web application helps to track them and in planning a strategy for removing them. The log information can be configured in the web application in config/app.php file. Please note the following points while dealing with Error Log in Laravel −

    • Laravel uses monolog PHP logging library.
    • The logging parameters used for error tracking are single, daily, syslog and errorlog.
    • For example, if you wish to log the error messages in log files, you should set the log value in your app configuration to daily as shown in the command below −
    'log' => env('APP_LOG',’daily’),
    
    • If the daily log mode is taken as the parameter, Laravel takes error log for a period of 5 days, by default. If you wish to change the maximum number of log files, you have to set the parameter of log_max_files in the configuration file to a desired value.
    ‘log_max_files’ => 25;
    

    Severity Levels

    As Laravel uses monolog PHP logging library, there are various parameters used for analyzing severity levels. Various severity levels that are available are error, critical, alert and emergency messages. You can set the severity level as shown in the command below −

    'log_level' => env('APP_LOG_LEVEL', 'error')
    
  • Ajax

    Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications. Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function.

    json() function syntax

    json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)
    

    Example

    Step 1 − Create a view file called resources/views/message.php and copy the following code in that file.

    <html>
       <head>
    
      &lt;title&gt;Ajax Example&lt;/title&gt;
      
      &lt;script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"&gt;
      &lt;/script&gt;
      
      &lt;script&gt;
         function getMessage() {
            $.ajax({
               type:'POST',
               url:'/getmsg',
               data:'_token = &lt;?php echo csrf_token() ?&gt;',
               success:function(data) {
                  $("#msg").html(data.msg);
               }
            });
         }
      &lt;/script&gt;
    </head> <body>
      &lt;div id = 'msg'&gt;This message will be replaced using Ajax. 
         Click the button to replace the message.&lt;/div&gt;
      &lt;?php
         echo Form::button('Replace Message',&#91;'onClick'=&gt;'getMessage()']);
      ?&gt;
    </body> </html>

    Step 2 − Create a controller called AjaxController by executing the following command.

    php artisan make:controller AjaxController --plain
    

    Step 3 − After successful execution, you will receive the following output −

    AjaxController

    Step 4 − Copy the following code in

    app/Http/Controllers/AjaxController.php file.

    app/Http/Controllers/AjaxController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    
    class AjaxController extends Controller {
       public function index() {
    
      $msg = "This is a simple message.";
      return response()-&gt;json(array('msg'=&gt; $msg), 200);
    } }

    Step 5 − Add the following lines in app/Http/routes.php.

    app/Http/routes.php

    Route::get('ajax',function() {
       return view('message');
    });
    Route::post('/getmsg','AjaxController@index');
    

    Step 6 − Visit the following URL to test the Ajax functionality.

    http://localhost:8000/ajax
    

    Step 7 − You will be redirected to a page where you will see a message as shown in the following image.

    Replace Message

    Step 8 − The output will appear as shown in the following image after clicking the button.

    Simple Message
  • Sending Email

    Laravel uses free feature-rich library SwiftMailer to send emails. Using the library function, we can easily send emails without too many hassles. The e-mail templates are loaded in the same way as views, which means you can use the Blade syntax and inject data into your templates.

    The following table shows the syntax and attributes of send function −

    Syntaxvoid send(string|array $view, array $data, Closure|string $callback)
    Parameters$view(string|array) − name of the view that contains email message$data(array) − array of data to pass to view$callback − a Closure callback which receives a message instance, allowing you to customize the recipients, subject, and other aspects of the mail message
    Returnsnothing
    DescriptionSends email.

    In the third argument, the $callback closure received message instance and with that instance we can also call the following functions and alter the message as shown below.

    • $message → subject(‘Welcome to the Tutorials Point’);
    • $message → from(’[email protected]’, ‘Mr. Example’);
    • $message → to(’[email protected]’, ‘Mr. Example’);

    Some of the less common methods include −

    To attach or embed files, you can use the following methods −

    • $message → attach(‘path/to/attachment.txt’);
    • $message → embed(‘path/to/attachment.jpg’);

    Mail can be sent as HTML or text. You can indicate the type of mail that you want to send in the first argument by passing an array as shown below. The default type is HTML. If you want to send plain text mail then use the following syntax.

    Syntax

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

    In this syntax, the first argument takes an array. Use text as the key name of the view as value of the key.

    Example

    Step 1 − We will now send an email from Gmail account and for that you need to configure your Gmail account in Laravel environment file – .env file. Enable 2-step verification in your Gmail account and create an application specific password followed by changing the .env parameters as shown below.

    .env

    MAIL_DRIVER = smtp
    MAIL_HOST = smtp.gmail.com
    MAIL_PORT = 587
    MAIL_USERNAME = your-gmail-username
    MAIL_PASSWORD = your-application-specific-password
    MAIL_ENCRYPTION = tls
    

    Step 2 − After changing the .env file execute the below two commands to clear the cache and restart the Laravel server.

    php artisan config:cache
    

    Step 3 − Create a controller called MailController by executing the following command.

    php artisan make:controller MailController --plain
    

    Step 4 − After successful execution, you will receive the following output −

    MailController

    Step 5 − Copy the following code in

    app/Http/Controllers/MailController.php file.

    app/Http/Controllers/MailController.php

    <?php
    
    namespace App\Http\Controllers;
    use Illuminate\Http\Request;
    use Mail;
    
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    
    class MailController extends Controller {
       public function basic_email() {
    
      $data = array('name'=&gt;"Virat Gandhi");
      Mail::send(&#91;'text'=&gt;'mail'], $data, function($message) {
         $message-&gt;to('[email protected]', 'Tutorials Point')-&gt;subject
            ('Laravel Basic Testing Mail');
         $message-&gt;from('[email protected]','Virat Gandhi');
      });
      echo "Basic Email Sent. Check your inbox.";
    } public function html_email() {
      $data = array('name'=&gt;"Virat Gandhi");
      Mail::send('mail', $data, function($message) {
         $message-&gt;to('[email protected]', 'Tutorials Point')-&gt;subject
            ('Laravel HTML Testing Mail');
         $message-&gt;from('[email protected]','Virat Gandhi');
      });
      echo "HTML Email Sent. Check your inbox.";
    } public function attachment_email() {
      $data = array('name'=&gt;"Virat Gandhi");
      Mail::send('mail', $data, function($message) {
         $message-&gt;to('[email protected]', 'Tutorials Point')-&gt;subject
            ('Laravel Testing Mail with Attachment');
         $message-&gt;attach('C:\laravel-master\laravel\public\uploads\image.png');
         $message-&gt;attach('C:\laravel-master\laravel\public\uploads\test.txt');
         $message-&gt;from('[email protected]','Virat Gandhi');
      });
      echo "Email Sent with attachment. Check your inbox.";
    } }

    Step 6 − Copy the following code in resources/views/mail.blade.php file.

    resources/views/mail.blade.php

    <h1>Hi, {{ $name }}</h1>
    l<p>Sending Mail from Laravel.</p>
    

    Step 7 − Add the following lines in app/Http/routes.php.

    app/Http/routes.php

    Route::get('sendbasicemail','MailController@basic_email');
    Route::get('sendhtmlemail','MailController@html_email');
    Route::get('sendattachmentemail','MailController@attachment_email');
    

    Step 8 − Visit the following URL to test basic email.

    http://localhost:8000/sendbasicemail
    

    Step 9 − The output screen will look something like this. Check your inbox to see the basic email output.

    Basic Email Sent

    Step 10 − Visit the following URL to test the HTML email.

    http://localhost:8000/sendhtmlemail
    

    Step 11 − The output screen will look something like this. Check your inbox to see the html email output.

    HTML Email

    Step 12 − Visit the following URL to test the HTML email with attachment.

    http://localhost:8000/sendattachmentemail
    

    Step 13 − You can see the following output

    Email Sent

    Note − In the MailController.php file the email address in the from method should be the email address from which you can send email address. Generally, it should be the email address configured on your server.

  • File Uploading

    Uploading Files in Laravel is very easy. All we need to do is to create a view file where a user can select a file to be uploaded and a controller where uploaded files will be processed.

    In a view file, we need to generate a file input by adding the following line of code.

    Form::file('file_name');
    

    In Form::open(), we need to add ‘files’=>’true’ as shown below. This facilitates the form to be uploaded in multiple parts.

    Form::open(array('url' => '/uploadfile','files'=>'true'));
    

    Example

    Step 1 − Create a view file called resources/views/uploadfile.php and copy the following code in that file.

    resources/views/uploadfile.php

    <html>
       <body>
    
      &lt;?php
         echo Form::open(array('url' =&gt; '/uploadfile','files'=&gt;'true'));
         echo 'Select the file to upload.';
         echo Form::file('image');
         echo Form::submit('Upload File');
         echo Form::close();
      ?&gt;
    </body> </html>

    Step 2 − Create a controller called UploadFileController by executing the following command.

    php artisan make:controller UploadFileController --plain
    

    Step 3 − After successful execution, you will receive the following output −

    UploadFileController

    Step 4 − Copy the following code in

    app/Http/Controllers/UploadFileController.php file.

    app/Http/Controllers/UploadFileController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    
    class UploadFileController extends Controller {
       public function index() {
    
      return view('uploadfile');
    } public function showUploadFile(Request $request) {
      $file = $request-&gt;file('image');
      //Display File Name
      echo 'File Name: '.$file-&gt;getClientOriginalName();
      echo '&lt;br&gt;';
      //Display File Extension
      echo 'File Extension: '.$file-&gt;getClientOriginalExtension();
      echo '&lt;br&gt;';
      //Display File Real Path
      echo 'File Real Path: '.$file-&gt;getRealPath();
      echo '&lt;br&gt;';
      //Display File Size
      echo 'File Size: '.$file-&gt;getSize();
      echo '&lt;br&gt;';
      //Display File Mime Type
      echo 'File Mime Type: '.$file-&gt;getMimeType();
      //Move Uploaded File
      $destinationPath = 'uploads';
      $file-&gt;move($destinationPath,$file-&gt;getClientOriginalName());
    } }

    Step 5 − Add the following lines in app/Http/routes.php.

    app/Http/routes.php

    Route::get('/uploadfile','UploadFileController@index');
    Route::post('/uploadfile','UploadFileController@showUploadFile');
    

    Step 6 − Visit the following URL to test the upload file functionality.

    http://localhost:8000/uploadfile
    

    Step 7 − You will receive a prompt as shown in the following image.

    Browse File
  • Validation

    Validation is the most important aspect while designing an application. It validates the incoming data. By default, base controller class uses a ValidatesRequests trait which provides a convenient method to validate incoming HTTP requests with a variety of powerful validation rules.

    Available Validation Rules in Laravel

    Laravel will always check for errors in the session data, and automatically bind them to the view if they are available. So, it is important to note that a $errors variable will always be available in all of your views on every request, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The following table shows all available validation rules in Laravel.

    Available Validation Rules in Laravel
    AcceptedActive URLAfter (Date)
    AlphaAlpha DashAlpha Numeric
    ArrayBefore (Date)Between
    BooleanConfirmedDate
    Date FormatDifferentDigits
    Digits BetweenE-MailExists (Database)
    Image (File)InInteger
    IP AddressJSONMax
    MIME Types(File)MinNot In
    NumericRegular ExpressionRequired
    Required IfRequired UnlessRequired With
    Required With AllRequired WithoutRequired Without All
    SameSizeString
    TimezoneUnique (Database)URL

    The $errors variable will be an instance of Illuminate\Support\MessageBag. Error message can be displayed in view file by adding the code as shown below.

    @if (count($errors) > 0)
       <div class = "alert alert-danger">
    
      &lt;ul&gt;
         @foreach ($errors-&gt;all() as $error)
            &lt;li&gt;{{ $error }}&lt;/li&gt;
         @endforeach
      &lt;/ul&gt;
    </div> @endif

    Example

    Step 1 − Create a controller called ValidationController by executing the following command.

    php artisan make:controller ValidationController --plain
    

    Step 2 − After successful execution, you will receive the following output −

    ValidationController

    Step 3 − Copy the following code in

    app/Http/Controllers/ValidationController.php file.

    app/Http/Controllers/ValidationController.php

    <?php
    
    namespace App\Http\Controllers;
    
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\Http\Controllers\Controller;
    
    class ValidationController extends Controller {
       public function showform() {
    
      return view('login');
    } public function validateform(Request $request) {
      print_r($request-&gt;all());
      $this-&gt;validate($request,&#91;
         'username'=&gt;'required|max:8',
         'password'=&gt;'required'
      ]);
    } }

    Step 4 − Create a view file called resources/views/login.blade.php and copy the following code in that file.

    resources/views/login.blade.php

    <html>
       
       <head>
    
      &lt;title&gt;Login Form&lt;/title&gt;
    </head> <body>
      
      @if (count($errors) &gt; 0)
         &lt;div class = "alert alert-danger"&gt;
            &lt;ul&gt;
               @foreach ($errors-&gt;all() as $error)
                  &lt;li&gt;{{ $error }}&lt;/li&gt;
               @endforeach
            &lt;/ul&gt;
         &lt;/div&gt;
      @endif
      
      &lt;?php
         echo Form::open(array('url'=&gt;'/validation'));
      ?&gt;
      
      &lt;table border = '1'&gt;
         &lt;tr&gt;
            &lt;td align = 'center' colspan = '2'&gt;Login&lt;/td&gt;
         &lt;/tr&gt;
         &lt;tr&gt;
            &lt;td&gt;Username&lt;/td&gt;
            &lt;td&gt;&lt;?php echo Form::text('username'); ?&gt;&lt;/td&gt;
         &lt;/tr&gt;
         &lt;tr&gt;
            &lt;td&gt;Password&lt;/td&gt;
            &lt;td&gt;&lt;?php echo Form::password('password'); ?&gt;&lt;/td&gt;
         &lt;/tr&gt;
         &lt;tr&gt;
            &lt;td align = 'center' colspan = '2'
               &gt;&lt;?php echo Form::submit('Login'); ?  &gt;&lt;/td&gt;
         &lt;/tr&gt;
      &lt;/table&gt;
      
      &lt;?php
         echo Form::close();
      ?&gt;
    </body> </html>

    Step 5 − Add the following lines in app/Http/routes.php.

    app/Http/routes.php

    Route::get('/validation','ValidationController@showform');
    Route::post('/validation','ValidationController@validateform');
    

    Step 6 − Visit the following URL to test the validation.

    http://localhost:8000/validation
    

    Step 7 − Click the “Login” button without entering anything in the text field. The output will be as shown in the following image.

    Login