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
Category: laravel
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 – 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 ”;
Laravel – Cookie
Laravel – Cookie ”; Previous Next Cookies play an important role while dealing a user’s session on a web application. In this chapter, you will learn about working with cookies in Laravel based web applications. Creating a Cookie Cookie can be created by global cookie helper of Laravel. It is an instance of SymfonyComponentHttpFoundationCookie. The cookie can be attached to the response using the withCookie() method. Create a response instance of IlluminateHttpResponse class to call the withCookie() method. Cookie generated by the Laravel are encrypted and signed and it can’t be modified or read by the client. Here is a sample code with explanation. //Create a response instance $response = new IlluminateHttpResponse(”Hello World”); //Call the withCookie() method with the response method $response->withCookie(cookie(”name”, ”value”, $minutes)); //return the response return $response; Cookie() method will take 3 arguments. First argument is the name of the cookie, second argument is the value of the cookie and the third argument is the duration of the cookie after which the cookie will get deleted automatically. Cookie can be set forever by using the forever method as shown in the below code. $response->withCookie(cookie()->forever(”name”, ”value”)); Retrieving a Cookie Once we set the cookie, we can retrieve the cookie by cookie() method. This cookie() method will take only one argument which will be the name of the cookie. The cookie method can be called by using the instance of IlluminateHttpRequest. Here is a sample code. //’name’ is the name of the cookie to retrieve the value of $value = $request->cookie(”name”); Example Observe the following example to understand more about Cookies − Step 1 − Execute the below command to create a controller in which we will manipulate the cookie. php artisan make:controller CookieController –plain Step 2 − After successful execution, you will receive the following output − Step 3 − Copy the following code in app/Http/Controllers/CookieController.php file. app/Http/Controllers/CookieController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use IlluminateHttpResponse; use AppHttpRequests; use AppHttpControllersController; class CookieController extends Controller { public function setCookie(Request $request) { $minutes = 1; $response = new Response(”Hello World”); $response->withCookie(cookie(”name”, ”virat”, $minutes)); return $response; } public function getCookie(Request $request) { $value = $request->cookie(”name”); echo $value; } } Step 4 − Add the following line in app/Http/routes.php file. app/Http/routes.php Route::get(”/cookie/set”,”CookieController@setCookie”); Route::get(”/cookie/get”,”CookieController@getCookie”); Step 5 − Visit the following URL to set the cookie. http://localhost:8000/cookie/set Step 6 − The output will appear as shown below. The window appearing in the screenshot is taken from firefox but depending on your browser, cookie can also be checked from the cookie option. Step 7 − Visit the following URL to get the cookie from the above URL. http://localhost:8000/cookie/get Step 8 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;
Laravel – Hashing
Laravel – Hashing ”; Previous Next Hashing is the process of transforming a string of characters into a shorter fixed value or a key that represents the original string. Laravel uses the Hash facade which provides a secure way for storing passwords in a hashed manner. Basic Usage The following screenshot shows how to create a controller named passwordController which is used for storing and updating passwords − The following lines of code explain the functionality and usage of the passwordController − <?php namespace AppHttpControllers; use IlluminateHttpRequest; use IlluminateSupportFacadesHash; use AppHttpControllersController class passwordController extends Controller{ /** * Updating the password for the user. * * @param Request $request * @return Response */ public function update(Request $request) { // Validate the new password length… $request->user()->fill([ ”password” => Hash::make($request->newPassword) // Hashing passwords ])->save(); } } The hashed passwords are stored using make method. This method allows managing the work factor of the bcrypt hashing algorithm, which is popularly used in Laravel. Verification of Password against Hash You should verify the password against hash to check the string which was used for conversion. For this you can use the check method. This is shown in the code given below − if (Hash::check(”plain-text”, $hashedPassword)) { // The passwords match… } Note that the check method compares the plain-text with the hashedPassword variable and if the result is true, it returns a true value. Print Page Previous Next Advertisements ”;
Laravel – Understanding Release Process ”; Previous Next Every web application framework has its own version history and it is always being updated and maintained. Every latest version brings new functionality and functions which are either changed or deprecated, so it is important that you know which version will be suitable for your projects. When it comes to Laravel, there are two active versions as given below − Laravel 4- released in May 2013 Laravel 5.1- released in February 2015 Laravel 5.1 also includes various releases with the latest version of Laravel 5.1.5 which includes all the robust features for web development. The roadmap of Laravel or the version release is shown in the image below − The following points are worth notable in the context of understanding the release process of Laravel − The old directory of app/models is removed in Laravel 5.1. All the controllers, middleware and requests are grouped within a directory under the app/Http folder. A new folder namely Providers directory is replaced with the app/start files in the previous versions of Laravel 4.x. All the language files and views are moved to the resources directory. New artisan command route:cache is used for registration of new routes and is included with the release of Laravel 5.1 and further versions. Laravel supports HTTP middleware and also includes CSRF tokens and authentication model. All the authentication models are located under one directory namely resources/views/auth. It includes user registration, authentication and password controllers. Laravel Releases Version Release Bug Fixes Until Security Fixes Until V1 June 2011 – – V2 September 2011 – – v3 February 2012 – – v4 May 2013 – – 5.0 Feb 4th, 2015 Aug 4th, 2015 Feb 4th, 2016 5.1 (LTS) Jun 9th, 2015 Jun 9th, 2017 Jun 9th, 2018 5.2 Dec 21st, 2015 Jun 21st, 2016 Dec 21st, 2016 5.3 Aug 23rd, 2016 Feb 23rd, 2017 Aug 23rd, 2017 5.4 Jan 24th, 2017 Jul 24th, 2017 Jan 24th, 2018 5.5 (LTS) Aug 30th, 2017 Aug 30th, 2019 Aug 30th, 2020 5.6 Feb 7th, 2018 Aug 7th, 2018 Feb 7th, 2019 5.7 Sep 4, 2018 Feb 4th, 2019 Sep 4th, 2019 Note that the highlighted version marks the latest release. Print Page Previous Next Advertisements ”;