BACHELORS'S IN COMPUTER APPLICATION SEMESTER - VI ADVANCED WEB DEVELOPMENT USING PHP 1
First Published in 2022 All rights reserved. No Part of this book may be reproduced or transmitted, in any form or by any means, without permission in writing from Chandigarh University. Any person who does any unauthorized act in relation to this book may be liable to criminal prosecution and civil claims for damages. This book is meant for educational and learning purpose. The authors of the book has/have taken all reasonable care to ensure that the contents of the book do not violate any existing copyright or other intellectual property rights of any person in any manner whatsoever. In the event the Authors have/ have been unable to track any source and if any copyright has been inadvertently infringed, please notify the publisher in writing for corrective action. 2
UNIT - 1 MVC STRUCTURE 1.0 Learning Objectives 1.1 Introduction to MVC 1.2 uses of MVC framework 1.3 Advantages and dis-advantages of MVC 1.4 Summary 1.5 Keywords 1.6 Learning Activity 1.7 Unit End Questions 1.8 References LEARNING OBJECTIVES After studying this unit, you will be able to know: Introduction to MVC uses of MVC framework Advantages and dis-advantages of MVC 1.1. INTRODUCTIONTO MVC The Model-View-Controller (MVC) is an architecture that is used by different technologies. Here “M” “V” “C” stands for “MODEL”, “VIEW”, and “CONTROLLER\" respectively. The Model-View-Controller (MVC) is an architectural pattern that separates an application into three main logical components: the model, the view, and the controller. Each of these components are built to handle specific development aspects of an application. MVC is one of the most frequently used industry-standard web development framework to create scalable and extensible projects. Areas such as software development and modern web development processes use the MVC framework to manage the internal architecture. Many modern software 3
frameworks like Django use the MVC pattern, which helps developers build on top of it, efficiently using MVC in their web applications 1.2. USES OF MVC FRAMEWORK The MVC framework is a design pattern that divides an application into three interconnected components namely: model, view and controller. Component separation enables programmers to keep the codebase separate. Every MVC component deals with a particular aspect of an application. It separates the business logic from the end-user interface. Areas such as software development and modern web development processes use the MVC framework to manage the internal architecture. Many modern software frameworks like Django use the MVC pattern, which helps developers build on top of it, efficiently using MVC in their web applications. The primary reasons for using MVC is to avoid repetition and facilitate the development of a robust structure for web applications. 1.3. ADVANTAGES AND DIS-ADVANTAGES OF MVC Components of an MVC framework There are three primary components of an MVC framework: Model The model is the central component of the pattern. It has the responsibility to manage the application data. MVC associates the model with the database; the model reflects any change in the database. This is what you add or retrieve data from. It responds to controller queries because the controller never communicates with the database alone. The model communicates with the database and then provides the controller with the required information. View The view takes care of the data representation and generates the user interface. The view can highlight specific data or filter out the data provided by the model. It represents the input and output data using UI components like the graph, chart, button, table, text box and 4
dropdown. The model component generates the view using the collected data. As the controller obtains these data indirectly, so the view only communicates with the controller. Controller The controller is the component that allows the views and the model to communicate with one another. It acts as a mediator. The controller does not have to deal with data logic; it only instructs the model. After getting data from the model, the controller processes it before sending it to the display and explains how to convey it to the user. We note that views and models cannot communicate directly. MVC framework example in daily life Every day we see examples of MVC around us but may not notice. Let us look at an example: When you go to a restaurant, the waiter takes your order, goes to the kitchen and informs the chef. The chef gets the ingredients from the fridge to cook your food. Once the food is ready, the waiter goes to the kitchen and brings the food to you. In the above example, 'you' acts as the 'view', 'waiter' as the 'controller', 'chef' as the 'model' and 'fridge' as the data. 'You' is the view in the example and cannot directly communicate with the 'chef', which is the model in this case. 'Waiter', the controller does not have to know how to process your instruction; it just shared them with 'chef', the model. Only the model, which is the 'chef' can access the data 'fridge' in this case. Popular MVC web frameworks Since MVC is essentially a way to arrange and organise your code, which makes it very easy to maintain even an extensive database. Various web frameworks use MVC architecture. Here are some examples of such web framework: Django Laravel CakePHP CodeIgniter Catalyst Ruby on Rails 5
1.4. SUMMARY The MVC architecture pattern turns complex application development into a much more manageable process. It allows several developers to simultaneously work on the application. When I first learned about MVC patterns, I was intimidated by all the jargon. And even more so when I started applying these concepts to an actual application. By taking a step back to focus on what MVC is and what it can accomplish, it's much easier to understand and apply the pattern to any web application. Since MVC is essentially a way to arrange and organise your code, which makes it very easy to maintain even an extensive database. Various web frameworks use MVC architecture. Here are some examples of such web framework: Django Laravel CakePHP CodeIgniter Catalyst Ruby on Rails 1.5. KEYWORDS Accessor A method defined on an Eloquent model that customizes how a given property will be returned. Accessors make it possible to define that getting a given property from a model will return a different (or, more likely, differently formatted) value than what is stored in the database for that property. ActiveRecord A common database ORM pattern, and also the pattern that Laravel’s Eloquent uses. In ActiveRecord the same model class defines both how to retrieve and persist database records and how to represent them. Additionally, each database record is represented by a single entity in the application, and each entity in the application is mapped to a single database record. Application test Often called acceptance or functional tests, application tests test the entire behavior of the application, usually at an outer boundary, by employing something like a DOM crawler—which is exactly what Laravel’s application test suite offers. Argument (Artisan) 6
Arguments are parameters that can be passed to Artisan console commands. Arguments aren’t prefaced with -- or followed by =, but instead just accept a single value. Artisan The tool that makes it possible to interact with Laravel applications from the command line. Assertion In testing, an assertion is the core of the test: you are asserting that something should be equal to (or less than or greater than) something else, or that it should have a given count, or whatever else you like. Assertions are the things ... 1.6. LEARNING ACTIVITY How will you define the 3 logical layers of MVC? How to execute any MVC project? Explain its steps. 1.7. UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain Model, View and Controller in Brief. 2. What are the different return types used by the controller action method in MVC? 3. Name the assembly in which the MVC framework is typically defined. 4. Explain the MVC Application life cycle. 5. What are the various steps to create the request object? 6. Explain some benefits of using MVC? Long Questions 1. Explain in brief the role of different MVC components? 2. How will you maintain the sessions in MVC? 3. What do you mean by partial view of MVC? 4. Explain in brief the difference between adding routes in a webform application & an MVC application? 5. What is the use of ActionFilters in MVC? 6. What is the concept of routing in MVC? 7. What are the 3 important segments for routing? B. Multiple Choice Questions 1. MVC is composed of three components: A) Member Vertical Controller B) Model View Control C) Model View Controller 7
D) Model Variable Centered 2. In MVC, the model is responsible for managing the data of the application. A) True B) False 3. The view is made with . . . . . . . A) HTML B) JavaScript C) CSS D) All of above 4. The MVC architecture creates the benefits of . . . . . . . of the system. A) request/response B) modularity C) flexibility D) visualisation E) reusability 5. Controller directly refers the view or manipulates it. A) True B) False 6. MVC framework is defined in . . . . . Assembly. A) System.CSS.Mvc B) System.Net.Mvc C) System.View.Mvc D) System.Web.Mvc Answers 1) c, 2) a, 3) d, 4) b,c,e, 5) b, 6) d 8
1.8. REFERENCES Reference Books: - 1. Professional WordPress: Design and Development by Brad Williams Step-By-Step WordPress for Beginners: How to Build a Beautiful Website on Your Own Domain from Scratch by Mike Taylor 9
UNIT - 2LARAVEL STRUCTURE 2.0.Learning Objectives 2.1.Introduction to Laravel 2.2.how laravel better than other frameworks 2.3.steps to install and configure laravel Project 2.4.Laravel directory structure 2.5.Summary 2.6.Keywords 2.7.Learning Activity 2.8.Unit End Questions 2.9.References 2.0 LEARNING OBJECTIVES After studying this unit, you will be able to know: how laravel better than other frameworks steps to install and configure laravel Project Laravel directory structure 2.1INTRODUCTIONTO LARAVEL Created by Taylor Otwell as a free open-source PHP web framework, Laravel is meant to ease and accelerate the development process of web applications with a great taste for simplicity. It follows the model–view–controller (MVC) architectural pattern as well as the PSR-2 coding standard, and the PSR-4 autoloading standard. Running a Test Driven Development (TDD) in Laravel is fun and easy to implement. Hosted on GitHub and available at https://github.com/laravel/laravel, Laravel boasts of a microservices architecture, making it tremendously extendable and this, with ease, with the use of custom-made and or existing third-party packages. 10
2.2HOW LARAVEL BETTER THAN OTHER FRAMEWORKS Since Laravel having following features comparing to other frameworks MVC Laravel uses the MVC model, therefore there are three core-parts of the framework which work together: models, views and controllers. Controllers are the main part where most of the work is done. They connect to models to get, create or update data and display the results on views, which contain the actual HTML structure of the application. Blade Templating Engine Laravel is shipped with a templating engine known as Blade. Blade is quite easy to use, yet, powerful. One feature the Blade templating engine does not share with other popular ones is her permissiveness; allowing the use of plain PHP code in Blade templating engine files. It is important to note that Blade templating engine files have .blade appended to file names right before the usual .php which is nothing other than the actual file extension. As such, .blade.php is the resulting file extension for Blade template files. Blade template engine files are stored in the resources/views directory. Routing & Middleware You can define the URLs of your application with the help of routes. These routes can contain variable data, connect to controllers or can be wrapped into middlewares. Middelware is a mechanism for filtering HTTP requests. They can be used to interact with requests before they reach the controllers and can thus modify or reject requests. Artisan Artisan is the command line tool you can use to control parts of Laravel. There are a lot of commands available to create models, controllers and other resources needed for development. You can also write your own commands to extend the Artisan command line tool. Eloquent ORM 11
To connect your models to various types of databases, Laravel offers its own ORM with a large set of functions to work with. The framework also provides migration and seeding and also features rollbacks. Event Handling The framework is capable of handling events across the application. You can create event listeners and event handlers that are similar to the ones from NodeJs. Version Version Release Date 1.0 2011-06-09 2.0 2011-11-24 3.0 2012-02-22 3.1 2012-03-27 3.2 2012-05-22 4.0 2013-05-28 4.1 2013-12-12 4.2 2014-06-01 5.0 2015-02-04 5.1 (LTS) 2015-06-09 5.2 2015-12-21 5.3 2016-08-24 5.4 2017-01-24 12
2.3STEPS TO INSTALL AND CONFIGURE LARAVEL PROJECT Installation from here 1. Get composer from https://getcomposer.organd install it 2. Get Wamp from https://www.wampserver.com/en/ install it and set environment variable of PHP composercreate-project--prefer-distlaravel/laravelprojectname 3. Get path to www and type command: composercreate-project--prefer-distlaravel/laravel=DESIRED_VERSIONprojectname To install a specific Laravel version, get path to www and type command: Or Via Laravel Installer First, download the Laravel installer using Composer: composerglobalrequire\"laravel/installer\" Make sure to place the $HOME/.composer/vendor/bin directory (or the equivalent directory for your OS) in your $PATH so the laravel executable can be located by your system. laravelnewblog Once installed, the laravel new command will create a fresh Laravel installation in the directory you specify. For instance, laravel new blog will create a directory named blog containing a fresh Laravel installation with all of Laravel's dependencies already installed: 2.4LARAVEL DIRECTORY STRUCTURE The Root Directory 13
The app Directory The bootstrap Directory The config Directory The database Directory The lang Directory The public Directory The resources Directory The routes Directory The storage Directory The tests Directory The vendor Directory The App Directory The Broadcasting Directory The Console Directory The Events Directory The Exceptions Directory The Http Directory The Jobs Directory The Listeners Directory The Mail Directory The Models Directory The Notifications Directory The Policies Directory The Providers Directory The Rules Directory Introduction 14
The default Laravel application structure is intended to provide a great starting point for both large and small applications. But you are free to organize your application however you like. Laravel imposes almost no restrictions on where any given class is located - as long as Composer can autoload the class. The Root Directory The App Directory The app directory contains the core code of your application. We'll explore thi s directory in more detail soon; however, almost all of the classes in your application will be in this directory. The Bootstrap Directory The bootstrap directory contains the app.php file which bootstraps the framework. This directory also houses a cache directory which contains framework generated files for performance optimization such as the route and services cache files. You should not typically need to modify any files within this directory. The Config Directory The config directory, as the name implies, contains all of your application's configuration files. It's a great idea to read through all of these files and familiarize yourself with all of the options available to you. The Database Directory The database directory contains your database migrations, model factories, and seeds. If you wish, you may also use this directory to hold an SQLite database. The Lang Directory The lang directory houses all of your application's language files. The Public Directory The public directory contains the index.php file, which is the entry point for all requests entering your application and configures autoloading. This directory also houses your assets such as images, JavaScript, and CSS. The Resources Directory 15
The resources directory contains your views as well as your raw, un-compiled assets such as CSS or JavaScript. The Routes Directory The routes directory contains all of the route definitions for your application. By default, several route files are included with Laravel: web.php, api.php, console.php, and channels.php. The web.php file contains routes that the RouteServiceProvider places in the web middleware group, which provides session state, CSRF protection, and cookie encryption. If your application does not offer a stateless, RESTful API then all your routes will most likely be defined in the web.php file. The api.php file contains routes that the RouteServiceProvider places in the api middleware group. These routes are intended to be stateless, so requests entering the application through these routes are intended to be authenticated via tokens and will not have access to session state. The console.php file is where you may define all of your closure based console commands. Each closure is bound to a command instance allowing a simple approach to interacting with each command's IO methods. Even though this file does not define HTTP routes, it defines console based entry points (routes) into your application. The channels.php file is where you may register all of the event broadcasting channels that your application supports. The Storage Directory The storage directory contains your logs, compiled Blade templates, file based sessions, file caches, and other files generated by the framework. This directory is segregated into app, framework, and logs directories. The app directory may be used to store any files generated by your application. The framework directory is used to store framework generated files and caches. Finally, the logs directory contains your application's log files. The storage/app/public directory may be used to store user-generated files, such as profile avatars, that should be publicly accessible. You should create a symbolic link at public/storage which points to this directory. You may create the link using the php artisan storage:link Artisan command. 16
The Tests Directory The tests directory contains your automated tests. Example PHPUnit unit tests and feature tests are provided out of the box. Each test class should be suffixed with the word Test. You may run your tests using the phpunit or php vendor/bin/phpunit commands. Or, if you would like a more detailed and beautiful representation of your test results, you may run your tests using the php artisan test Artisan command. The Vendor Directory The vendor directory contains your Composer dependencies. The App Directory The majority of your application is housed in the app directory. By default, this directory is namespaced under App and is autoloaded by Composer using the PSR-4 autoloading standard. The app directory contains a variety of additional directories such as Console, Http, and Providers. Think of the Console and Http directories as providing an API into the core of your application. The HTTP protocol and CLI are both mechanisms to interact with your application, but do not actually contain application logic. In other words, they are two ways of issuing commands to your application. The Console directory contains all of your Artisan commands, while the Http directory contains your controllers, middleware, and requests. A variety of other directories will be generated inside the app directory as you use the make Artisan commands to generate classes. So, for example, the app/Jobs directory will not exist until you execute the make:job Artisan command to generate a job class. Many of the classes in the app directory can be generated by Artisan via commands. To review the available commands, run the php artisan list make command in your terminal. The Broadcasting Directory The Broadcasting directory contains all of the broadcast channel classes for your application. These classes are generated using the make:channel command. This directory does not exist by default, but will be created for you when you create your first channel. To learn more about channels, check out the documentation on event broadcasting. 17
The Console Directory The Console directory contains all of the custom Artisan commands for your application. These commands may be generated using the make:command command. This directory also houses your console kernel, which is where your custom Artisan commands are registered and your scheduled tasks are defined. The Events Directory This directory does not exist by default, but will be created for you by the event:generate and make:event Artisan commands. The Events directory houses event classes. Events may be used to alert other parts of your application that a given action has occurred, providing a great deal of flexibility and decoupling. The Exceptions Directory The Exceptions directory contains your application's exception handler and is also a good place to place any exceptions thrown by your application. If you would like to customize how your exceptions are logged or rendered, you should modify the Handler class in this directory. The Http Directory The Http directory contains your controllers, middleware, and form requests. Almost all of the logic to handle requests entering your application will be placed in this directory. The Jobs Directory This directory does not exist by default, but will be created for you if you execute the make:job Artisan command. The Jobs directory houses the queueable jobs for your application. Jobs may be queued by your application or run synchronously within the current request lifecycle. Jobs that run synchronously during the current request are sometimes referred to as \"commands\" since they are an implementation of the command pattern. The Listeners Directory This directory does not exist by default, but will be created for you if you execute the event:generate or make:listener Artisan commands. The Listeners directory contains the classes that handle your events. Event listeners receive an event instance and 18
perform logic in response to the event being fired. For example, a UserRegistered event might be handled by a SendWelcomeEmail listener. The Mail Directory This directory does not exist by default, but will be created for you if you execute the make:mail Artisan command. The Mail directory contains all of your classes that represent emails sent by your application. Mail objects allow you to encapsulate all of the logic of building an email in a single, simple class that may be sent using the Mail::send method. The Models Directory The Models directory contains all of your Eloquent model classes. The Eloquent ORM included with Laravel provides a beautiful, simple ActiveRecord implementation for working with your database. Each database table has a corresponding \"Model\" which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table. The Notifications Directory This directory does not exist by default, but will be created for you if you execute the make:notification Artisan command. The Notifications directory contains all of the \"transactional\" notifications that are sent by your application, such as simple notifications about events that happen within your application. Laravel's notification feature abstracts sending notifications over a variety of drivers such as email, Slack, SMS, or stored in a database. The Policies Directory This directory does not exist by default, but will be created for you if you execute the make:policy Artisan command. The Policies directory contains the authorization policy classes for your application. Policies are used to determine if a user can perform a given action against a resource. The Providers Directory The Providers directory contains all of the service providers for your application. Service providers bootstrap your application by binding services in the service container, registering events, or performing any other tasks to prepare your application for incoming requests. 19
In a fresh Laravel application, this directory will already contain several providers. You are free to add your own providers to this directory as needed. The Rules Directory This directory does not exist by default, but will be created for you if you execute the make:rule Artisan command. The Rules directory contains the custom validation rule objects for your application. Rules are used to encapsulate complicated validation logic in a simple object. For more information, check out the validation documentation. 2.5SUMMARY Laravel and its other first-party packages follow Semantic Versioning. Major framework releases are released every year (~February), while minor and patch releases may be released as often as every week. Minor and patch releases should never contain breaking changes. When referencing the Laravel framework or its components from your application or package, you should always use a version constraint such as ^9.0, since major releases of Laravel do include breaking changes. However, we strive to always ensure you may update to a new major release in one day or less. Directory Structure The Root Directory The app Directory The bootstrap Directory The config Directory The database Directory The lang Directory The public Directory The resources Directory The routes Directory The storage Directory 20
The tests Directory The vendor Directory The App Directory The Broadcasting Directory The Console Directory The Events Directory The Exceptions Directory The Http Directory The Jobs Directory The Listeners Directory The Mail Directory The Models Directory The Notifications Directory The Policies Directory The Providers Directory The Rules Directory 2.6KEYWORDS concrete model A non-abstract (abstract=False) model. field An attribute on a model; a given field usually maps directly to a single database column. G eneric view 21
A higher-order view function that provides an abstract/generic implementation of a common idiom or pattern found in view development. model Models store your application’s data. MTV“Model-template-view”; a software pattern, similar in style to MVC, but a better description of the way Django does things. MVC Model-view-controller; a software pattern. Django follows MVC to some extent. 2.7LEARNING ACTIVITY Explain structure of Laravel Write steps to install Laravel 2.8UNIT END QUESTIONS A. Descriptive Questions Short Questions 1.What is Laravel? 2.What is the latest version of Laravel? 3.What is the minimum compatible version of PHP for Laravel 7 and 8? 4.What are the popular features of Laravel? 5.What are the new features of Laravel 8? 6.Does Laravel support Bootstrap? Long Questions 1.What are the advantages of using the Laravel framework to build complex web applications? 2.Name a few competitors of Laravel? 3.What are the differences between Laravel and CodeIgniter frameworks? 4.What is MVC architecture? 22
5.What is the command you can use to check whether you have installed the composer on your computer? 6.What are the server requirements for Installing Laravel version 8? B. Multiple Choice Questions 1.Bootstrap directory in Laravel is used to__________ 1. Initialize a Laraval application 2. Call laravel library functions 3. Load laravel classes and models 4. Load the configuration files Answer: Initialize a Laraval application 2. How to create a controller in laravel by cmd? 1. php artisan make:controller generate 2. php artisan make: generate controller contoller_name 3. php artisan make:controller –plain 4. php artisan make:requestcontroller_name create Answer: php artisan make:controller –plain 3. Interpolation of variable in laravel done using 1. {{}} 2. compact 3. helpers 4. None Answer: {{}} 4. Which command is used to start laravel server? 1. php artisan project_name 2. artisan start-server 3. php artisan serve 4. php artisan start php 23
Answer: php artisan serve 5. Which one Laravel command line interface? 1. Composer 2. Php artisan 3. Git 4. CLI Answer: Php artisan 6. Why does Laravel use the Blade Template Engine? 1. As a template 2. To simplify programming 3. For the view in MVC 4. For fun Answer: For the view in MVC 2.9REFERENCES Reference Books: - 1. Professional WordPress: Design and Development by Brad Williams Step-By-Step WordPress for Beginners: How to Build a Beautiful Website on Your Own Domain from Scratch by Mike Taylor 24
UNIT - 3ROUTING STRUCTURE 3.0.Learning Objectives 3.1.Introduction 3.2.Creating route file 3.3.route file functions 3.4.uses of route functions 3.5.Summary 3.6.Keywords 3.7.Learning Activity 3.8.Unit End Questions 3.9.References 3 LEARNING OBJECTIVES After studying this unit, you will be able to know: How to Create route file route file functions uses of route functions 3.1INTRODUCTION Routing is a process that is performed by layer 3 (or network layer) devices in order to deliver the packet by choosing an optimal path from one network to another. There are 3 types of routing: 25
1. Static routing – Static routing is a process in which we have to manually add routes to the routing table. Advantages – No routing overhead for router CPU which means a cheaper router can be used to do routing. It adds security because an only administrator can allow routing to particular networks only. No bandwidth usage between routers. Disadvantage – For a large network, it is a hectic task for administrators to manually add each route for the network in the routing table on each router. The administrator should have good knowledge of the topology. If a new administrator comes, then he has to manually add each route so he should have very good knowledge of the routes of the topology. 3.2CREATING ROUTE FILE 1) User Routes : Here you have to define routes in web.php in routes folder. in that file you have declare routes for user login. 2) Manager Routes : Here you have to create new file manager.php in routes folder. in that file you have declare routes for manager user. 3) Admin Routes : Here you have to create new file admin.php in routes folder. in that file you have declare routes for admin user. 26
3.3ROUTE FILE FUNCTIONS Route file functions routes/web.php <?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the \"web\" middleware group. Now create something great! | */ Route::get('/', function () { dd('Welcome to simple user route file.'); }); routes/manager.php <?php /* |-------------------------------------------------------------------------- | User Routes |-------------------------------------------------------------------------- | | Here is where you can register user routes for your application. These | routes are loaded by the RouteServiceProvider within a group which 27
| contains the \"user\" middleware group. Now create something great! | */ Route::get('/', function () { dd('Welcome to manager user routes.'); }); routes/admin.php <?php /* |-------------------------------------------------------------------------- | Admin Routes |-------------------------------------------------------------------------- | | Here is where you can register admin routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the \"admin\" middleware group. Now create something great! | */ Route::get('/', function () { dd('Welcome to admin user routes.'); }); Add Files to ServiceProvider In this step, we require to register our new two user file in RouteServiceProvider, that way we can create new file for each user wise like we create two user \"admin\" and \"manager\" then we create new file admin.php and manager.php in routes directory for define routing. So, let's open RouteServiceProvider.php and put bellow code: app/Providers/RouteServiceProvider.php 28
<?php namespace App\\Providers; use Illuminate\\Support\\Facades\\Route; use Illuminate\\Foundation\\Support\\Providers\\RouteServiceProviderasServiceProvider; classRouteServiceProviderextendsServiceProvider { /** * This namespace is applied to your controller routes. * * In addition, it is set as the URL generator's root namespace. * * @var string */ protected $namespace = 'App\\Http\\Controllers'; /** * Define your route model bindings, pattern filters, etc. * * @return void */ publicfunction boot() { parent::boot(); } /** * Define the routes for the application. 29
* * @return void */ publicfunction map() { $this->mapApiRoutes(); $this->mapWebRoutes(); $this->mapAdminRoutes(); $this->mapManagerRoutes(); } /** * Define the \"web\" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protectedfunctionmapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the \"api\" routes for the application. * 30
* These routes are typically stateless. * * @return void */ protectedfunctionmapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } /** * Define the \"admin\" routes for the application. * * These routes are typically stateless. * * @return void */ protectedfunctionmapAdminRoutes() { Route::prefix('admin') ->namespace($this->namespace) ->group(base_path('routes/admin.php')); } /** * Define the \"user\" routes for the application. 31
* * These routes are typically stateless. * * @return void */ protectedfunctionmapManagerRoutes() { Route::prefix('manager') ->namespace($this->namespace) ->group(base_path('routes/user.php')); } 3.4 USES OF ROUTE FUNCTIONS Route is a way of creating a request URL of your application. These URLs do not have to map to specific files on a website. The best thing about these URLs is that they are both human readable and SEO friendly. In Laravel, routes are created inside the routes folder. Routes for the website are created in web.php file, Similarly, the routes for the API are created inside api.php. The default installation of Laravel comes with two routes, one for the web and the other for API. Here is how the route for web in web.php looks like: Route::get('/', function () { return view('welcome'); }); Stop Wasting Time on Servers Cloudways handle server management for you so you can focus on creating great apps and keeping your clients happy. 32
In the above code, a route is defined for the homepage. Every time this route receives a get request for /, It will return the view welcome. Views are the frontend of the application and I will discuss the topic in an upcoming installment of this series. All Laravel routes are defined in your route files, which are found within the routes directory. These records are consequently stacked by your application’s AppProvidersRouteServiceProvider. The routes/web.php record defines routes that are for your web interface. The structure of the route is very simple. Open the appropriate file (either `web.php` or `api.php`) and start the code with `Route::` This is followed by the request you want to assign to that specific route and then comes the function that will be executed as a result of the request. Laravel offers the following route methods: get post put delete patch options Routes are defined in Laravel within the Route class with an HTTP verb, the route to reply to, and closure, or a controller strategy. 3.5SUMMARY 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 33
In this installment of the series, I discussed routing in Laravel 5.5. I described various related concepts regarding routes such as regular expressions and names for the routes. 3.6KEYWORDS property Also known as “managed attributes”, and a feature of Python since version 2.2. This is a neat way to implement attributes whose usage resembles attribute access, but whose implementation uses method calls. queryset An object representing some set of rows to be fetched from the database. slug A short label for something, containing only letters, numbers, underscores or hyphens. They’re generally used in URLs. For example, in a typical blog entry URL: https://www.djangoproject.com/weblog/2008/apr/12/spring/ the last bit (spring) is the slug. template A chunk of text that acts as formatting for representing data. A template helps to abstract the presentation of data from the data itself. view A function responsible for rendering a page. 3.7LEARNING ACTIVITY Write the steps of creatin route file Make table containing route file functions 3.8UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is REST api routes? 2. How to define route in laravel? 3. How to define a route without controller? 4. How to define routes with parameters? Long Questions 1. How to validate route parameters? 34
2. Define routes with namespaces 3. How to add prefix in front of each url? 4. How to get current route name or action or route? 5. How to define 404 route? A. Multiple Choice Questions 1. Where do we need to set database connection in Laravel? 1. Config.php 2. Setting.php 3. In seed files 4. .ENV file Answer: .ENV file 2. Where is the routing file located in Laravel ? 1. urls/ 2. routes/ 3. vendors/ 4. app/Http/ Answer: routes/ 3. How to set a session data in Laravel? 1. $request->session()->put(‘key’, ‘value’); 2. $request->db->session(‘key’, ‘value’); 3. $request->session()->set(‘key’, ‘value’); 4. none Answer: $request->session()->put(‘key’, ‘value’); 4. How to check current laravel version install your system? 1. php artisan check –version 2. php artisan make –version 3. php artisan –version 4. none of the above Answer: php artisan –version 5. For what do the .env is used? 35
1. For running cron jobs 2. For setting environment variables 3. For tracking vendors 4. None of These Answer: For setting environment variables 6. How to get current action name in Laravel? 1. request()->DB->getActionMethod() 2. request()->route()->getActionMethod() 3. request()->getActionMethod() 4. none of the above Answer: request()->route()->getActionMethod() 3.9REFERENCES Reference Books: - 1. Professional WordPress: Design and Development by Brad Williams Step-By-Step WordPress for Beginners: How to Build a Beautiful Website on Your Own Domain from Scratch by Mike Taylor 36
UNIT - 4CONTROLLER STRUCTURE 4.0.Learning Objectives 4.1.Introduction 4.2.Creating Controller in Laravel 4.3.creating functions in controller 4.4.get requested data in controller 4.5.accessing form data in controller 4.6.Connecting controller with route file. 4.7.Summary 4.8.Keywords 4.9.Learning Activity 4.10. Unit End Questions 4.10.References 4.0 LEARNING OBJECTIVES After studying this unit, you will be able to know: Creating Controller in Laravel creating functions in controller get requested data in controller accessing form data in controller Connecting controller with route file. 4.1INTRODUCTION A controller, in a computing context, is a hardware device or a software program that manages or directs the flow of data between two entities. In computing, controllers may be cards, microchips or separate hardware devices for the control of a peripheral device. In a general sense, a controller can be thought of as something or someone that interfaces between two systems and manages communications between them. 37
Here are a few examples of controllers: A graphics card is an integrated circuit card in a computer or, in some cases, a monitor that provides digital-to-analog conversion, video RAM, and a video controller so that data can be sent to a computer's display. A game controller is an input device for playing games. A network interface card (NIC) is a computer circuit board or card that is installed in a computer so that it can be connected to a network. A WAN interface card (WIC) is a specialized network interface card that allows devices to connect to a wide area network. A flash controller is the part of flash memory that communicates with the host device and manages the flash file directory. An application delivery controller is a data center network device that helps manage client connections to complex Web and enterprise applications. A baseboard management controller (BMC) is a specialized service processor that monitors the physical state of a computer, network server or other hardware device using sensors and communicating with the system administrator through an independent connection. A session border controller (SBC) is a device or application that governs the manner in which calls, also called sessions, are initiated, conducted and terminated in a VoIP (Voice over Internet Protocol) network. 4.2CREATING CONTROLLER IN LARAVEL 1 – Create model command You can use the php artisan make model for creating a model using the command line (CLI) php artisan make:model Product This command is to create the Product model, which is a placed on the app/models directory. 2 – Create Controller command 38
You can use the php artisan make:controller command for creating a controller using this command line: php artisan make:controllerProductController This command will create controller named ProductController, Which is placed on app/http/controllers directory. 3 – Create a Resource Controller Command To create the resource controller in laravel 8, so, you can execute the following command on command prompt: php artisan make:controllerProductController --resource PHP artisan make controller resource command creates a resource controller. It has already created some methods like index, update, edit, destroy, etc. 4 – Laravel make:model with migration and controller If you want to create controller and model, so you can execute php artisan make:model -mc for creating a controller and model in command prompt: php artisan make:model Product -mcr This single command has been created as a Product controller and model. 5 – Create Model and Migration Execute the following command on command prompt to create model and migration file: php artisan make:model Product -m This single command has been created as a product controller and model. 6 – Create API Controller using Artisan Use the following command to create api controller in laravel 8, so open command prompt and execute the following command: php artisan make:controller API\\ProductController This command will create api product controller, which is placed on app/http/controllers/API directory. 7 – Laravel create model and controller in one command execute the following command on command prompt to create model and migration file: 39
php artisan make:model Product -c This single command has been created as a product controller and model. 4.3CREATING FUNCTIONS IN CONTROLLER It is better to create custom classes in a separate directory. Create a directory inside the app directory. For the illustration, I am going to create a Classes directory in the app. +– app | +– Classes To create a class that generates users’ notifications, let’s create Notification.php class inside the Classes directory. +– +– app | Classes | +– Notification.php <?php class Notifications { public function __construct() { return \"construct function was initialized.\"; } public function create() { // create notification // send email // return output } } Using Custom Classes in application Namespace was introduced in PHP 5.3 and allowed to partition code into logical groups. Using namespace, we can use classes anywhere in our application. 40
To create a namespace, use the keyword ‘namespace’, and all code below this namespace is available under this namespace. So the ‘Notification.php’ class I created above, we can use namespacing to make it usable in the controllers or anywhere else in the application. <?php namespace App\\Classes; class Notifications { public function __construct() { return \"construct function was initialized.\"; } public function create() { // create notification // send email // return output } } As you can notice, the namespace is in the third line. The namespace is App\\Classes so any class in the Classes directory is available under App\\Classes namespace. To use this class in the controller, import the class by calling it by its namespace. <?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; use App\\Classes\\Notification; class UsersController extends Controller { // activate user subscription public function subscribe(Request $request) { // activate user subscription 41
all subscription code goes here... // send notifications $notification = new Notification; $notification->create(); } } Namespacing is one way of using our custom-created classes in Laravel. It is recommended to use namespace to manage your code easily under logical groups. The other method is to use custom classes is to add path in composer.json file. Add the class path to ‘classmap’. <?php \"autoload\": { \"psr-4\": { \"App\\\\\": \"app/\" }, \"classmap\": [ \"database/seeds\", \"database/factories\", \"app/Classes\" ] } Example of how a Resource Controller look 42
<?php namespaceApp\\Http\\Controllers; useIlluminate\\Http\\Request; classPhotoControllerextendsController { /** * Displayalistingoftheresource. * * @return\\Illuminate\\Http\\Response */ publicfunctionindex() { // } /**Showtheformforcreatinganewresource.*@return\\Illuminate\\Http\\Response */ publicfunctioncreate() { // } /** * Store a newly created resource in storage. * * @param \\Illuminate\\Http\\Request $request * @return \\Illuminate\\Http\\Response */ public function store(Request $request) 43
{ // } /** * Display the specified resource. * * @param int $id * @return \\Illuminate\\Http\\Response */ public function show($id) { // } /** * Show the form for editing the specified resource. * * @param int $id * @return \\Illuminate\\Http\\Response */ public function edit($id) { // } 44
/** * Update the specified resource in storage. * * @param \\Illuminate\\Http\\Request $request * @param int $id * @return \\Illuminate\\Http\\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \\Illuminate\\Http\\Response */ public function destroy($id) { // } } The example of the resource controller shares the method name of those in the table below. Next, you may register a resourceful route to the controller: 45
Route::resource('photos', 'PhotoController'); This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions, including notes informing you of the HTTP verbs and URIs they handle. 4.4GET REQUESTED DATA IN CONTROLLER Accessing The Request To obtain an instance of the current HTTP request via dependency injection, you should type- hint the Illuminate\\Http\\Request class on your controller constructor or method. The current request instance will automatically be injected by the service container: <?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; use Illuminate\\Routing\\Controller; class UserController extends Controller { /** * Store a new user. * * @param Request $request * @return Response */ public function store(Request $request) { $name = $request->input('name'); 46
// } } If your controller method is also expecting input from a route parameter, simply list your route arguments after your other dependencies. For example, if your route is defined like so: Route::put('user/{id}', 'UserController@update'); You may still type-hint the Illuminate\\Http\\Request and access your route parameter id by defining your controller method like the following: <?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; use Illuminate\\Routing\\Controller; class UserController extends Controller { /** * Update the specified user. * * @param Request $request * @param int $id * @return Response */ public function update(Request $request, $id) { // } } Basic Request Information 47
The Illuminate\\Http\\Request instance provides a variety of methods for examining the HTTP request for your application. The Laravel Illuminate\\Http\\Request extends the Symfony\\Component\\HttpFoundation\\Request class. Here are a few more of the useful methods available on this class: Retrieving The Request URI The path method returns the request's URI. So, if the incoming request is targeted at http://domain.com/foo/bar, the path method will return foo/bar: $uri = $request->path(); The is method allows you to verify that the incoming request URI matches a given pattern. You may use the * character as a wildcard when utilizing this method: if ($request->is('admin/*')) { // } To get the full URL, not just the path info, you may use the url method on the request instance: $url = $request->url(); Retrieving The Request Method The method method will return the HTTP verb for the request. You may also use the isMethod method to verify that the HTTP verb matches a given string: $method = $request->method(); if ($request->isMethod('post')) { // } PSR-7 Requests The PSR-7 standard specifies interfaces for HTTP messages, including requests and responses. If you would like to obtain an instance of a PSR-7 request, you will first need to install a few libraries. Laravel uses the Symfony HTTP Message Bridge component to convert typical Laravel requests and responses into PSR-7 compatible implementations: 48
composer require symfony/psr-http-message-bridge composer require zendframework/zend-diactoros Once you have installed these libraries, you may obtain a PSR-7 request by simply type- hinting the request type on your route or controller: use Psr\\Http\\Message\\ServerRequestInterface; Route::get('/', function (ServerRequestInterface $request) { // }); If you return a PSR-7 response instance from a route or controller, it will automatically be converted back to a Laravel response instance and be displayed by the framework. Retrieving Input Retrieving An Input Value Using a few simple methods, you may access all user input from your Illuminate\\Http\\Request instance. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs: $name = $request->input('name'); Alternatively, you may access user input using the properties of the Illuminate\\Http\\Request instance. For example, if one of your application's forms contains a name field, you may access the value of the posted field like so: $name = $request->name; You may pass a default value as the second argument to the input method. This value will be returned if the requested input value is not present on the request: $name = $request->input('name', 'Sally'); When working on forms with array inputs, you may use \"dot\" notation to access the arrays: $input = $request->input('products.0.name'); Determining If An Input Value Is Present 49
To determine if a value is present on the request, you may use the has method. The has method returns true if the value is present and is not an empty string: if ($request->has('name')) { // } Retrieving All Input Data You may also retrieve all of the input data as an array using the all method: $input = $request->all(); Retrieving A Portion Of The Input Data If you need to retrieve a sub-set of the input data, you may use the only and except methods. Both of these methods will accept a single array or a dynamic list of arguments: $input = $request->only(['username', 'password']); $input = $request->only('username', 'password'); $input = $request->except(['credit_card']); $input = $request->except('credit_card'); Old Input Laravel allows you to keep input from one request during the next request. This feature is particularly useful for re-populating forms after detecting validation errors. However, if you are using Laravel's included validation services, it is unlikely you will need to manually use these methods, as some of Laravel's built-in validation facilities will call them automatically. Flashing Input To The Session The flash method on the Illuminate\\Http\\Request instance will flash the current input to the session so that it is available during the user's next request to the application: $request->flash(); You may also use the flashOnly and flashExcept methods to flash a sub-set of the request data into the session: $request->flashOnly('username', 'email'); $request->flashExcept('password'); 50
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226
- 227
- 228
- 229
- 230
- 231
- 232
- 233
- 234
- 235
- 236
- 237
- 238
- 239
- 240
- 241
- 242
- 243
- 244
- 245
- 246
- 247
- 248
- 249
- 250
- 251
- 252
- 253