Laravel – Quick Guide

Laravel – Quick Guide ”; Previous Next Laravel – Overview Laravel is an open-source PHP framework, which is robust and easy to understand. It follows a model-view-controller design pattern. Laravel reuses the existing components of different frameworks which helps in creating a web application. The web application thus designed is more structured and pragmatic. Laravel offers a rich set of functionalities which incorporates the basic features of PHP frameworks like CodeIgniter, Yii and other programming languages like Ruby on Rails. Laravel has a very rich set of features which will boost the speed of web development. If you are familiar with Core PHP and Advanced PHP, Laravel will make your task easier. It saves a lot time if you are planning to develop a website from scratch. Moreover, a website built in Laravel is secure and prevents several web attacks. Advantages of Laravel Laravel offers you the following advantages, when you are designing a web application based on it − The web application becomes more scalable, owing to the Laravel framework. Considerable time is saved in designing the web application, since Laravel reuses the components from other framework in developing web application. It includes namespaces and interfaces, thus helps to organize and manage resources. Composer Composer is a tool which includes all the dependencies and libraries. It allows a user to create a project with respect to the mentioned framework (for example, those used in Laravel installation). Third party libraries can be installed easily with help of composer. All the dependencies are noted in composer.json file which is placed in the source folder. Artisan Command line interface used in Laravel is called Artisan. It includes a set of commands which assists in building a web application. These commands are incorporated from Symphony framework, resulting in add-on features in Laravel 5.1 (latest version of Laravel). Features of Laravel Laravel offers the following key features which makes it an ideal choice for designing web applications − Modularity Laravel provides 20 built in libraries and modules which helps in enhancement of the application. Every module is integrated with Composer dependency manager which eases updates. Testability Laravel includes features and helpers which helps in testing through various test cases. This feature helps in maintaining the code as per the requirements. Routing Laravel provides a flexible approach to the user to define routes in the web application. Routing helps to scale the application in a better way and increases its performance. Configuration Management A web application designed in Laravel will be running on different environments, which means that there will be a constant change in its configuration. Laravel provides a consistent approach to handle the configuration in an efficient way. Query Builder and ORM Laravel incorporates a query builder which helps in querying databases using various simple chain methods. It provides ORM (Object Relational Mapper) and ActiveRecord implementation called Eloquent. Schema Builder Schema Builder maintains the database definitions and schema in PHP code. It also maintains a track of changes with respect to database migrations. Template Engine Laravel uses the Blade Template engine, a lightweight template language used to design hierarchical blocks and layouts with predefined blocks that include dynamic content. E-mail Laravel includes a mail class which helps in sending mail with rich content and attachments from the web application. Authentication User authentication is a common feature in web applications. Laravel eases designing authentication as it includes features such as register, forgot password and send password reminders. Redis Laravel uses Redis to connect to an existing session and general-purpose cache. Redis interacts with session directly. Queues Laravel includes queue services like emailing large number of users or a specified Cron job. These queues help in completing tasks in an easier manner without waiting for the previous task to be completed. Event and Command Bus Laravel 5.1 includes Command Bus which helps in executing commands and dispatch events in a simple way. The commands in Laravel act as per the application’s lifecycle. Laravel – Installation For managing dependencies, Laravel uses composer. Make sure you have a Composer installed on your system before you install Laravel. In this chapter, you will see the installation process of Laravel. You will have to follow the steps given below for installing Laravel onto your system − Step 1 − Visit the following URL and download composer to install it on your system. https://getcomposer.org/download/ Step 2 − After the Composer is installed, check the installation by typing the Composer command in the command prompt as shown in the following screenshot. Step 3 − Create a new directory anywhere in your system for your new Laravel project. After that, move to path where you have created the new directory and type the following command there to install Laravel. composer create-project laravel/laravel –-prefer-dist Now, we will focus on installation of version 5.7. In Laravel version 5.7, you can install the complete framework by typing the following command − composer create-project laravel/laravel test dev-develop The output of the command is as shown below − The Laravel framework can be directly installed with develop branch which includes the latest framework. Step 4 − The above command will install Laravel in the current directory. Start the Laravel service by executing the following command. php artisan serve Step 5 − After executing the above command, you will see a screen as shown below − Step 6 − Copy the URL underlined in gray in the above screenshot and open that URL in the browser. If you see the following screen, it implies Laravel has been installed successfully. Laravel – Application Structure The application structure in Laravel is basically the structure of folders, sub-folders and files included in a project. Once we create a project in Laravel, we get an overview of the application structure as shown in the image here. The snapshot shown here refers to the root folder of Laravel namely laravel-project. It includes various sub-folders and files. The analysis of folders and files, along with their functional aspects is given

Laravel – Discussion

Discuss Laravel ”; Previous Next Laravel is a powerful MVC PHP framework, designed for developers who need a simple and elegant toolkit to create full-featured web applications. Laravel was created by Taylor Otwell. This is a brief tutorial that explains the basics of Laravel framework. Print Page Previous Next Advertisements ”;

Laravel – Useful Resources

Laravel – Useful Resources ”; Previous Next The following resources contain additional information on Laravel. Please use them to get more in-depth knowledge on this topic. Useful Video Courses Laravel RESTful APIs – Admin App, Docker, Open API(Swagger) 36 Lectures 3.5 hours Antonio Papa More Detail Laravel 5 43 Lectures 1 hours Skillbakery More Detail Finest Laravel Course – Learn from 0 to ninja with ReactJS Most Popular 166 Lectures 13 hours Paul Carlo Tordecilla More Detail Master Laravel with Vue 117 Lectures 13 hours Hafizullah Masoudi More Detail PHP Development with the Laravel 4 Framework 16 Lectures 3 hours Stone River ELearning More Detail Vue 3 and Laravel: Breaking a Monolith to Microservices 156 Lectures 14 hours Packt Publishing More Detail Print Page Previous Next Advertisements ”;

Laravel – Forms

Laravel – Forms ”; Previous Next Laravel provides various in built tags to handle HTML forms easily and securely. All the major elements of HTML are generated using Laravel. To support this, we need to add HTML package to Laravel using composer. Example 1 Step 1 − Execute the following command to proceed with the same. composer require illuminate/html Step 2 − This will add HTML package to Laravel as shown in the following image. Step 3 − Now, we need to add the package shown above to Laravel configuration file which is stored at config/app.php. Open this file and you will see a list of Laravel service providers as shown in the following image. Add HTML service provider as indicated in the outlined box in the following image. Step 4 − Add aliases in the same file for HTML and Form. Notice the two lines indicated in the outlined box in the following image and add those two lines. Step 5 − Now everything is setup. Let’s see how we can use various HTML elements using Laravel tags. Opening a Form {{ Form::open(array(”url” => ”foo/bar”)) }} // {{ Form::close() }} Generating a Label Element echo Form::label(”email”, ”E-Mail Address”); Generating a Text Input echo Form::text(”username”); Specifying a Default Value echo Form::text(”email”, ”[email protected]”); Generating a Password Input echo Form::password(”password”); Generating a File Input echo Form::file(”image”); Generating a Checkbox Or Radio Input echo Form::checkbox(”name”, ”value”); echo Form::radio(”name”, ”value”); Generating a Checkbox Or Radio Input That Is Checked echo Form::checkbox(”name”, ”value”, true); echo Form::radio(”name”, ”value”, true); Generating a Drop-Down List echo Form::select(”size”, array(”L” => ”Large”, ”S” => ”Small”)); Generating A Submit Button echo Form::submit(”Click Me!”); Example 2 Step 1 − Copy the following code to create a view called resources/views/form.php. resources/views/form.php <html> <body> <?php echo Form::open(array(”url” => ”foo/bar”)); echo Form::text(”username”,”Username”); echo ”<br/>”; echo Form::text(”email”, ”[email protected]”); echo ”<br/>”; echo Form::password(”password”); echo ”<br/>”; echo Form::checkbox(”name”, ”value”); echo ”<br/>”; echo Form::radio(”name”, ”value”); echo ”<br/>”; echo Form::file(”image”); echo ”<br/>”; echo Form::select(”size”, array(”L” => ”Large”, ”S” => ”Small”)); echo ”<br/>”; echo Form::submit(”Click Me!”); echo Form::close(); ?> </body> </html> Step 2 − Add the following line in app/Http/routes.php to add a route for view form.php app/Http/routes.php Route::get(”/form”,function() { return view(”form”); }); Step 3 − Visit the following URL to see the form. http://localhost:8000/form Step 4 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;

Laravel – Validation

Laravel – Validation ”; Previous Next 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 Accepted Active URL After (Date) Alpha Alpha Dash Alpha Numeric Array Before (Date) Between Boolean Confirmed Date Date Format Different Digits Digits Between E-Mail Exists (Database) Image (File) In Integer IP Address JSON Max MIME Types(File) Min Not In Numeric Regular Expression Required Required If Required Unless Required With Required With All Required Without Required Without All Same Size String Timezone Unique (Database) URL The $errors variable will be an instance of IlluminateSupportMessageBag. Error message can be displayed in view file by adding the code as shown below. @if (count($errors) > 0) <div class = “alert alert-danger”> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </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 − Step 3 − Copy the following code in app/Http/Controllers/ValidationController.php file. app/Http/Controllers/ValidationController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class ValidationController extends Controller { public function showform() { return view(”login”); } public function validateform(Request $request) { print_r($request->all()); $this->validate($request,[ ”username”=>”required|max:8”, ”password”=>”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> <title>Login Form</title> </head> <body> @if (count($errors) > 0) <div class = “alert alert-danger”> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}</li> @endforeach </ul> </div> @endif <?php echo Form::open(array(”url”=>”/validation”)); ?> <table border = ”1”> <tr> <td align = ”center” colspan = ”2”>Login</td> </tr> <tr> <td>Username</td> <td><?php echo Form::text(”username”); ?></td> </tr> <tr> <td>Password</td> <td><?php echo Form::password(”password”); ?></td> </tr> <tr> <td align = ”center” colspan = ”2” ><?php echo Form::submit(”Login”); ? ></td> </tr> </table> <?php echo Form::close(); ?> </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. Print Page Previous Next Advertisements ”;

Laravel – Guest User Gates

Laravel – Guest User Gates ”; Previous Next The Guest User Gates feature is an add-on to the latest 5.7 version released in September 2018. This feature is used to initiate the authorization process for specific users. In Laravel 5.6, there was a procedure where it used to return false for unauthenticated users. In Laravel 5.7, we can allow guests to go authorization checks by using the specific nullable type hint within the specified controller as given below − <?php Gate::define(”view-post”, function (?User $user) { // Guests }); Explanation of the Code By using a nullable type hint the $user variable will be null when a guest user is passed to the gate. You can then make decisions about authorizing the action. If you allow nullable types and return true, then the guest will have authorization. If you don’t use a nullable type hint, guests will automatically get the 403 response for Laravel 5.7, which is displayed below − The difference between 403 and 404 error is that 404 is displayed when user tries to access the unknown resource or URL and 403 error as mentioned in the snapshot above is displayed if unauthorized user accesses the website. Print Page Previous Next Advertisements ”;

Laravel – Artisan Console

Laravel – Artisan Console ”; Previous Next Laravel framework provides three primary tools for interaction through command-line namely: Artisan, Ticker and REPL. This chapter explains about Artisan in detail. Introduction to Artisan Artisan is the command line interface frequently used in Laravel and it includes a set of helpful commands for developing a web application. Example Here is a list of few commands in Artisan along with their respective functionalities − To start Laravel project php artisan serve To enable caching mechanism php artisan route:cache To view the list of available commands supported by Artisan php artisan list To view help about any command and view the available options and arguments php artisan help serve The following screenshot shows the output of the commands given above − Writing Commands In addition to the commands listed in Artisan, a user can also create a custom command which can be used in the web application. Please note that commands are stored in app/console/commands directory. The default command for creating user defined command is shown below − php artisan make:console <name-of-command> Once you type the above given command, you can see the output as shown in the screenshot given below − The file created for DefaultCommand is named as DefaultCommand.php and is shown below − <?php namespace AppConsoleCommands; use IlluminateConsoleCommand; class DefaultCommand extends Command{ /** * The name and signature of the console command. * * @var string */ protected $signature = ”command:name”; /** * The console command description. * * @var string */ protected $description = ”Command description”; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // } } This file includes the signature and description for the command that user defined. The public function named handle executes the functionalities when the command is executed. These commands are registered in the file Kernel.php in the same directory. You can also create the schedule of tasks for the user defined command as shown in the following code − <?php namespace AppConsole; use IlluminateConsoleSchedulingSchedule; use IlluminateFoundationConsoleKernel as ConsoleKernel; class Kernel extends ConsoleKernel { /** * The Artisan commands provided by your application. * * @var array */ protected $commands = [ // CommandsInspire::class, CommandsDefaultCommand::class ]; /** * Define the application”s command schedule. * * @param IlluminateConsoleSchedulingSchedule $schedule * @return void */ protected function schedule(Schedule $schedule) { // $schedule->command(”inspire”) // ->hourly(); } } Note that the schedule of tasks for the given command is defined in the function named schedule, which includes a parameter for scheduling the tasks which takes hourly parameter. The commands are registered in the array of commands, which includes the path and name of the commands. Once the command is registered, it is listed in Artisan commands. The values included in the signature and description section will be displayed when you call for the help attribute of the specified command. Let us see how to view the attributes of our command DefaultCommand. You should use the command as shown below − php artisan help DefaultCommand Print Page Previous Next Advertisements ”;

Laravel – Encryption

Laravel – Encryption ”; Previous Next Encryption is a process of converting a plain text to a message using some algorithms such that any third user cannot read the information. This is helpful for transmitting sensitive information because there are fewer chances for an intruder to target the information transferred. Encryption is performed using a process called Cryptography. The text which is to be encrypted is termed as Plain Text and the text or the message obtained after the encryption is called Cipher Text. The process of converting cipher text to plain text is called Decryption. Laravel uses AES-256 and AES-128 encrypter, which uses Open SSL for encryption. All the values included in Laravel are signed using the protocol Message Authentication Code so that the underlying value cannot be tampered with once it is encrypted. Configuration The command used to generate the key in Laravel is shown below − php artisan key:generate Please note that this command uses the PHP secure random bytes’ generator and you can see the output as shown in the screenshot given below − The command given above helps in generating the key which can be used in web application. Observe the screenshot shown below − Note The values for encryption are properly aligned in the config/app.php file, which includes two parameters for encryption namely key and cipher. If the value using this key is not properly aligned, all the values encrypted in Laravel will be insecure. Encryption Process Encryption of a value can be done by using the encrypt helper in the controllers of Laravel class. These values are encrypted using OpenSSL and AES-256 cipher. All the encrypted values are signed with Message Authentication code (MAC) to check for any modifications of the encrypted string. The code shown below is mentioned in a controller and is used to store a secret or a sensitive message. <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpControllersController; class DemoController extends Controller{ ** * Store a secret message for the user. * * @param Request $request * @param int $id * @return Response */ public function storeSecret(Request $request, $id) { $user = User::findOrFail($id); $user->fill([ ”secret” => encrypt($request->secret) ])->save(); } } Decryption Process Decryption of the values is done with the decrypt helper. Observe the following lines of code − use IlluminateContractsEncryptionDecryptException; // Exception for decryption thrown in facade try { $decrypted = decrypt($encryptedValue); } catch (DecryptException $e) { // } Please note that if the process of decryption is not successful because of invalid MAC being used, then an appropriate exception is thrown. Print Page Previous Next Advertisements ”;

Laravel – Dump Server

Laravel – Dump Server ”; Previous Next Laravel dump server comes with the version of Laravel 5.7. The previous versions do not include any dump server. Dump server will be a development dependency in laravel/laravel composer file. With release of version 5.7, you’ll get this command which includes a concept out-of-thebox which allows user to dump data to the console or an HTML file instead of to the browser. The command execution is mentioned below − php artisan dump-server # Or send the output to an HTML file php artisan dump-server –format=html > dump.html Explanation The command runs a server in the background which helps in collection of data sent from the application, that sends the output through the console. When the command is not running in the foreground, the dump() function is expected to work by default. Print Page Previous Next Advertisements ”;

Laravel – Artisan Commands

Laravel – Artisan Commands ”; Previous Next Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below − class ArtisanCommandTest extends TestCase{ public function testBasicTest() { $this->artisan(”nova:create”, [ ”name” => ”My New Admin panel” ]) ->expectsQuestion(”Please enter your API key”, ”apiKeySecret”) ->expectsOutput(”Authenticating…”) ->expectsQuestion(”Please select a version”, ”v1.0”) ->expectsOutput(”Installing…”) ->expectsQuestion(”Do you want to compile the assets?”, ”yes”) ->expectsOutput(”Compiling assets…”) ->assertExitCode(0); } } Explanation of Code Here a new class named “ArtisanCommandTest” is created under test cases module. It includes a basic function testBasicTest which includes various functionalities of assertions. The artisan command expectsQuestion includes two attributes. One with question and other with an apiKeySecret. Here, the artisan validates the apiKeySecret and verifies the input sent by user. The same scenario applies for the question “Please select a version” where a user is expected to mention a specific version. Print Page Previous Next Advertisements ”;