Flash Input Into Session Then Redirect Since you often will want to flash input in association with a redirect to the previous page, you may easily chain input flashing onto a redirect using the withInput method: return redirect('form')->withInput(); return redirect('form')->withInput($request->except('password')); Retrieving Old Data To retrieve flashed input from the previous request, use the old method on the Request instance. The old method provides a convenient helper for pulling the flashed input data out of the session: $username = $request->old('username'); Laravel also provides a global old helper function. If you are displaying old input within a Blade template, it is more convenient to use the old helper: {{ old('username') }} Cookies Retrieving Cookies From The Request All cookies created by the Laravel framework are encrypted and signed with an authentication code, meaning they will be considered invalid if they have been changed by the client. To retrieve a cookie value from the request, you may use the cookie method on the Illuminate\\Http\\Request instance: $value = $request->cookie('name'); Attaching A New Cookie To A Response Laravel provides a global cookie helper function which serves as a simple factory for generating new Symfony\\Component\\HttpFoundation\\Cookie instances. The cookies may be attached to a Illuminate\\Http\\Response instance using the withCookie method: $response = new Illuminate\\Http\\Response('Hello World'); $response->withCookie(cookie('name', 'value', $minutes)); 51
return $response; To create a long-lived cookie, which lasts for five years, you may use the forever method on the cookie factory by first calling the cookie helper with no arguments, and then chaining the forever method onto the returned cookie factory: $response->withCookie(cookie()->forever('name', 'value')); Files Retrieving Uploaded Files You may access uploaded files that are included with the Illuminate\\Http\\Request instance using the file method. The object returned by the file method is an instance of the Symfony\\Component\\HttpFoundation\\File\\UploadedFile class, which extends the PHP SplFileInfo class and provides a variety of methods for interacting with the file: $file = $request->file('photo'); Verifying File Presence You may also determine if a file is present on the request using the hasFile method: if ($request->hasFile('photo')) { // } Validating Successful Uploads In addition to checking if the file is present, you may verify that there were no problems uploading the file via the isValid method: if ($request->file('photo')->isValid()) { // } Moving Uploaded Files To move the uploaded file to a new location, you should use the move method. This method will move the file from its temporary upload location (as determined by your PHP configuration) to a more permanent destination of your choosing: $request->file('photo')->move($destinationPath); 52
$request->file('photo')->move($destinationPath, $fileName); Other File Methods There are a variety of other methods available on UploadedFile instances. Check out the API documentation for the class for more information regarding these methods. 4.5ACCESSING FORM DATA IN CONTROLLER There are different ways to access data from views to controller, In this post, we are going to learn how to access view form data into controller using Request object. To demonstrate this, let’s create a form. VIEW CODE <h2>Receive With Request Form</h2> @using (Html.BeginForm(\"ReceiveWithRequestFormData\", \"ControllerAndAction\")) { <ol> <li> @Html.Label(\"Username\") @Html.TextBox(\"txtUserName\") : user </li> <li> @Html.Label(\"Password\") @Html.TextBox(\"txtPassword\") : pass </li> </ol> <input type=\"submit\" value=\"Login\" /> } <div id=\"divResult\"></div> 53
In the above code, we are creating two textboxes and a Login button. As the first parameter of the Html.BeginForm is ReceiveWithRequestForm and second parameter is ControllerAndAction so clicking on the Login button submit the page on /ControllerAndAction/ReceiveWithRequestForm url. CONTROLLER CODE public ActionResultReceiveWithRequestForm() { return View(); } Above method renders above View. When Login button is clicked below action method of the controller executes. [HttpPost] public ActionResultReceiveWithRequestFormData() { string userName = Request.Form[\"txtUserName\"]; string password = Request.Form[\"txtPassword\"]; if (userName.Equals(\"user\", StringComparison.CurrentCultureIgnoreCase) &&password.Equals(\"pass\", StringComparison.CurrentCultureIgnoreCase)) { return Content(\"Login successful !\"); } else 54
{ return Content(\"Login failed !\"); } } To access the form elements value, we can use Request.Form collection by passing the name of the form element. 4.6CONNECTING CONTROLLER WITH ROUTE FILE. Create custom route file in laravel; Through this tutorial, i am going to show you how to create custom route file or multiple routes file in laravel apps. How to Create Custom Route File in Laravel Follow the below given steps to create custom route file in laravel apps; is as follows: Step 1: Install Laravel App Step 2: Create Custom Route File Step 3: Add Route Files to ServiceProvider Step 1: Install Laravel App Run the following command on command prompt to install laravel fresh application into your system: composer create-project --prefer-distlaravel/laravel blog Step 2: Create Custom Route File Go to your app/routes folder and create custom routes file. And will create custom routes file name students.php. Then add routes in this file according to your requirements. ?php 55
/* |-------------------------------------------------------------------------- | User Routes |-------------------------------------------------------------------------- | | Here is where you can register user routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the \"user\" middleware group. Now create something great! | */ Route::get('/', function () { dd('Welcome to student routes.'); }); Step 3: Add Files to ServiceProvider Go to app/Providers folder and find RouteServiceProvider.php . Then open it and register your custom routes file as follow: <?php namespace App\\Providers; use Illuminate\\Support\\Facades\\Route; use Illuminate\\Foundation\\Support\\Providers\\RouteServiceProvider as ServiceProvider; class RouteServiceProvider extends ServiceProvider 56
{ /** * 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 */ public function boot() { parent::boot(); } /** * Define the routes for the application. * * @return void */ public function map() 57
{ $this->mapApiRoutes(); $this->mapWebRoutes(); $this->mapStudentRoutes(); } /** * Define the \"web\" routes for the application. * * These routes all receive session state, CSRF protection, etc. * * @return void */ protected function mapWebRoutes() { Route::middleware('web') ->namespace($this->namespace) ->group(base_path('routes/web.php')); } /** * Define the \"api\" routes for the application. * * These routes are typically stateless. * * @return void 58
*/ protected function mapApiRoutes() { Route::prefix('api') ->middleware('api') ->namespace($this->namespace) ->group(base_path('routes/api.php')); } /** * Define the \"student\" routes for the application. * * These routes are typically stateless. * * @return void */ protected function mapStudentRoutes() { Route::prefix('admin') ->namespace($this->namespace) ->group(base_path('routes/student.php')); } } To add your routes in student.php route file and use it as follow: http://localhost:8000/student/* 59
4.7SUMMARY Laravel is an MVC based PHP framework. In MVC architecture, ‘C‘ stands for ‘Controller‘. A Controller is that which controls the behavior of a request. It handles the requests coming from the Routes. In Laravel, a controller is in the ‘app/Http/Controllers’ directory. All the controllers, that are to be created, should be in this directory. We can create a controller using ‘make:controller’ Artisan command. Syntax: php artisan make:controllerUserController You can specify any name in place of ‘User’, but according to the naming convention of Laravel, you have to specify the word ‘Controller’ at the end for any name you specify. 4.8KEYWORDS 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) 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 ... 60
4.9LEARNING ACTIVITY 1.If you need to add additional routes to a resource controller beyond the default set of resource routes, you should define those routes after your call to Route::resource 2. _____ directory contains much of the custom code used to power your application, including the models, controllers and middleware. 4.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. How the Laravel controller method get the parameters? 2. Which method can be used to register a route that responds to all HTTP verbs? 3. Which is correct to create a route(s) to resource controller named 'PostController'? 4. Which is correct to have an optional parameter in route? 5. Which method can be used to create custom blade directives? 6. Correct way to set SQLite as database for unit testing? Long Questions 1. Which validation rules are acceptable? 2. How do you define a single action controller for the following route? Route::get('user/{id}', 'ShowProfile'); 3. The field under validation must be present in the input data and not empty. A field is considered 'empty' if one of the following conditions are true: 4. How access custom textbox name in Laravel using validation 'unique'? 5. How to use laravel routing for unknown number of parameters in URL. 6. ___ web applications respond to meaningful HTTP verbs with appropriate data. 7. ____ are an important part of any web-based application. They help control the flow of the application which allows us to receive input from our users and make decisions that affect the functionality of our applications. 8. Validation If checkbox ticked then Input text is required? 9. To protect application from cross-site request forgery attacks, which should be included in forms? 10. To validate a date named finish_date against following rules: -Should be date - Required -Should be greater than start_date which is correct validation rule? Multiple Choice Questions 1. Composer is a tool for ______ in PHP. A. Configuration B. Dependency management C. Interpolation D. None of the above 61
Answer: Dependency management 2. Which class is used in Laravel to handle exceptions? A. App\\Exception\\Handler B. App\\Exceptions\\Handler C. App\\Exceptions\\Handle D. None of above Answer: App\\Exceptions\\Handler 3. When was Laravel first released? A. June 2011 B. June 2007 C. June 2009 D. None Answer: June 2011 4. After running “artisan down”, The project will show the maintenance page. What would be HTTP Status return Code? A. 298 B. 503 C. 400 D. 254 Answer: 503 5. Where are all the Laravel Models stored at ? A. Inside Laravel database B. Within a server C. Main app directory D. None of the above Answer: Main app directory 6. Which of the following methods are used in Database Migrations classes? A. run() and delete() B. save() and update() C. execute() and rollback() D. up() and down() Answer: up() and down() 62
4.11 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 –5VIEW STRUCTURE 5.0.Learning Objectives 5.1.Introduction 5.2.Creating Blade file in Laravel 5.3.creating form in blade file 5.4.sending file or image through form 5.5.Summary 5.6.Keywords 5.7.Learning Activity 5.8.Unit End Questions 5.9.References 5. LEARNING OBJECTIVES After studying this unit, you will be able to know: o Creating Blade file in Laravel o creating form in blade file o sending file or image through form 63
5.1INTRODUCTION Views contain the html code required by your application, and it is a method in Laravel that separates the controller logic and domain logic from the presentation logic. Views are located in the resources folder, and its path is resources/views. Laravel Create Model is an MVC based PHP system. In the MVC architecture, ‘M’ stands for ‘Model’. A model is used as a way for questioning data to and from the table within the database. Laravel gives a basic way to do that using Eloquent ORM where each table incorporates a Model to interact with it. Views contain the html code required by your application, and it could be a strategy in Laravel that isolates the controller logic and domain logic from the introduction rationale. Views are found within the assets organizer, and its way is resources/views. 5.2CREATING BLADE FILE IN LARAVEL Step 1: Create a folder of your project name in the resources\\views folder. Step 2: Create layouts\\partials folder in project_name folder Step 3: Create header.blade.php, footer.blade.php and script/stylesheet.blade.php as per the requirement at the below path resources\\views\\project_name\\layouts\\partials Step 4: Create mainlayout.blade.php in the below path resources\\views\\project_name\\layouts And add the following code to add header, footer, script, and stylesheet file 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <title>Project Name </title> 5 @include('project_name.layouts.partials.stylesheet')//include stylesheet file 64
6 @yield('styles') // for page specific stylesheet 7 </head> 8 9 <body> 10 11@include('project_name.layouts.partials.script') // include script file 12@include('project_name.layouts.partials.header') // include header file 13 14@yield('content') //content part of page 15 16@include('project_name.layouts.partials.footer') // include footer file 17 18@yield('scripts') // for page specific script 19</body> 20</html> Step 5: Include the mainlayout file as per your requirement and add sections. 1 @extends('project_name.layouts.mainlayout') 2 @section('styles') 3 //page specific style 4 @endsection 5 @section('content') 6 // write your page content here 7 @endsection 8 @section('script') 9 // code for page specific script 65
10@endsection 5.3CREATING FORM IN BLADE FILE Step 1 – Install Laravel 8 Application Step 2 – Configuring Database using Env File Step 3 – Create Model & Migration File For Add Blog Post Form Step 4 – Create Routes Step 5 – Creating Controller Step 6 – Create Blade File For Add Blog Post Form Step 7 – Start Development Server Step 8 – Run Laravel 8 Form App On Browser Step 1 – Install Laravel 8 Application In step 1, open your terminal and navigate to your local web server directory using the following command: //for windows user cd xampp/htdocs //for ubuntu user cd var/www/html Then install laravel 8 latest application using the following command: composer create-project --prefer-distlaravel/laravelLaravelForm Step 2 – Configuring Database using Env File In step 2, open your downloaded laravel 8 app into any text editor. Then find .env file and configure database detail like following: DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 66
DB_DATABASE=db name DB_USERNAME=db user name DB_PASSWORD=db password Step 3 – Create Model & Migration File For Add Blog Post Form In step 3, open command prompt and navigate to your project by using the following command: cd / LaravelForm Then create model and migration file by using the following command: php artisan make:model Post -m The above command will create two files into your laravel 8 form application, which is located inside the following locations: LaravelForm/app/Models/Post.php LaravelForm/database/migrations/2020_09_09_025857_create_posts_table.php So, find create_posts_table.php file inside LaravelForm/database/migrations/ directory. Then open this file and add the following code into function up() on this file: public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->string('title'); $table->text('description'); $table->timestamps(); }); } Now, open again your terminal and type the following command on cmd to create tables into your selected database: php artisan migrate 67
Step 4 – Create Routes In step 4, open your web.php file, which is located inside routes directory. Then add the following routes into web.php file: <?php use Illuminate\\Support\\Facades\\Route; use App\\Http\\Controllers\\PostController; /* |-------------------------------------------------------------------------- | 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 () { return view('welcome'); }); Route::get('add-blog-post-form', [PostController::class, 'index']); Route::post('store-form', [PostController::class, 'store']); Step 5 – Creating Controller In step 5, create form controller by using the following command: php artisan make:controllerPostController The above command will create PostController.php file, which is located inside LaravelForm/app/Http/Controllers/ directory. So open PostController.php file and add the following code into it: 68
<?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; use App\\Models\\Post; class PostController extends Controller { public function index() { return view('add-blog-post-form'); } public function store(Request $request) { $post = new Post; $post->title = $request->title; $post->description = $request->description; $post->save(); return redirect('add-blog-post-form')->with('status', 'Blog Post Form Data Has Been inserted'); } } Step 6 – Create Blade File For Form In step 6, create new blade view file that named add-blog-post-form.blade.php inside resources/views directory for add blog post form. Then add the following html form code into add-blog-post-form.blade.php: <!DOCTYPE html> <html> <head> 69
<title>Laravel 8 Form Example Tutorial</title> <meta name=\"csrf-token\" content=\"{{ csrf_token() }}\"> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> </head> <body> <div class=\"container mt-4\"> @if(session('status')) <div class=\"alert alert-success\"> {{ session('status') }} </div> @endif <div class=\"card\"> <div class=\"card-header text-center font-weight-bold\"> Laravel 8 - Add Blog Post Form Example </div> <div class=\"card-body\"> <form name=\"add-blog-post-form\" id=\"add-blog-post-form\" method=\"post\" action=\"{{url('store-form')}}\"> @csrf <div class=\"form-group\"> <label for=\"exampleInputEmail1\">Title</label> <input type=\"text\" id=\"title\" name=\"title\" class=\"form-control\" required=\"\"> </div> <div class=\"form-group\"> <label for=\"exampleInputEmail1\">Description</label> <textarea name=\"description\" class=\"form-control\" required=\"\"></textarea> 70
</div> <button type=\"submit\" class=\"btnbtn-primary\">Submit</button> </form> </div> </div> </div> </body> </html> Step 7 – Start Development Server Finally, open your command prompt again and run the following command to start development server for your laravel 8 form application: php artisan serve Step 8 – Run Laravel 8 Form App On Browser In step 8, open your browser and fire the following url into your browser: http://127.0.0.1:8000/add-blog-post-form When you fire the above given url on browser, you will look like in the following image: Table 5.1 71
5.4SENDING FILE OR IMAGE THROUGH FORM Steps To Upload An Image In Laravel Download Laravel 8 application Setup Database Create Model & Migration Create Routes Create Controller Create Blade View Create Image Directory Run Development Server Download Laravel 8 application In order to upload an image, first of all, we need to download and set up a laravel application. With composer installed on your computer, you can download a laravel project with the following command- composer create-project laravel/laravellaravel-image-upload PHP Setup Database Now the project is installed, you need to set up the database to store the data. You need to find out the .env file on your laravel project and set up the database name. Like this- DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel-image-upload DB_USERNAME=your_database_username DB_PASSWORD=your_database_password 72
PHP Create Model & Migration As we know, laravel follows the model-view-controller(MVC) pattern, we need to create a model. Models are objects that create relationships with a database table. You can create a model and migration file at a time with this php artisan command. php artisan make:modelPostimage -m PHP Here Postimage is the model name and -m command means creating a migration file. Tough, you can create them separately if you want. Now the migration file is created, you’ll find that file under the database/migrations folder and the file name is create_postimages_table.php. public function up() { Schema::create('postimages', function (Blueprint $table) { $table->id(); $table->string('image')->nullable(); $table->integer('created_by')->nullable(); $table->integer('updated_by')->nullable(); $table->timestamps(); }); } PHP You can add many fields you want to your database table. Now you need to migrate it to the database following this artisan command. php artisan migrate PHP Create Routes 73
Now we need to make routes. In laravel routes makes a relationship with your laravel controller. In your installed laravel project there is a file called web.php. Routes are written in that file. We need to create three routes for this project in this article to add, store, and view the image. Like this- //For adding an image Route::get('/add-image',[ImageUploadController::class,'addImage'])->name('images.add'); //For storing an image Route::post('/store-image',[ImageUploadController::class,'storeImage']) ->name('images.store'); //For showing an image Route::get('/view-image',[ImageUploadController::class,'viewImage'])->name('images.view'); PHP Create Controller After creating the routes, now we need a controller. The controller is a class where we handle requests, implement logic. In your laravel project, they are stored in the app/Http/Controllers directory. You can use the php artisan command to create a controller- php artisan make:controllerImageUploadController PHP In this example, we’re going to use the name ImageUploadController. Inside the controller, you’ll need three functions to add, store and view the data- <?php namespace App\\Http\\Controllers; use Illuminate\\Http\\Request; class ImageUploadController extends Controller { //Add image public function addImage(){ 74
return view('add_image'); } //Store image public function storeImage(){ /*Logic to store data*/ } //View image public function viewImage(){ return view('view_image'); } } PHP Here in the controller, addImage() and viewImage() functions returns blade files. Create Blade View Now we’ve our routes, controller and model, we need to create blade files to add and display images. For adding the image- //add_image.blade.php <div class=\"container\"> <form method=\"post\" action=\"{{ route('images.store') }}\" enctype=\"multipart/form-data\"> @csrf <div class=\"image\"> <label><h4>Add image</h4></label> <input type=\"file\" class=\"form-control\" required name=\"image\"> </div> <div class=\"post_button\"> 75
<button type=\"submit\" class=\"btnbtn-success\">Add</button> </div> </form> </div> PHP Here is the HTML code for adding data to a database through the form. Inside the for m, we have an input field that takes images as files and a submit button for submitting the data. When you are going to upload an image to a database in laravel remember you must have to use (enctype=”multipart/form-data”). Otherwise, it’ll not work. Our, method is “post” because we’re inserting data not getting. Be careful about that. And in the action, we’re going to define the route name where we put our data storing functionality. Create Images Directory When we upload an image to the database, it is the image path that is stored in the database. So, you need to create a folder under the public folder of your project. Like public/Image. After adding the image, now we’ve to store it. Here is the code for storing the data: /*You've to use the database model name from your App\\Models folder at the top of your controller page*/ use App\\Models\\Postimage; //Store image public function storeImage(Request $request){ $data= new Postimage(); if($request->file('image')){ $file= $request->file('image'); $filename= date('YmdHi').$file->getClientOriginalName(); $file-> move(public_path('public/Image'), $filename); $data['image']= $filename; 76
} $data->save(); return redirect()->route('images.view'); } PHP At first, The Request function returns the current request instance or obtains an input item from the user or you can say the form that we created in the “add_image” page. Then we call the Postimage model and store the result to a variable. Then we check a condition if our $request variable contains or does not, the specific file name in that case “image”. Then we concatenate with date function and GetClientOriginalName(). The function GetClientOriginalName() is used to retrieve the file’s original name at the time of upload in laravel. Then we move the filename to a path and the path will be stored in the database. After that, we just simply use the save() method to save the data to the database. Now the data is stored in the database, we can view the data to the user interface which is very easy. The code to view the images from the database is given below: //View post public function viewImage(){ $imageData= Postimage::all(); return view('Image.view_image', compact('imageData')); } PHP In this function, we’ve used all() function to get all the images from the database by using the “Postimage” model and passing the retrieved data into the “view_image” HTML page through a compact function. Here is the HTML code to view the images: <div class=\"container\"> <h3>View all image</h3><hr> <table class=\"table\"> <thead> 77
<tr> <th scope=\"col\">Image id</th> <th scope=\"col\">Image</th> </tr> </thead> <tbody> @foreach($imageData as $data) <tr> <td>{{$data->id}}</td> <td> <imgsrc=\"{{ url('public/Image/'.$data->image) }}\" style=\"height: 100px; width: 150px;\"> </td> </tr> @endforeach </tbody> </table> </div> PHP In the view page, we looped through the retrieved data by using @foreach loop statement and viewing the images. Run Development Server Now run the development server with the following PHP artisan command- php artisan serve PHP OUTPUT(Add image): 78
5.5SUMMARY Laravel is an MVC based PHP framework. In MVC architecture, V stands for View. The View is data that is going to be displayed to the user on their browser and the user can interact with it. It is simply an interface provided to the user for interaction. Laravel used a powerful templating engine called Blade. The extension for this file used here is filename.blade.php. Even though there are some directives and layout format used with a blade for taking advantage of this templating engine, still it allows us to write plain PHP in the view file. The main advantage of using Blade Templating Engine is that it provides template inheritance. With this, we can create a master layout page, which will become the base for other pages. So, the master page becomes the parent for all the child pages that we extend it to. • # Localization Localization is a way to translate a website or web app to different languages, including local currencies and units of measurement. Laravel provides an easy way to retrieve strings in 79
various languages by either using the __ helper function or the @lang Blade directive. Laravel also supports pluralization for languages that have different pluralization rules. • # Lumen Lumen is a free, API-focused microframework built by Laravel. Its incredible speed makes it one of the fastest microframeworks on the market, and because it is powered by Laravel's components, it is very easy to upgrade your Lumen application to a full Laravel application. 5.6KEYWORDS # Helper Methods Laravel provides a large number of global functions called helpers that make some common tasks easier to perform. The list includes methods for working with strings, arrays, objects, URLs and other miscellaneous methods. # Homestead Laravel Homestead is an official, pre-set Vagrant box that is pre-configured to serve Laravel applications and mirrors Laravel Forge almost exactly. # Horizon Horizon is a dashboard and configuration package for Laravel-powered Redis queues. Redis (RemoteDictionaryServer) is an in-memory key-value store used as a database, cache, and a message broker and Horizon makes it easy to monitor key metrics, for example, the health, performance, failures or history of any queue system in your Laravel application. # Localization Localization is a way to translate a website or web app to different languages, including local currencies and units of measurement. Laravel provides an easy way to retrieve strings in various languages by either using the __ helper function or the @lang Blade directive. Laravel also supports pluralization for languages that have different pluralization rules. 80
# Lumen Lumen is a free, API-focused microframework built by Laravel. Its incredible speed makes it one of the fastest microframeworks on the market, and because it is powered by Laravel's components, it is very easy to upgrade your Lumen application to a full Laravel application. # Nova Laravel Nova is an administration dashboard that is known for its great design and the ability to administer the app's database records using Eloquent, the Laravel ORM (Object-Relational Mapping). # Passport Laravel Passport is a package to authenticate APIs. Due to the unique nature of APIs as they typically use tokens to authenticate users and do not maintain session state between requests, authenticating APIs has not always been straightforward. Laravel Passport makes it possible by implementing an OAuth2 server inside your Laravel application. 5.7LEARNING ACTIVITY Write the steps for Creating Blade file in Laravel Describe how to send file or image through form 5.8UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is the latest Laravel version? 2.Define Composer. 3.What is the templating engine used in Laravel? 4.What are available databases supported by Laravel? 5.What is an artisan? 6.How to define environment variables in Laravel? Long Questions 1.Can we use Laravel for Full Stack Development (Frontend + Backend)? 81
2.How to put Laravel applications in maintenance mode? 3.What are the default route files in Laravel? 4.What are migrations in Laravel? 5.What are seeders in Laravel? 6.What are factories in Laravel? 7.How to implement soft delete in Laravel? 8.What are Models? B.Multiple Choice Questions 1. In the MVC framework, the letter 'C' stands for? A. Cookie B. Configuration C. command prompt D. Controller Ans : D 2. Cookie can be created by global cookie helper of Laravel. A. TRUE B. FALSE C. Can be true or false D. Can not say Ans : A 3. How many arguments cookie() method will take? A. 2 B. 4 C. 1 D. 3 Ans : D 4. Which method will automatically convert the array into appropriate json response? 82
A. application.json B. json C. routes D. test Ans : B 5. Which version introduces the concept of using Blade? A. Laravel 2.1 B. Laravel 3.1 C. Laravel 4.1 D. Laravel 5.1 Ans : D 5.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 83
UNIT - 6FLASH MESSAGES STRUCTURE 6.0.Learning Objectives 6.1.Introduction 6.2.what are flash-messages 6.3.explain different type of flash messages 6.4.Summary 6.5.Keywords 6.6.Learning Activity 6.7.Unit End Questions 6.8.References 6.0LEARNING OBJECTIVES After studying this unit, you will be able to know: what are flash-messages describe flash messages explain different type of flash messages 6.1 INTRODUCTION We will use laravel 8 flash message from controller. step by step explain laravel 8 flash message notification. this example will help you flash message laravel 8. you will do the following things for create flash message laravel 8. we will define various type of flash message notification like alert success, alert danger, alert info, alert warning messages in bootstrap laravel 8 projects. When you have success task on controller method then you can use success flash message, if you have any error task then you can use error flash message. Flash messages are required in laravel 8 application because that way we can give alter with what progress complete, error, warning etc. In this tutorial, I added several ways to give a 84
flash message like redirect with success message, redirect with an error message, redirect with a warning message and redirect with info message. In this example, we use a bootstrap flash alert layout that way it becomes good layout. 6.2WHAT ARE FLASH-MESSAGES A flash message allows you to create a message on one page and display it once on another page. To transfer a message from one page to another, you use the $_SESSION superglobal variable. For example, you can add a message to the $_SESSION on the first page: <?php session_start(); $_SESSION['flash_message'] = \"I'm a flash message'; Code language: PHP (php) Later, on another page, you can get the flash message from the $_SESSION variable and assign it to a variable. Then, you delete the message from the $_SESSION and display the message: <?php session_start(); if(isset($_SESSION['flash_message'])) { $message = $_SESSION['flash_message']; unset($_SESSION['flash_message']); echo $message; } Code language: PHP (php) This is a simple flash message example. 85
In practice, a flash message has a name (or an ID) for reference later. Also, a flash message has a type such as error, success, information, and warning. The message type allows you to make a specific style for the message In the following section, we’ll define a set of functions that do the following: Create a flash message with a name. Format a flash message. Display a flash message specified by a name. Display all the flash messages. Create a flash message First, define a constant as a key for all the flash messages: const FLASH = 'FLASH_MESSAGES'; Code language: PHP (php) Second, define constants that define the type of flash messages including error, information, warning, and success: const FLASH_ERROR = 'error'; const FLASH_WARNING = 'warning'; const FLASH_INFO = 'info'; const FLASH_SUCCESS = 'success'; Code language: PHP (php) Third, define a function that creates a flash message which has a name, a message, and a type: <?php /** * Create a flash message * * @param string $name 86
* @param string $message * @param string $type * @return void */ function create_flash_message(string $name, string $message, string $type): void { // remove existing message with the name if (isset($_SESSION[FLASH][$name])) { unset($_SESSION[FLASH][$name]); } // add the message to the session $_SESSION[FLASH][$name] = ['message' => $message, 'type' => $type]; } Code language: PHP (php) Format a flash message The following format_flash_message() function formats a flash message: /** * Format a flash message * * @param array $flash_message * @return string */ function format_flash_message(array $flash_message): string { return sprintf('<div class=\"alert alert-%s\">%s</div>', $flash_message['type'], 87
$flash_message['message'] ); } Code language: PHP (php) In this function, we use the following HTML with the class alert and alert-$type to format the message. The message type can be an error, info, warning, and success. The following example shows an error message: <div class=\"alert alert-error\"> This is an error! </div> Code language: HTML, XML (xml) Display a flash message To display a flash message by a name, you check if the message name exists in the $_SESSION[FLASH] variable. If so, you get the flash message in the $_SESSION['FLASH'], remove it from the $_SESSION['FLASH'], and display the flash message: <?php /** * Display a flash message * * @param string $name * @return void */ function display_flash_message(string $name): void { if (!isset($_SESSION[FLASH][$name])) { 88
return; } // get message from the session $flash_message = $_SESSION[FLASH][$name]; // delete the flash message unset($_SESSION[FLASH][$name]); // display the flash message echo format_flash_message($flash_message); } Code language: PHP (php) Display all flash messages The following function displays all flash messages from the $_SESSION['FLASH'] variable: <?php /** * Display all flash messages * * @return void */ function display_all_flash_messages(): void { if (!isset($_SESSION[FLASH])) { 89
return; } // get flash messages $flash_messages = $_SESSION[FLASH]; // remove all the flash messages unset($_SESSION[FLASH]); // show all flash messages foreach ($flash_messages as $flash_message) { echo format_flash_message($flash_message); } } Code language: PHP (php) Define the flash() function It would be more convenient if we define a single flash() function that: Create a flash message Display a flash message Display all flash messages The following flash() function reuses the above functions: <?php /** * Flash a message * * @param string $name * @param string $message 90
* @param string $type (error, warning, info, success) * @return void */ function flash(string $name = '', string $message = '', string $type = ''): void { if ($name !== '' && $message !== '' && $type !== '') { create_flash_message($name, $message, $type); } elseif ($name !== '' && $message === '' && $type === '') { display_flash_message($name); } elseif ($name === '' && $message === '' && $type === '') { display_all_flash_messages(); } } Code language: PHP (php) To create a flash message, you pass three arguments: name, message, and type to the flash() function like this: flash('greeting', 'Hi there', FLASH_INFO); Code language: PHP (php) To display a flash message by a name, you need to pass a name to the flash() function: flash('greeting'); Code language: PHP (php) To display all flash messages, you don’t pass any arguments to the flash() function: flash(); Code language: PHP (php) Put it all together The following places all the functions in the flash.php file: 91
<?php const FLASH = 'FLASH_MESSAGES'; const FLASH_ERROR = 'error'; const FLASH_WARNING = 'warning'; const FLASH_INFO = 'info'; const FLASH_SUCCESS = 'success'; /** * Create a flash message * * @param string $name * @param string $message * @param string $type * @return void */ function create_flash_message(string $name, string $message, string $type): void { // remove existing message with the name if (isset($_SESSION[FLASH][$name])) { unset($_SESSION[FLASH][$name]); } // add the message to the session $_SESSION[FLASH][$name] = ['message' => $message, 'type' => $type]; } /** 92
* Format a flash message * * @param array $flash_message * @return string */ function format_flash_message(array $flash_message): string { return sprintf('<div class=\"alert alert-%s\">%s</div>', $flash_message['type'], $flash_message['message'] ); } /** * Display a flash message * * @param string $name * @return void */ function display_flash_message(string $name): void { if (!isset($_SESSION[FLASH][$name])) { return; } // get message from the session 93
$flash_message = $_SESSION[FLASH][$name]; // delete the flash message unset($_SESSION[FLASH][$name]); // display the flash message echo format_flash_message($flash_message); } /** * Display all flash messages * * @return void */ function display_all_flash_messages(): void { if (!isset($_SESSION[FLASH])) { return; } // get flash messages $flash_messages = $_SESSION[FLASH]; // remove all the flash messages unset($_SESSION[FLASH]); // show all flash messages foreach ($flash_messages as $flash_message) { echo format_flash_message($flash_message); 94
} } /** * Flash a message * * @param string $name * @param string $message * @param string $type (error, warning, info, success) * @return void */ function flash(string $name = '', string $message = '', string $type = ''): void { if ($name !== '' && $message !== '' && $type !== '') { // create a flash message create_flash_message($name, $message, $type); } elseif ($name !== '' && $message === '' && $type === '') { // display a flash message display_flash_message($name); } elseif ($name === '' && $message === '' && $type === '') { // display all flash message display_all_flash_messages(); } } Code language: HTML, XML (xml) A flash message example 95
First, create the following directory and file structure: ├── inc | ├── flash.php | ├── footer.php | └── header.php ├── page1.php └── page2.php Code language: plaintext (plaintext) Second, place all the functions above in the flash.php file. Third, add the following code to the header.php file. The header.php links to the style.css file in the css folder: <!DOCTYPE html> <html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"https://www.phptutorial.net/app/css/style.css\"> <title>PHP Flash Message</title> </head> <body> Code language: HTML, XML (xml) Fourth, add the following HTML to the footer.php file: </body> </html> Code language: HTML, XML (xml) Fifth, create a flash message on the page1.php file by calling the flash() function: 96
<?php session_start(); require __DIR__ . '/inc/flash.php'; require __DIR__ . '/inc/header.php'; flash('greeting', 'Hi there', FLASH_INFO); echo '<a href=\"page2.php\" title=\"Go To Page 2\">Go To Page 2</a>'; require __DIR__ . '/inc/footer.php'; Code language: PHP (php) The page1.php file has a link to the page2.php. Finally, show the greeting message on the page2.php file by calling the flash() function and pass the name into it: <?php session_start(); require __DIR__ . '/inc/flash.php'; require __DIR__ . '/inc/header.php'; flash('greeting'); require __DIR__ . '/inc/footer.php'; Code language: PHP (php) If you open the page1.php page and click the link, you’ll see a message on the page2.php page. 97
6.2 EXPLAIN DIFFERENT TYPE OF FLASH MESSAGES Step 1: flash-message blade file In first step we will create new blade file flash-message.blade.php. In this file we will write code of bootstrap alert and check which messages come. There are following alert will added: 1)success 2)error 3)warning 4)info 5)validation error So, let's create flash-message.blade.php file and put bellow code on that file. resources/views/flash-message.blade.php @if ($message = Session::get('success')) <divclass=\"alert alert-success alert-block\"> <buttontype=\"button\" class=\"close\" data-dismiss=\"alert\">×</button> <strong>{{ $message }}</strong> </div> @endif @if ($message = Session::get('error')) <divclass=\"alert alert-danger alert-block\"> <buttontype=\"button\" class=\"close\" data-dismiss=\"alert\">×</button> <strong>{{ $message }}</strong> </div> @endif @if ($message = Session::get('warning')) 98
<divclass=\"alert alert-warning alert-block\"> <buttontype=\"button\" class=\"close\" data-dismiss=\"alert\">×</button> <strong>{{ $message }}</strong> </div> @endif @if ($message = Session::get('info')) <divclass=\"alert alert-info alert-block\"> <buttontype=\"button\" class=\"close\" data-dismiss=\"alert\">×</button> <strong>{{ $message }}</strong> </div> @endif @if ($errors->any()) <divclass=\"alert alert-danger\"> <buttontype=\"button\" class=\"close\" data-dismiss=\"alert\">×</button> Please check the form below for errors </div> @endif Step 2: use flash-message file in theme In this step we have to just include flash-message.blade.php file in your theme default file. So we can add file like this way: resources/views/layouts/app.blade.php <!DOCTYPE html> <htmllang=\"en\"> <head> <metacharset=\"utf-8\"> <metahttp-equiv=\"X-UA-Compatible\" content=\"IE=edge\"> 99
<metaname=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Styles --> <linkhref=\"/css/app.css\" rel=\"stylesheet\"> </head> <body> <divid=\"app\"> @include('flash-message') @yield('content') </div> <!-- Scripts --> <scriptsrc=\"/js/app.js\"></script> </body> </html> Step 3: use flash messages with redirect In this step we will learn how to give message when you redirect one by one: 1. Redirect with success message We can simple redirect route or redirect url or redirect back with success flash message, we can use in controller like this way: publicfunctioncreate(Request $request) { $this->validate($request,[ 'title' => 'required', 'details' => 'required' ]); $items = Item::create($request->all()); 100
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