Laravel – Application Structure ”; Previous Next 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 below − App It is the application folder and includes the entire source code of the project. It contains events, exceptions and middleware declaration. The app folder comprises various sub folders as explained below − Console Console includes the artisan commands necessary for Laravel. It includes a directory named Commands, where all the commands are declared with the appropriate signature. The file Kernal.php calls the commands declared in Inspire.php. If we need to call a specific command in Laravel, then we should make appropriate changes in this directory. Events This folder includes all the events for the project. Events are used to trigger activities, raise errors or necessary validations and provide greater flexibility. Laravel keeps all the events under one directory. The default file included is event.php where all the basic events are declared. Exceptions This folder contains all the methods needed to handle exceptions. It also contains the file handle.php that handles all the exceptions. Http The Http folder has sub-folders for controllers, middleware and application requests. As Laravel follows the MVC design pattern, this folder includes model, controllers and views defined for the specific directories. The Middleware sub-folder includes middleware mechanism, comprising the filter mechanism and communication between response and request. The Requests sub-folder includes all the requests of the application. Jobs The Jobs directory maintains the activities queued for Laravel application. The base class is shared among all the Jobs and provides a central location to place them under one roof. Listeners Listeners are event-dependent and they include methods which are used to handle events and exceptions. For example, the login event declared includes a LoginListener event. Policies Policies are the PHP classes which includes the authorization logic. Laravel includes a feature to create all authorization logic within policy classes inside this sub folder. Providers This folder includes all the service providers required to register events for core servers and to configure a Laravel application. Bootstrap This folder encloses all the application bootstrap scripts. It contains a sub-folder namely cache, which includes all the files associated for caching a web application. You can also find the file app.php, which initializes the scripts necessary for bootstrap. Config The config folder includes various configurations and associated parameters required for the smooth functioning of a Laravel application. Various files included within the config folder are as shown in the image here. The filenames work as per the functionality associated with them. Database As the name suggests, this directory includes various parameters for database functionalities. It includes three sub-directories as given below − Seeds − This contains the classes used for unit testing database. Migrations − This folder helps in queries for migrating the database used in the web application. Factories − This folder is used to generate large number of data records. Public It is the root folder which helps in initializing the Laravel application. It includes the following files and folders − .htaccess − This file gives the server configuration. javascript and css − These files are considered as assets. index.php − This file is required for the initialization of a web application. Resources Resources directory contains the files which enhances your web application. The sub-folders included in this directory and their purpose is explained below − assets − The assets folder include files such as LESS and SCSS, that are required for styling the web application. lang − This folder includes configuration for localization or internalization. views − Views are the HTML files or templates which interact with end users and play a primary role in MVC architecture. Observe that the resources directory will be flattened instead of having an assets folder. The pictorial representation of same is shown below − Storage This is the folder that stores all the logs and necessary files which are needed frequently when a Laravel project is running. The sub-folders included in this directory and their purpose is given below − app − This folder contains the files that are called in succession. framework − It contains sessions, cache and views which are called frequently. Logs − All exceptions and error logs are tracked in this sub folder. Tests All the unit test cases are included in this directory. The naming convention for naming test case classes is camel_case and follows the convention as per the functionality of the class. Vendor Laravel is completely based on Composer dependencies, for example to install Laravel setup or to include third party libraries, etc. The Vendor folder includes all the composer dependencies. In addition to the above mentioned files, Laravel also includes some other files which play a primary role in various functionalities such as GitHub configuration, packages and third party libraries. The files included in the application structure are shown below − Print Page Previous Next Advertisements ”;
Category: laravel
Laravel – Configuration
Laravel – Configuration ”; Previous Next In the previous chapter, we have seen that the basic configuration files of Laravel are included in the config directory. In this chapter, let us discuss the categories included in the configuration. Environment Configuration Environment variables are those which provide a list of web services to your web application. All the environment variables are declared in the .env file which includes the parameters required for initializing the configuration. By default, the .env file includes following parameters − APP_ENV = local APP_DEBUG = true APP_KEY = base64:ZPt2wmKE/X4eEhrzJU6XX4R93rCwYG8E2f8QUA7kGK8 = APP_URL = http://localhost DB_CONNECTION = mysql DB_HOST = 127.0.0.1 DB_PORT = 3306 DB_DATABASE = homestead DB_USERNAME = homestead DB_PASSWORD = secret CACHE_DRIVER = file SESSION_DRIVER = file QUEUE_DRIVER = sync REDIS_HOST = 127.0.0.1 REDIS_PASSWORD = null REDIS_PORT = 6379 MAIL_DRIVER = smtp MAIL_HOST = mailtrap.ioMAIL_PORT = 2525 MAIL_USERNAME = null MAIL_PASSWORD = null MAIL_ENCRYPTION = null Important Points While working with basic configuration files of Laravel, the following points are to be noted − The .env file should not be committed to the application source control, since each developer or user has some predefined environment configuration for the web application. For backup options, the development team should include the .env.example file, which should contain the default configuration. Retrieval of Environment Variables All the environment variables declared in the .env file can be accessed by env-helper functions which will call the respective parameter. These variables are also listed into $_ENV global variable whenever application receives a request from the user end. You can access the environment variable as shown below − ”env” => env(”APP_ENV”, ”production”), env-helper functions are called in the app.php file included in the config folder. The above given example is calling for the basic local parameter. Accessing Configuration Values You can easily access the configuration values anywhere in the application using the global config helper function. In case if the configuration values are not initialized, default values are returned. For example, to set the default time zone, the following code is used − config([”app.timezone” => ”Asia/Kolkata”]); Caching of Configuration To increase the performance and to boost the web application, it is important to cache all the configuration values. The command for caching the configuration values is − config:cache The following screenshot shows caching in a systematic approach − Maintenance Mode Sometimes you may need to update some configuration values or perform maintenance on your website. In such cases, keeping it in maintenance mode, makes it easier for you. Such web applications which are kept in maintenance mode, throw an exception namely MaintenanceModeException with a status code of 503. You can enable the maintenance mode on your Laravel web application using the following command − php artisan down The following screenshot shows how the web application looks when it is down − Once you finish working on updates and other maintenance, you can disable the maintenance mode on your web application using following command − php artisan up Now, you can find that the website shows the output with proper functioning and depicting that the maintenance mode is now removed as shown below − Print Page Previous Next Advertisements ”;
Laravel – Routing
Laravel – Routing ”; Previous Next In Laravel, all requests are mapped with the help of routes. Basic routing routes the request to the associated controllers. This chapter discusses routing in Laravel. Routing in Laravel includes the following categories − Basic Routing Route parameters Named Routes Basic Routing All the application routes are registered within the app/routes.php file. This file tells Laravel for the URIs it should respond to and the associated controller will give it a particular call. The sample route for the welcome page can be seen as shown in the screenshot given below − Route::get (”/”, function () { return view(”welcome”);}); Example Observe the following example to understand more about Routing − app/Http/routes.php <?php Route::get(”/”, function () { return view(”welcome”); }); resources/view/welcome.blade.php <!DOCTYPE html> <html> <head> <title>Laravel</title> <link href = “https://fonts.googleapis.com/css?family=Lato:100” rel = “stylesheet” type = “text/css”> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; display: table; font-weight: 100; font-family: ”Lato”; } .container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } </style> </head> <body> <div class = “container”> <div class = “content”> <div class = “title”>Laravel 5.1</div> </div> </div> </body> </html> The routing mechanism is shown in the image given below − Let us now understand the steps involved in routing mechanism in detail − Step 1 − Initially, we should execute the root URL of the application. Step 2 − Now, the executed URL should match with the appropriate method in the route.php file. In the present case, it should match the method and the root (‘/’) URL. This will execute the related function. Step 3 − The function calls the template file resources/views/welcome.blade.php. Next, the function calls the view() function with argument ‘welcome’ without using the blade.php. This will produce the HTML output as shown in the image below − Route Parameters Sometimes in the web application, you may need to capture the parameters passed with the URL. For this, you should modify the code in routes.php file. You can capture the parameters in routes.php file in two ways as discussed here − Required Parameters These parameters are those which should be mandatorily captured for routing the web application. For example, it is important to capture the user’s identification number from the URL. This can be possible by defining route parameters as shown below − Route::get(”ID/{id}”,function($id) { echo ”ID: ”.$id; }); Optional Parameters Sometimes developers can produce parameters as optional and it is possible with the inclusion of ? after the parameter name in URL. It is important to keep the default value mentioned as a parameter name. Look at the following example that shows how to define an optional parameter − Route::get(”user/{name?}”, function ($name = ”TutorialsPoint”) { return $name;}); The example above checks if the value matches to TutorialsPoint and accordingly routes to the defined URL. Named Routes Named routes allow a convenient way of creating routes. The chaining of routes can be specified using name method onto the route definition. The following code shows an example for creating named routes with controller − Route::get(”user/profile”, ”UserController@showProfile”)->name(”profile”); The user controller will call for the function showProfile with parameter as profile. The parameters use name method onto the route definition. Print Page Previous Next Advertisements ”;
Laravel – Overview
Laravel – Overview ”; Previous Next 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. Print Page Previous Next Advertisements ”;
Laravel – Pagination Customizations ”; Previous Next Laravel includes a feature of pagination which helps a user or a developer to include a pagination feature. Laravel paginator is integrated with the query builder and Eloquent ORM. The paginate method automatically takes care of setting the required limit and the defined offset. It accepts only one parameter to paginate i.e. the number of items to be displayed in one page. Laravel 5.7 includes a new pagination method to customize the number of pages on each side of the paginator. The new method no longer needs a custom pagination view. The custom pagination view code demonstration is mentioned below − <?php namespace AppHttpControllers; use IlluminateSupportFacadesDB; use AppHttpControllersController; class UserController extends Controller{ /** * Show all of the users for the application. * * @return Response */ public function index() { $users = DB::table(”users”)->paginate(15); return view(”user.index”, [”users” => $users]); } } The new pagination customization as per Laravel standards is mentioned below − <?php User::paginate(10)->onEachSide(5); Note that onEachSide refers to the subdivision of each pagination records with 10 and subdivision of 5. Print Page Previous Next Advertisements ”;
Laravel – Middleware
Laravel – Middleware ”; Previous Next Middleware acts as a bridge between a request and a response. It is a type of filtering mechanism. This chapter explains you the middleware mechanism in Laravel. Laravel includes a middleware that verifies whether the user of the application is authenticated or not. If the user is authenticated, it redirects to the home page otherwise, if not, it redirects to the login page. Middleware can be created by executing the following command − php artisan make:middleware <middleware-name> Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app/Http/Middleware directory. Example Observe the following example to understand the middleware mechanism − Step 1 − Let us now create AgeMiddleware. To create that, we need to execute the following command − php artisan make:middleware AgeMiddleware Step 2 − After successful execution of the command, you will receive the following output − Step 3 − AgeMiddleware will be created at app/Http/Middleware. The newly created file will have the following code already created for you. <?php namespace AppHttpMiddleware; use Closure; class AgeMiddleware { public function handle($request, Closure $next) { return $next($request); } } Registering Middleware We need to register each and every middleware before using it. There are two types of Middleware in Laravel. Global Middleware Route Middleware The Global Middleware will run on every HTTP request of the application, whereas the Route Middleware will be assigned to a specific route. The middleware can be registered at app/Http/Kernel.php. This file contains two properties $middleware and $routeMiddleware. $middleware property is used to register Global Middleware and $routeMiddleware property is used to register route specific middleware. To register the global middleware, list the class at the end of $middleware property. protected $middleware = [ IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class, AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, ]; To register the route specific middleware, add the key and value to $routeMiddleware property. protected $routeMiddleware = [ ”auth” => AppHttpMiddlewareAuthenticate::class, ”auth.basic” => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, ”guest” => AppHttpMiddlewareRedirectIfAuthenticated::class, ]; Example We have created AgeMiddleware in the previous example. We can now register it in route specific middleware property. The code for that registration is shown below. The following is the code for app/Http/Kernel.php − <?php namespace AppHttp; use IlluminateFoundationHttpKernel as HttpKernel; class Kernel extends HttpKernel { protected $middleware = [ IlluminateFoundationHttpMiddlewareCheckForMaintenanceMode::class, AppHttpMiddlewareEncryptCookies::class, IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class, IlluminateSessionMiddlewareStartSession::class, IlluminateViewMiddlewareShareErrorsFromSession::class, AppHttpMiddlewareVerifyCsrfToken::class, ]; protected $routeMiddleware = [ ”auth” => AppHttpMiddlewareAuthenticate::class, ”auth.basic” => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class, ”guest” => AppHttpMiddlewareRedirectIfAuthenticated::class, ”Age” => AppHttpMiddlewareAgeMiddleware::class, ]; } Middleware Parameters We can also pass parameters with the Middleware. For example, if your application has different roles like user, admin, super admin etc. and you want to authenticate the action based on role, this can be achieved by passing parameters with middleware. The middleware that we create contains the following function and we can pass our custom argument after the $next argument. public function handle($request, Closure $next) { return $next($request); } Example Step 1 − Create RoleMiddleware by executing the following command − php artisan make:middleware RoleMiddleware Step 2 − After successful execution, you will receive the following output − Step 3 − Add the following code in the handle method of the newly created RoleMiddlewareat app/Http/Middleware/RoleMiddleware.php. <?php namespace AppHttpMiddleware; use Closure; class RoleMiddleware { public function handle($request, Closure $next, $role) { echo “Role: “.$role; return $next($request); } } Step 4 − Register the RoleMiddleware in appHttpKernel.php file. Add the line highlighted in gray color in that file to register RoleMiddleware. Step 5 − Execute the following command to create TestController − php artisan make:controller TestController –plain Step 6 − After successful execution of the above step, you will receive the following output − Step 7 − Copy the following lines of code to app/Http/TestController.php file. app/Http/TestController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class TestController extends Controller { public function index() { echo “<br>Test Controller.”; } } Step 8 − Add the following line of code in app/Http/routes.php file. app/Http/routes.php Route::get(”role”,[ ”middleware” => ”Role:editor”, ”uses” => ”TestController@index”, ]); Step 9 − Visit the following URL to test the Middleware with parameters http://localhost:8000/role Step 10 − The output will appear as shown in the following image. Terminable Middleware Terminable middleware performs some task after the response has been sent to the browser. This can be accomplished by creating a middleware with terminate method in the middleware. Terminable middleware should be registered with global middleware. The terminate method will receive two arguments $request and $response. Terminate method can be created as shown in the following code. Example Step 1 − Create TerminateMiddleware by executing the below command. php artisan make:middleware TerminateMiddleware Step 2 − The above step will produce the following output − Step 3 − Copy the following code in the newly created TerminateMiddleware at app/Http/Middleware/TerminateMiddleware.php. <?php namespace AppHttpMiddleware; use Closure; class TerminateMiddleware { public function handle($request, Closure $next) { echo “Executing statements of handle method of TerminateMiddleware.”; return $next($request); } public function terminate($request, $response) { echo “<br>Executing statements of terminate method of TerminateMiddleware.”; } } Step 4 − Register the TerminateMiddleware in appHttpKernel.php file. Add the line highlighted in gray color in that file to register TerminateMiddleware. Step 5 − Execute the following command to create ABCController. php artisan make:controller ABCController –plain Step 6 − After the successful execution of the URL, you will receive the following output − Step 7 − Copy the following code to app/Http/ABCController.php file. app/Http/ABCController.php <?php namespace AppHttpControllers; use IlluminateHttpRequest; use AppHttpRequests; use AppHttpControllersController; class ABCController extends Controller { public function index() { echo “<br>ABC Controller.”; } } Step 8 − Add the following line of code in app/Http/routes.php file. app/Http/routes.php Route::get(”terminate”,[ ”middleware” => ”terminate”, ”uses” => ”ABCController@index”, ]); Step 9 − Visit the following URL to test the Terminable Middleware. http://localhost:8000/terminate Step 10 − The output will appear as shown in the following image. Print Page Previous Next Advertisements ”;
Laravel – Home
Laravel Tutorial PDF Version Quick Guide Resources Job Search Discussion 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. Audience This tutorial will guide the developers and students who want to learn how to develop a website using Laravel. This tutorial is particularly meant for all those developers who have no prior experience of using Laravel. Prerequisites Before you start proceeding with this tutorial, we assume that you are familiar with HTML, Core PHP, and Advance PHP. If you are new to any of these concepts, we suggest you to pick tutorials based on these concepts first, to gain a better understanding of Laravel. Please note that we have used Laravel version 5.7 in all the examples. Print Page Previous Next Advertisements ”;
Laravel – Event Handling
Laravel – Event Handling ”; Previous Next 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. 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 AppEvents; abstract class Event{ // } As mentioned above, event.php includes the basic definition of class Event and calls for namespace AppEvents. Please note that the user defined or custom events are created in this file. SomeEvent.php <?php namespace AppEvents; use AppEventsEvent; use IlluminateQueueSerializesModels; use IlluminateContractsBroadcastingShouldBroadcast; 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 []; } } 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 AppListeners; use AppEventsSomeEvent; use IlluminateQueueInteractsWithQueue; use IlluminateContractsQueueShouldQueue; 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. Print Page Previous Next Advertisements ”;