Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU - BCA -Sem VI - ADVANCED WEB DEVELOPMENT USING PHP

CU - BCA -Sem VI - ADVANCED WEB DEVELOPMENT USING PHP

Published by Teamlease Edtech Ltd (Amita Chitroda), 2022-11-12 07:10:43

Description: CU - BCA -Sem VI - ADVANCED WEB DEVELOPMENT USING PHP

Search

Read the Text Version

["if (condition is true) { block one else block two } ?> HERE, \uf0b7 \u201cif (condition is true)\u201d is the control structure \uf0b7 \u201cblock one\u201d is the code to be executed if the condition is true \uf0b7 {\u2026else\u2026} is the fallback if the condition is false \uf0b7 \u201cblock two\u201d is the block of code executed if the condition is false How it works The flow chart shown below illustrates how the if then\u2026 else control structure works 151","Let\u2019s see this in action The code below uses \u201cif\u2026 then\u2026 else\u201d to determine the larger value between two numbers. <?php $first_number = 7; $second_number = 21; if ($first_number> $second_number){ echo \\\"$first_number is greater than $second_number\\\"; }else{ echo \\\"$second_number is greater than $first_number\\\"; 152","} ?> Output: 21 is greater than 7 9.4VALIDATION IN LARAVEL To learn about Laravel's powerful validation features, let's look at a complete example of validating a form and displaying the error messages back to the user. By reading this high- level overview, you'll be able to gain a good general understanding of how to validate incoming request data using Laravel: Defining The Routes First, let's assume we have the following routes defined in our routes\/web.php file: use App\\\\Http\\\\Controllers\\\\PostController; Route::get('\/post\/create', [PostController::class, 'create']); Route::post('\/post', [PostController::class, 'store']); The GET route will display a form for the user to create a new blog post, while the POST route will store the new blog post in the database. Creating The Controller Next, let's take a look at a simple controller that handles incoming requests to these routes. We'll leave the store method empty for now: <?php namespace App\\\\Http\\\\Controllers; use App\\\\Http\\\\Controllers\\\\Controller; use Illuminate\\\\Http\\\\Request; class PostController extends Controller { 153","\/** * Show the form to create a new blog post. * * @return \\\\Illuminate\\\\View\\\\View *\/ public function create() { return view('post.create'); } \/** * Store a new blog post. * * @param \\\\Illuminate\\\\Http\\\\Request $request * @return \\\\Illuminate\\\\Http\\\\Response *\/ public function store(Request $request) { \/\/ Validate and store the blog post... } } Writing The Validation Logic Now we are ready to fill in our store method with the logic to validate the new blog post. To do this, we will use the validate method provided by the Illuminate\\\\Http\\\\Request object. If the validation rules pass, your code will keep executing normally; however, if validation fails, an Illuminate\\\\Validation\\\\ValidationException exception will be thrown and the proper error response will automatically be sent back to the user. 154","If validation fails during a traditional HTTP request, a redirect response to the previous URL will be generated. If the incoming request is an XHR request, a JSON response containing the validation error messages will be returned. To get a better understanding of the validate method, let's jump back into the store method: \/** * Store a new blog post. * * @param \\\\Illuminate\\\\Http\\\\Request $request * @return \\\\Illuminate\\\\Http\\\\Response *\/ public function store(Request $request) { $validated = $request->validate([ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); \/\/ The blog post is valid... } As you can see, the validation rules are passed into the validate method. Don't worry - all available validation rules are documented. Again, if the validation fails, the proper response will automatically be generated. If the validation passes, our controller will continue executing normally. Alternatively, validation rules may be specified as arrays of rules instead of a single | delimited string: $validatedData = $request->validate([ 'title' => ['required', 'unique:posts', 'max:255'], 155","'body' => ['required'], ]); In addition, you may use the validateWithBag method to validate a request and store any error messages within a named error bag: $validatedData = $request->validateWithBag('post', [ 'title' => ['required', 'unique:posts', 'max:255'], 'body' => ['required'], ]); Stopping On First Validation Failure Sometimes you may wish to stop running validation rules on an attribute after the first validation failure. To do so, assign the bail rule to the attribute: $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]); In this example, if the unique rule on the title attribute fails, the max rule will not be checked. Rules will be validated in the order they are assigned. A Note On Nested Attributes If the incoming HTTP request contains \\\"nested\\\" field data, you may specify these fields in your validation rules using \\\"dot\\\" syntax: $request->validate([ 'title' => 'required|unique:posts|max:255', 'author.name' => 'required', 'author.description' => 'required', ]); On the other hand, if your field name contains a literal period, you can explicitly prevent this from being interpreted as \\\"dot\\\" syntax by escaping the period with a backslash: 156","$request->validate([ 'title' => 'required|unique:posts|max:255', 'v1\\\\.0' => 'required', ]); Displaying The Validation Errors So, what if the incoming request fields do not pass the given validation rules? As mentioned previously, Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session. An $errors variable is shared with all of your application's views by the Illuminate\\\\View\\\\Middleware\\\\ShareErrorsFromSession middleware, which is provided by the web middleware group. When this middleware is applied an $errors variable will always be available in your views, allowing you to conveniently assume the $errors variable is always defined and can be safely used. The $errors variable will be an instance of Illuminate\\\\Support\\\\MessageBag. So, in our example, the user will be redirected to our controller's create method when validation fails, allowing us to display the error messages in the view: <!-- \/resources\/views\/post\/create.blade.php --> <h1>Create Post<\/h1> @if ($errors->any()) <div class=\\\"alert alert-danger\\\"> <ul> @foreach ($errors->all() as $error) <li>{{ $error }}<\/li> @endforeach <\/ul> 157","<\/div> @endif <!-- Create Post Form --> 9.5REDIRECTION IN LARAVEL, we normally use redirect() helper method for redirect user in controller. We can simply use redirect() helper in laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9. Laravel version provided redirect(). there are several way to do redirect URL in Laravel. In this post i am going to give you all the way to redirect URL with parameters. There are several methods through we can redirect URL in Laravel 5 as listed bellow: 1) Redirect to URL 2) Redirect back to previous page 3) Redirect to Named Routes 4) Redirect to Named Routes with parameters 5) Redirect to Controller Action 6) Redirect to Controller Action With Parameters 7) Redirect with Flashed Session Data Redirect to URL you can simply redirect given URL, bellow example i simple redirect \\\"itsolutionstuff\/tags\\\" URL. Route: Route::get('itsolutionstuff\/tags', 'HomeController@tags'); Controller Method: publicfunction home() { 158","return redirect('itsolutionstuff\/tags'); } Redirect back to previous page In this example, we can redirect back to our previous page URL, so you can do it both way: publicfunction home() { return back(); } OR public function home2() { return redirect()->back(); } Redirect to Named Routes If you declare route with name and you want to redirect route from controller method then you can simply do it. Route: Route::get('itsolutionstuff\/tags', array('as'=> 'itsolutionstuff.tags', 'uses' => 'HomeController@tags')); Controller Method: publicfunction home() { return redirect()->route('itsolutionstuff.tags'); } Redirect to Named Routes with parameters If you declare route with name and also parameters and you want to redirect route from controller method then you can do it by following example. 159","Route: Route::get('itsolutionstuff\/tag\/{id}', array('as'=> 'itsolutionstuff.tag', 'uses' => 'HomeController@tags')); Controller Method: publicfunction home() { return redirect()->route('itsolutionstuff.tag',['id'=>17]); } Redirect to Controller Action we can also redirect controller method using action of redirect() helper as you can see bellow example: publicfunction home() { return redirect()->action('App\\\\Http\\\\Controllers\\\\HomeController@home'); } Redirect to Controller Action With Parameters we can also redirect controller method using action with parameters of redirect() helper as you can see bellow example: publicfunction home() { return redirect()->action('App\\\\Http\\\\Controllers\\\\HomeController@home',['id'=>17]); } Redirect with Flashed Session Data we can also pass flashed session message while redirect with routes or url in controller method as you can see bellow example. publicfunction home() { 160","return redirect('home')->with('message', 'Welcome to ItSolutionStuff Tutorials!'); } You can simply redirect above ways to URL from controller method. 9.6MIRATION AND SEEDING IN LARAVEL, Migrations are like version control for your database, allowing your team to easily modify and share the application\u2019s database schema. Migrations are typically paired with Laravel\u2019s schema builder to easily build your application\u2019s database schema. If you have ever had to tell a teammate to manually add a column to their local database schema, you\u2019ve faced the problem that database migrations solve. Laravel includes a simple method of seeding your database with test data using seed classes. All seed classes are stored in the database\/seeds directory. Seed classes may have any name you wish, but probably should follow some sensible convention, such as UsersTableSeeder, etc. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order. In this ,we will learn how to use laravel migrations and seeders for them. Laravel provides great functionality to create migrations which are the schema for the database. Laravel also provides seeder which is very helpful for creating dummy data. This dummy data is very useful for testing purposes. Setting Up Migrations The database Migration table will keep track of which migrations you have and have not run In this tutorial, we will a create migration for a products, categories and product_category A product has some categories, let\u2019s create a migration for Category table, To create a new migration file, use the make:migration {migration_file_name} -create={table_name} by Artisan command : php artisan make:migrationcreate_category_table \u2013create=categories Open the categories table migration file present in the database\/migrations directory. Replace the contents of the file with the contents present below. 161","<?php use Illuminate\\\\Support\\\\Facades\\\\Schema; use Illuminate\\\\Database\\\\Schema\\\\Blueprint; use Illuminate\\\\Database\\\\Migrations\\\\Migration; class CreateCategoryTable extends Migration { \/** * Run the migrations. * * @return void *\/ public function up() { Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); } \/** * Reverse the migrations. * * @return void *\/ public function down() { Schema::dropIfExists('categories'); } } 162","A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should reverse the operations performed by the up method. To create new columns in a table, whether in a create table call or a modify table call, use the instance of Blueprint that\u2019s passed into your closure: Schema::create('categories', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('description'); $table->timestamps(); }); Let\u2019s create a migration for the products table by running the following command. php artisan make:migrationcreate_product_table \u2014 create=products Open the products table migration file present in the database\/migrations directory. Replace the contents of the file with the contents present below. <?php use Illuminate\\\\Support\\\\Facades\\\\Schema; use Illuminate\\\\Database\\\\Schema\\\\Blueprint; use Illuminate\\\\Database\\\\Migrations\\\\Migration; class CreateProductTable extends Migration { \/** * Run the migrations. * * @return void *\/ public function up() { Schema::create('products', function (Blueprint $table) { $table->increments('id'); 163","$table->string('sku')->unique(); $table->string('title'); $table->text('description'); $table->float('price'); $table->timestamps(); }); } \/** * Reverse the migrations. * * @return void *\/ public function down() { Schema::dropIfExists('products'); } } Finally create a migration for the product-category table by running the following command. php artisan make:migrationcreate_product_category_table \u2014 create=product_category Open the product_category table migration file present in the database\/migrations directory. Replace the contents of the file with the contents present below. <?php use Illuminate\\\\Support\\\\Facades\\\\Schema; use Illuminate\\\\Database\\\\Schema\\\\Blueprint; use Illuminate\\\\Database\\\\Migrations\\\\Migration; class CreateProductCategoryTable extends Migration { \/** * Run the migrations. 164","* * @return void *\/ public function up() { Schema::create('product_category', function (Blueprint $table) { $table->integer('product_id'); $table->integer('category_id'); $table->primary(['product_id', 'category_id']); }); } \/** * Reverse the migrations. * * @return void *\/ public function down() { Schema::dropIfExists('product_category'); } } You can create some more migrations like a migration for the attributes, images, brands, stocks, comments, etc table. But for the sake of this tutorial, we will create a simple like above. Migration the database Now that we have created migrations, let\u2019s migrate them to the database. Run the following command to migrate the database. php artisan migrate After run this command, you will receive message like following : Migrating: 2018_07_27_161708_create_product_tableMigrated: 2018_07_27_161708_create_product_tableMigrating: 165","2018_07_27_130104_create_category_tableMigrated: 2018_07_27_130104_create_category_tableMigrating: 2018_08_10_120731_create_product_category_tableMigrated: 2018_08_10_120731_create_product_category_table Rolling Back Migrations If you forgot create any column, we can rollback the lastest migration operation (Migrations table in database will keep track of which migrations you have and haven\u2019t run), we may use the rollback command. This command rolls back the last \u201cbatch\u201d of migrations, which may include multiple migration files : php artisan migrate:rollback You may rollback a limited number of migrations by providing the step option to the rollback command. Fo example, the following command will rollback the last file migrations: php artisan migrate:rollback \u2014 step=5 Then you can open any table migration file present in the database\/migrations directory And add more columns. After finish, Run the following command to migrate the database. php artisan migrate Creating Database Seeders Now that we have created database migrations, let\u2019s create seeder for the categories, products and product_category table. To create a new seeder file, use the make:seeder {seeder_file_name} by Artisan command, Run the following command to create it. php artisan make:seederCategoriesTableSeederphp artisan make:seederProductsTableSeederphp artisan make:seederProductCategoryTableSeeder Open the CategoriesTableSeeder seeder file present in the database\/seeds directory. Replace the contents of the file with the contents present below. <?php use Illuminate\\\\Database\\\\Seeder; class CategoriesTableSeeder extends Seeder { 166","\/** * Run the database seeds. * * @return void *\/ public function run() { DB::table('categories')->insert([ [ 'title' => 'Dresses', 'description' => 'The The Dress Shop event is over, but there is still more to discover.', ], [ 'title' => 'Jewelry', 'description' => 'The Fashion Week | Your fashion, your style event is over, but there is still more to discover.', ], [ 'title' => 'Sunglasses', 'description' => 'The Sunglasses with Free Shipping event is over, but there is still more to discover.', ], ]); } } Open the ProductsTableSeeder seeder file present in the database\/seeds directory. Replace the contents of the file with the contents present below. <?php use Illuminate\\\\Database\\\\Seeder; class ProductTableSeeder extends Seeder 167","{ \/** * Run the database seeds. * * @return void *\/ public function run() { DB::table('products')->insert([ [ 'sku' => 'P0001', 'title' => 'Hot Women Holiday Strappy Button Pocket Ladies Summer Beach Midi Swing Sun Dress', 'description' => 'It is made of high quality materials,durableenought for your daily wearing. Stylish and fashion make you more attractive', 'price' => 7.98, ], [ 'sku' => 'P0002', 'title' => 'Womens Vintage Boho Long Maxi Evening Party Dress Summer Casual Beach Sundress', 'description' => 'It is a Summer Must have and a statement piece that will turn heads. Beautiful and high quality dress,Full Length, Chiffon Material', 'price' => 7.95, ], [ 'sku' => 'P0003', 'title' => 'Diamond Jewel 14K Gold Round Diamond Stud Earrings', 'description' => 'The weight of a precious stone and easiest way to measure a diamond.One carat is equal to 200 miligrams.', 'price' => 799, ], [ 'sku' => 'P0004', 168","'title' => 'Diamond Jewel 14K Gold Round Diamond Stud Earrings', 'description' => 'The weight of a precious stone and easiest way to measure a diamond.One carat is equal to 200 miligrams.', 'price' => 799, ], [ 'sku' => 'P0005', 'title' => 'J+S Premium Military Style Classic Aviator Sunglasses, Polarized, 100% UV protection', 'description' => 'POLARIZED LENS, UV 400 PROTECTION, HIGH QUALITY FRAME, PERFECT ALL ROUNDER, 100% RISK FREE PURCHASE', 'price' => 16.99, ], ]); } } Open the ProductCategoryTableSeeder seeder file present in the database\/seeds directory. Replace the contents of the file with the contents present below. <?php use Illuminate\\\\Database\\\\Seeder; class ProductCategoryTableSeeder extends Seeder { \/** * Run the database seeds. * * @return void *\/ public function run() { DB::table('product_category')->insert([ [ 169","'product_id' => 1, 'category_id' => 1, ], [ 'product_id' => 2, 'category_id' => 1, ], [ 'product_id' => 3, 'category_id' => 2, ], [ 'product_id' => 4, 'category_id' => 3, ], ]); } } Now, go to the DatabaseSeeder.php file located in database\/seeds directory and replace the run function with the code present below. <?php use Illuminate\\\\Database\\\\Seeder; class DatabaseSeeder extends Seeder { \/** * Seed the application's database. * * @return void *\/ public function run() { 170","$this->call([ CategoriesTableSeeder::class, ProductTableSeeder::class, ProductCategoryTableSeeder::class, ]); } } Of course, manually specifying the attributes for each model seed is cumbersome. Instead you can use model factories to conveniently generate large amounts of database records. Running Seeders Once you have written your seeder, you may need to regenerate Composer\u2019s autoloader using the dump-autoload command: composer dump-autoload Now, that our database migrations and seeder are created. Run the command below to seed the database php artisan db:seed By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the \u2013class option to specify a specific seeder class to run individually : php artisan db:seed \u2013class= CategoriesTableSeederphp artisan db:seed \u2013class= ProductTableSeederphp artisan db:seed \u2013class= ProductCategoryTableSeeder 9.7ARTISAN COMMANDS IN LARAVEL Laravel is a full-stack framework that offers a lot of artisan commands to automate various actions, like creating a controller, seeding the database, and starting the server. However, when you build custom solutions, you have your own special needs, which could include a new command. Laravel doesn\u2019t limit you to only its commands; you can create your own in a few steps. Here are the steps for how to create a new artisan command. Step 1: Create a new Laravel application 171","laravel new custom Step 2: Create a command Use the make:command command to create a new command. Simply pass in the command name, like so: php artisan make:command CheckUsers In this example, we\u2019re creating a command called CheckUsers. The command creates a file named CheckUsers.php, named after the command name, in a newly created Commands directory in the Console folder. The generated file contains the configurations of the newly created command that are easy to understand and edit. Step 3: Customize command First, set the command signature. This is what would be put after php artisan to run the command. In this example, we will use check:users, so the command will be accessible by running: php artisan check:users To do this, update the \uff04signature property of the command, like this: protected \uff04signature = 'check:users'; Next, set up a suitable description that would show up when php artisan list displays the command with other commands. To do this, update the \uff04description property to match this: protected \uff04description = 'Get count of users on the platform'; Finally, in the handle() method, perform whatever action you intend it to perform. In this example, the number of users on the platform is echoed. public function handle() { echo User::count() . \\\"\\\\n\\\"; } 172","Step 4: Test command In the terminal, run the command to see the number of users in your database. php artisan check:users Passing arguments to the command You could have a command that needs an argument to the function. For example, a command to clear all of a specific user\u2019s posts from the database would require the user\u2019s id. To add an argument, update the \uff04signature string and add the argument in curly braces. protected \uff04signature = 'remove:posts {userId}'; This command would then be called where the id of a user is 5: php artisan remove:posts 5 At other times, you want to be able to pass in an argument, but not always, so you can make the argument optional by appending a question mark at the end, as follows: protected \uff04signature = 'remove:posts {userId?}'; You may also set a default value for an argument like so: protected \uff04signature = 'remove:posts {userId=6}'; You may also pass in multiple arguments and make them optional or with default values as you wish. protected \uff04signature = 'remove:posts{userId} {\uff04userAge?} {\uff04userStatus=alive}' These arguments can be accessed using: \uff04this->arguments() This returns an associative array with arguments as key and their values as values. So to access the userId argument, you can get it like this: \uff04user_id = \uff04this->arguments()['userId']; However, there\u2019s another way to get only one argument: 173","\uff04user_id = \uff04this->argument('userId'); Passing options to the command The command may also receive options. Options are like arguments, and they are used to add more information to the command. They can be used with no arguments. For example, to get the count of only users with verified emails, you may pass in a -- verified option to the command. To create an option, pass it into the \uff04signature property like the argument, but prefix it with --. protected \uff04signature = 'check:users {--verified}'; Now, the command may be used with an option like this: php artisan check:users --verified You may set a default value for an option or set it to require a value. protected \uff04signature = 'check:users {--verified} {--add=} {--delete=5}'; In this example, add requires a value to be used and delete has a default value of 5. verified is assigned a Boolean value depending on whether it is passed in. The value of these options can be accessed easily using \uff04this->option('verified') for the single ones and \uff04this->options() to get all options as an associative array. Describing input parameters So far, we\u2019ve learned how to accept arguments and even options, but when the command is used with php artisan help, these inputs have no description. To set these, simply add a colon, :, after the argument or option name. protected \uff04signature = ' check:users {userId: Id of user to be fetched} {--verified: Gets count of verified users} '; 174","Now, when php artisan --help check:users is run, you should see something like this: Input description shows 9.8SUMMARY \uf0b7 Laravel redirects are those which transport the user from one page to another. This page may be a different web page altogether or within the same website. \uf0b7 Redirects help the users to visit other parts of the page or get relevant information about the same subject, without having to hunt for it themselves. \uf0b7 This leads to the saving of a whole lot of time. \uf0b7 Redirects also increase the level of satisfaction in user experience, which is the ultimate goal of any developer. 9.9KEYWORDS 175","\uf0b7 If Statement if statement allows conditional execution of code. It is executed if condition is true. If statement is used to executes the block of code exist inside the if statement only if the specified condition is true. \uf0b7 If-else Statement if-else statement is executed whether condition is true or false. If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false. \uf0b7 If-else-if Statement The if-else-if is a special statement used to combine multiple if?.else statements. So, we can check multiple conditions using this statement. \uf0b7 nested if Statement The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true. 9.10 LEARNING ACTIVITY Difference between Miration and seeding in laravel List all artisn commands 9.11 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Give syntax of if statement 2. Give syntax of if-else 3. Difference between if and if else with example 4. Laravel is based on _____________________ ... 5. Why miration use for? Long Questions 1. Which of following Collection method returns all records from Laravel collection? ... 2. Which one Laravel command line interface? ... 3. Which command is used to start laravel server 4. How ternary operator works 5. What are Validations? 176","6. How to use redirection in laravel B. Multiple Choice Questions 1. What will be the output of the following PHP code? <?php $x = 10; $y = 20; if ($x > $y && 1||1) print \\\"1000 PHP MCQ\\\" ; else print \\\"Welcome to Sanfoundry\\\"; ?> a) no output b) Welcome to Sanfoundry c) 1000 PHP MCQ d) error Answer: c 2. Which is the right way of declaring a variable in PHP? a) $3hello b) $_hello c) $this d) $5_Hello Answer: b 3. What will be the output of the following PHP program? <?php $fruits = array (\\\"apple\\\", \\\"orange\\\", array (\\\"pear\\\", \\\"mango\\\"),\\\"banana\\\"); echo (count($fruits, 1)); 177","?> a) 6 b) 5 c) 4 d) 3 Answer: a 4. What will be the output of the following PHP program? <?php function multi($num) { if ($num == 3) echo \\\"I Wonder\\\"; if ($num == 7) echo \\\"Which One\\\"; if ($num == 8) echo \\\"Is The\\\"; if ($num == 19) echo \\\"Correct Answer\\\"; } $can = stripos(\\\"I love php, I love phptoo!\\\",\\\"PHP\\\"); multi($can); ?> a) Correct Answer b) Is The c) I Wonder 178","d) Which One Answer: d 5. Which of the following PHP functions can be used for generating unique ids? a) md5() b) uniqueid() c) mdid() d) id() Answer: b 9.12 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 UNIT - 10MIDDLEWARE STRUCTURE 10.0. Learning Objectives 10.1. Introduction 10.2. what is middleware in Laravel 10.3. what its uses 10.4. how to create middleware 10.5. Summary 10.6. Keywords 10.7. Learning Activity 179","10.8. Unit End Questions 10.9. References 10 LEARNING OBJECTIVES After studying this unit, you will be able toknow : \uf0b7 what is middleware in Laravel \uf0b7 what its uses \uf0b7 how to create middleware 10.1 INTRODUCTION Middleware provide a convenient mechanism for inspecting and filtering HTTP requests entering your application. For example, Laravel includes a middleware that verifies the user of your application is authenticated. If the user is not authenticated, the middleware will redirect the user to your application's login screen. However, if the user is authenticated, the middleware will allow the request to proceed further into the application. Additional middleware can be written to perform a variety of tasks besides authentication. For example, a logging middleware might log all incoming requests to your application. There are several middleware included in the Laravel framework, including middleware for authentication and CSRF protection. All of these middleware are located in the app\/Http\/Middleware directory. 10.2 WHAT IS MIDDLEWARE IN LARAVEL Middleware is another essential component of Laravel and provides the method to filter HTTP requests that get entered into your project. Let us assume a situation where this middleware of Laravel checks for an authenticated user of your software or project. In case the authentication is verified as valid, the middleware feature will let the user proceed with your project. There is another middleware name CORS in charge of adding appropriate headers to all of your responses. 180","10.3 WHAT ITS USES Middleware acts as a layer between the user and the request. It means that when the user requests the server then the request will pass through the middleware, and then the middleware verifies whether the request is authenticated or not. If the user's request is authenticated then the request is sent to the backend. If the user request is not authenticated, then the middleware will redirect the user to the login screen. An additional middleware can be used to perform a variety of tasks except for authentication. For example, CORS middleware is responsible for adding headers to all the responses. Laravel framework includes several middleware such as authentication and CSRF protection, and all these are located in the app\/Http\/Middleware directory. 10.4 HOW TO CREATE MIDDLEWARE Middleware can be defined as a middle-man or interface acting in coordination between a request and a response. As mentioned in the above test scenario, if the user is not authenticated, your project may redirect that user from the login.php to index.php page. You can create your middleware by running the syntax mentioned below: Syntax: php artisan make:middleware<middleware_name> Here, you have to replace the <middleware_name> with your middleware. You can see this path location app\/Http\/Middleware the middleware that you will be creating your project. Example: php artisan make:middleware CheckUser Registering Middlewares Before using any middleware, you have to register it. Laravel provides two types of Middlewares. These are: \uf0b7 Global Middleware \uf0b7 Route Middleware 181","Global middlewares are those that will be running during every HTTP request of your application. In the $middleware property of your app\/Http\/Kernel.php class, you can list all the global middleware for your project. When you want a middleware to specific routes, you have to add the middleware with a key for your app\/Http\/Kernel.php file, and such middlewares are called route middleware. $routeMiddleware, by default, holds entries for the middleware that are already incorporated in Laravel. For adding your custom middleware, you need to append them to the list and add a key of your choice. Example: rotected $routeMiddleware = [ 'auth' =>\\\\Illuminate\\\\Auth\\\\Middleware\\\\Authenticate::class, 'auth.basic' =>\\\\Illuminate\\\\Auth\\\\Middleware\\\\AuthenticateWithBasicAuth::class, 'guest' =>\\\\App\\\\Http\\\\Middleware\\\\RedirectIfAuthenticated::class, 'userAuth' =>\\\\Illuminate\\\\Routing\\\\Middleware\\\\UserAuthRequests::class, ]; Middleware Parameters Parameters can also be passed to middlewares. Various parameterized situations can be when your project has attributes like a customer, employee, admin, owner, etc. You want to execute different modules based on the user's roles; for those situations, middlewares' parameters become useful. Example: public function handle($request, Closure $next, $profile) { if (! $request->user()->hasProfile($profile)) { \/\/ Next page } return $next($request); } 182","} It would help if you created the Profile middleware by running the code mentioned below: php artisan make:middlewareProfileMiddleware The newly created middleware can be handled using the code: app\/Http\/Middleware\/ProfileMiddleware.php Example: <?php namespace App\\\\Http\\\\Middleware; use Closure; class ProfileMiddleware { public function handle($request, Closure $next, $Profile) { echo \\\"Role: \\\".$Profile; return $next($request); } } Terminable Middlewares These are special types of middlewares that start working right after any response is sent to the browser. The terminate method is used for achieving this. When a termination method is used in your project's middleware, it gets called automatically after the browser response is sent. Example: <?php namespace Illuminate\\\\Session\\\\Middleware; use Closure; 183","class SessionBegin { public function handle($request, Closure $next) { return $next($request); } public function terminate($request, $response) { \/\/ tasks assigned within terminate method } } 10.5 SUMMARY \uf0b7 we can say that Laravel middleware is an important feature provided by Laravel for the users who can use it to handle the exchange of information in the process of requests and responses that the application needs to take command over. \uf0b7 It is a security feature that gives limited access if any random person tries to seek information or data from the application. \uf0b7 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. \uf0b7 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. \uf0b7 Middleware can be created by executing the following command \u2212 \uf0b7 php artisan make:middleware<middleware-name> \uf0b7 Replace the <middleware-name> with the name of your middleware. The middleware that you create can be seen at app\/Http\/Middleware directory. \uf0b7 10.6 KEYWORDS \uf0b7 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 184","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); } \uf0b7 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. \uf0b7 app\/Http\/routes.php Route::get('terminate',[ 'middleware' => 'terminate', 'uses' => 'ABCController@index', ]); \uf0b7 Laravel middleware, as its name suggests implements some functionality during the request hit on the particular URI. 10.7 LEARNING ACTIVITY 1.what its uses of middleware 2. how to create middleware 10.8 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. what is middleware in Laravel 2. How do you make and use Middleware in Laravel? 3. How to use Stored Procedure in Laravel? 4. How Laravel implicit bound middleware work? 185","5. how to avoid running burst operations in laravel middleware Long Questions 1. how to Add Multiple Middleware Directly To Route 2. what to do when Laravel middleware does not recognize user is logged in 3. how to use custom rule in middleware of laravel 9.x? 4. How Laravel implicit bound middleware work? 5. How to use laravel middleware with parameter in route executed twice 6. How to test middleware in Laravel B. Multiple Choice Questions 1. Middleware has enabled the production of various types of smart machines having microprocessor chips with embedded software. a) True b) False Answer: b 2. A \u201cglue\u201d between client and server parts of application. a) Middleware b) Firmware c) Package d) System Software Answer: a 3. MOM stands for? a) Message oriented middleware b) Mails oriented middleware c) Middleware of messages d) Main object middleware Answer: a 4. Storage of firmware is ___________ a) Cache Memory b) RAM c) External d) ROM 186","Answer: d 5. DNS stands for? a) Domain Name System b) Direct Name System c) Direct Network System d) Domain Network System Answer: a 6. A software that lies between the OS and the applications running on it. a) Firmware b) Middleware c) Utility Software d) Application Software Answer: b 7. A type of middleware that allows for between the built-in applications and the real-time OS? a) Firmware b) Database middleware c) Portals d) Embedded Middleware Answer: d 10.9 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 187","UNIT \u201311SESSION HANDLING IN LARAVEL STRUCTURE 11.0. Learning Objectives 11.1. Introduction 11.2. how to create session and get session data 11.3. Summary 11.4. Keywords 11.5. Learning Activity 11.6. Unit End Questions 11.7. References 11 LEARNING OBJECTIVES After studying this unit, you will be able to: \uf0b7 Know sessions \uf0b7 Know how to create session \uf0b7 understand how to get session data 11.1 INTRODUCTION You know that Session is useful to hide the data which the user can not be able to read or write. Sessions are easier to handle in Laravel. Sometimes we need to store data in our session without saving it in the database. That case session is the best option to put this data somewhere. Like we want a create a session-based login system, or create an add to cart e- commerce option using session. 11.2 HOW TO CREATE SESSION AND GET SESSION DATA In a programming language, session is a great way to store data. It makes easy to handle data without storing in a database. Session is useful to protect the data that the user wouldn't be able to read or write. Sessions are easier and secure cookies. Sessions are useful user logins, carts etc. 188","Laravel framework has easy ways to store and retrieve session. Laravel session can be stored in database, files or encrypted cookies. Laravel session configuration is stored in config\/session.php file. By default, Laravel store session data in files. If you want to store session in database table, then change session driver to database and run bellow command to generate sessions table. php artisan session:table php artisan migrate This will create session table in database where all session data is saved. Store data in session There are two ways to working with session, First is to Request instance and second use session() global helper method. \/\/ Request instance $request->session()->put('key','value'); \/\/ global session helper session(['key' => 'value']); Get data with specific key To get data with specific key, use bellow methods. \/\/ Request instance $value = $request->session()->get('key'); \/\/ global helper method $value = session('key'); \/\/ return session data with default value if not specific session key not found $value = session('key', 'default'); If you would like to retrieve all data store in session, use can use all() method. $data = $request->session()->all(); Check session data with key If you want to check if specific key exist in session, you may use has() method. 189","if ($request->session()->has('users')) { \/\/ 'user' key is in session $user = $request->session()->get('users'); } If you also want to check if session value is null, then use exist() method. if ($request->session()->exists('users')) { \/\/ 'user' is exist in session $user = $request->session()->get('users'); } Push to array session values If you want to push value to existing session array, you can use push() method. This will set new value for frameworks key of php array. $request->session()->push('php.frameworks', 'laravel'); Delete session data If you want to remove specific key from the array, then use forget() method. $request->session()->forget('key'); Or if you want to retrieve and remove the key, then use pull() method. $value = $request->session()->pull('key', 'default'); If you want to delete multiple session data, then pass array of keys to forget() method. $request->session()->forget(['key1', 'key2']); If you want to delete all session data, then use flush() method. $request->session()->flush(); You may manually regenerate the session ID, you may use the regenerate() method. This prevents users to make malicious fixation in session. $request->session()->regenerate(); 190","11.3 SUMMARY \uf0b7 Laravel provides more inbuilt method to get and set session data. it\u2019s easy to working with session in laravel. \uf0b7 A session variable is used to store some information or some data about user or anything you want to access on all pages of an application. \uf0b7 In laravel session configuration is stored in \u201capp\/config\/session.php\u201d. 11.4 KEYWORDS \uf0b7 Store data in session There are two ways to working with session, First is to Request instance and second use session() global helper method. \uf0b7 Get data with specific key To get data with specific key, use bellow methods. \uf0b7 Check session data with key If you want to check if specific key exist in session, you may use has() method. \uf0b7 Push to array session values If you want to push value to existing session array, you can use push() method. This will set new value for frameworks key of php array. \uf0b7 Delete session data If you want to remove specific key from the array, then use forget() method. 11.5 LEARNING ACTIVITY 1. how to create session 2. how to get session data 11.6 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is sessions in Laravel 2. What is session handler 3. How Laravel handler help in session 4. How to Understand Laravel Session Handler 5. Explain laravel session management in subdomain Long Questions 191","1. What is Laravel random drop session 2. How to implement Laravel random drop session 3. How to implement laravel and multi-sessions from the same browser 4. How does the Sessions work? 5. How will you explain Events in Laravel? B. Multiple Choice Questions 1. Which one of the following is the very first task executed by a session enabled page? a) Delete the previous session b) Start a new session c) Check whether a valid session exists d) Handle the session Answer: c 2. How many ways can a session data be stored? a) 3 b) 4 c) 5 d) 6 Answer: b 3. Which directive determines how the session information will be stored? a) save_data b) session.save c) session.save_data d) session.save_handler Answer: d 4. Which one of the following is the default PHP session name? a) PHPSESSID b) PHPSESID c) PHPSESSIONID 192","d) PHPIDSESS Answer: a 5. If session.use_cookie is set to 0, this results in use of _____________ a) Session b) Cookie c) URL rewriting d) Nothing happens Answer: c 11.7 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 193","UNIT - 12HANDLING DATABASE STRUCTURE 12.0. Learning Objectives 12.1. Introduction 12.2. Configuration and connectivity 12.3. fetching data from database 12.4. insertion and updation form data in database 12.5. joins in Laravel 12.6. getQueryLog () 12.7. create laravel application 12.8. Summary 12.9. Keywords 12.10. Learning Activity 12.11. Unit End Questions 12.12. References 12 LEARNING OBJECTIVES After studying this unit, you will be able toknow : \uf0b7 Configuration and connectivity \uf0b7 fetching data from database \uf0b7 insertion and updation form data in database \uf0b7 joins in Laravel \uf0b7 getQueryLog () \uf0b7 create laravel application 12.1 INTRODUCTION Laravel makes connecting with databases and running queries extremely simple. The database configuration file is app\/config\/database.php. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file. 194","You know that Session is useful to hide the data which the user can not be able to read or write. 12.2 CONFIGURATION AND CONNECTIVITY Laravel makes connecting with databases and running queries extremely simple. The database configuration file is app\/config\/database.php. In this file you may define all of your database connections, as well as specify which connection should be used by default. Examples for all of the supported database systems are provided in this file. Currently Laravel supports four database systems: MySQL, Postgres, SQLite, and SQL Server. Read \/ Write Connections Sometimes you may wish to use one database connection for SELECT statements, and another for INSERT, UPDATE, and DELETE statements. Laravel makes this a breeze, and the proper connections will always be used whether you are using raw queries, the query builder, or the Eloquent ORM. To see how read \/ write connections should be configured, let's look at this example: 'mysql' => array( 'read' => array( 'host' => '192.168.1.1', ), 'write' => array( 'host' => '196.168.1.2' ), 'driver' => 'mysql', 'database' => 'database', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 195","'collation' => 'utf8_unicode_ci', 'prefix' => '', ), Note that two keys have been added to the configuration array: read and write. Both of these keys have array values containing a single key: host. The rest of the database options for the read and write connections will be merged from the main mysql array. So, we only need to place items in the read and write arrays if we wish to override the values in the main array. So, in this case, 192.168.1.1 will be used as the \\\"read\\\" connection, while 192.168.1.2 will be used as the \\\"write\\\" connection. The database credentials, prefix, character set, and all other options in the main mysql array will be shared across both connections. 12.3 FETCHING DATA FROM DATABASE In this example we will discuss about how to retrieve a record or data from MySQL database using laravel framework PHP. For retrieve data from MySQL database using laravel framework first we have to create a table in data base. The SELECT statement is used to retrieve data from one or more tables: The SQL query for retrieve specific column. SELECT column_name(s) FROM table_name or we can use the * character to retrieve ALL columns from a table: SELECT * FROM table_name Create 3 files for retrieve data in Laravel : \uf0b7 StudViewController.php (app\/Http\/Controllers\/StudViewController.php) \uf0b7 stud_view.blade.php (resources\/views\/stud_view.blade.php) \uf0b7 web.php (routes\/web.php) 196","In this example we retrieve the students data. stud_view.blade.php <!DOCTPE html> <html> <head> <title>View Student Records<\/title> <\/head> <body> <table border = \\\"1\\\"> <tr> <td>Id<\/td> <td>First Name<\/td> <td>Last Name<\/td> <td>City Name<\/td> <td>Email<\/td> <\/tr> @foreach ($users as $user) <tr> <td>{{ $user->id }}<\/td> <td>{{ $user->first_name }}<\/td> <td>{{ $user->last_name }}<\/td> <td>{{ $user->city_name }}<\/td> <td>{{ $user->email }}<\/td> <\/tr> @endforeach <\/table> <\/body> <\/html> StudViewController.php <?php class=\\\"ezoic-autoinsert-ad ezoic-under_first_paragraph\\\">namespace App\\\\Http\\\\Controllers; use Illuminate\\\\Http\\\\Request; 197","use DB; use App\\\\Http\\\\Requests; use App\\\\Http\\\\Controllers\\\\Controller; class StudViewController extends Controller { public function index(){ $users = DB::select('select * from student_details'); return view('stud_view',['users'=>$users]); } } 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! | *\/ \/\/retrive data Route::get('view-records','StudViewController@index'); After fetch data the table look like this. Id first name last name City name Email Id 1 Divyasundar Sahu Mumbai [email protected] 2 Hritika Sahu Pune [email protected] 198","3 Milan Jena Chennai [email protected] 12.4 INSERTION AND UPDATION FORM DATA IN DATABASE In this example we are going to show you how to insert data in database using laravel framework PHP. For insert data in MySQL using laravel first we have to create a table in data base. The INSERT INTO statement is used to insert new data to a MySQL table: INSERT INTO table_name (column1, column2, column3,...) VALUES (value1, value2, value3,...) To learn more about SQL, please visit our SQL tutorial. For creating table the SQL query is: SQL Query CREATE TABLE student_detailid int NOT NULL AUTO_INCREMENTfirst_name varchar(50), last_name varchar(50city_name varchar(50)email varchar(50)PRIMARY KEY(id) )Create 3 files for insert data in Laravel : \uf0b7 StudInsertController.php (app\/Http\/Controllers\/StudInsertController.php) \uf0b7 stud_create.php (resources\/views\/stud_create.php) \uf0b7 web.php (routes\/web.php) stud_create.blade.php(View File) <!DOCTYPE html> <html> <head> <title>Student Management | Add<\/title> 199","<\/head> <body> @if (session('status')) <div class=\\\"alert alert-success\\\" role=\\\"alert\\\"> <button type=\\\"button\\\" class=\\\"close\\\" data-dismiss=\\\"alert\\\">\u00d7<\/button> {{ session('status') }} <\/div> @elseif(session('failed')) <div class=\\\"alert alert-danger\\\" role=\\\"alert\\\"> <button type=\\\"button\\\" class=\\\"close\\\" data-dismiss=\\\"alert\\\">\u00d7<\/button> {{ session('failed') }} <\/div> @endif <form action = \\\"\/create\\\" method = \\\"post\\\"> <input type = \\\"hidden\\\" name = \\\"_token\\\" value = \\\"<?php echo csrf_token(); ?>\\\"> <table> <tr> <td>First Name<\/td> <td><input type='text' name='first_name' \/><\/td> <tr> <td>Last Name<\/td> <td><input type=\\\"text\\\" name='last_name'\/><\/td> <\/tr> <tr> <td>City Name<\/td> <td> 200"]


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook