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

["return back()->with('success','Item created successfully!'); } You can get layout of success flash message: 2. Redirect with error message We can simple redirect route or redirect url or redirect back with error flash message, we can use in controller like this way: publicfunctioncreate(Request $request) { return redirect()->route('home') ->with('error','You have no permission for this page!'); } You can get layout of error flash message: 3. Redirect with warning message 101","We can simple redirect route or redirect url or redirect back with warning flash message, we can use in controller like this way: publicfunctioncreate(Request $request) { return redirect()->route('home') ->with('warning','Don't Open this link); } You can get layout of warning flash message: 4. Redirect with info message We can simple redirect route or redirect url or redirect back with info 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()); return back()->with('info','You added new items, follow next step!'); 102","} You can get layout of info flash message: 5. Validation Error If you use laravel 5 validation then you will redirect back with errors automatically, At that time it will also generate error flash message. publicfunctioncreate(Request $request) { $this->validate($request,[ 'title' => 'required', 'details' => 'required' ]); ..... } You can get layout of error flash message: 103","This way you can simple implement flash message in your laravel 5 application. 6.3 SUMMARY \uf0b7 Where confidentiality is concerned, Flash SMS is the tool for your business. Not only does it trigger a prompt and attention-grabbing buzz but it also prevents private data from being stored on your customer's mobile \uf0b7 It might just be the saving grace when it comes to cybersecurity. As a business with Flash SMS in its arsenal, you can count on it to provide a fail-safe to your data protection. \uf0b7 We would shed light on flash message example in laravel after login. Possibly, this is required in almost every application, be it built with laravel or any other language or framework. \uf0b7 \uf0b7 Notification is an act of bringing something to the notice of the user. \uf0b7 Flash messages are foundational elements that bring something sudden to the user\u2019s attention. Alert messages are considered valuable from a user experience perspective, eventually being a programmer, we must have some skills about UX as well. Here are the possible list of alert, notification or flash messages: \uf0b7 Success Alert Message \uf0b7 Error Alert Message \uf0b7 Info Alert Message \uf0b7 Warning Alert Message \uf0b7 Validation Alert Message 6.4KEYWORDS # Service Provider Service providers are the heart of every Laravel application. These PHP classes contain and organize the relevant code in which the framework (and dependencies) bootstrap themselves. This includes binding classes, defining event listeners, and registering everything Laravel uses across multiple systems like middleware and routes. Service providers run at the beginning of each request; as the app boostraps Laravel runs through each service provider listend in app\/config\/app.php. Laravel comes with core service providers, but programmers can also build our own. # Socialite Laravel Socialite is a package that makes it easy to set up and use OAuth authentication in a Laravel application. 104","# Spark Spark is a software as a service (SaaS) application scaffolding. Using Spark in your application makes it easy to set up many common features of web applications such as subscriptions, invoices, team billing, user impersonation and many others. # Telescope Laravel Telescope is a debug assistant package that allows to debug and monitor various aspects of Laravel application, such as exceptions, notifications, scheduled tasks, variable dumps and others. # Tinker Tinker is a REPL (Read, Evaluate, Print, Loop) interactive tool that is included with every Laravel installation. Like Ruby's IRB, Tinker allows programmers to interact with their Laravel application and see the output of their actions. # Vagrant Vagrant is a software program used to manage and standardize development environments. It's a Ruby-based configuration layer that makes it easy to provision and control hypervisors (VMWare, Parallels, HyperV, etc.) with simple configuration scripts. # Valet Valet is a Laravel development environment for Mac minimalists. Using Homebrew and a few bundled applications, it serves your Laravel projects (and also those in WordPress, Statamic, and more) with almost no configuration on your end. # Vapor Laravel Vapor is an auto-scaling, serverless deployment platform developed specifically for Laravel, powered by AWS Lambda. # VueJS VueJS is a progressive frontend JavaScript framework for creating user interfaces, the view layer of the application. Its ease of use and a smooth learning curve means that Vue is a popular choice when choosing a front-end framework, so much so that Laravel provides an 105","easy way to install and setup Vue inside Laravel app by running php artisan uivue or php artisan uivue --auth. 6.5 LEARNING ACTIVITY How to display the message How do you flash a session message in laravel ? 6.6 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. What is flash messages 2. What is validation error 3. Explain the different types of flash messages 4. how to create flash messages in laravel Code Example 5. how to create fade out animation for session flash message Long Questions 1. create Custom Laravel 9 Flash Message Examples 2. How to verify laravel default flash messages in selenium? 3. How to add Flash messages 4. How Laravel Redirect Back with() Message 5. How to Display Session Flash Message in Laravel 8 B. Multiple Choice Questions 1. (ORM)means ----------l A. Object-Relational Mapping B. object random map C. Model View Controller D. command link interface A. Object-Relational Mapping 2. PHP frameworks typically follow the---------design pattern. This concept separates themanipulation of data from its presentation. A. Object-Relational Mapping 106","B. object random map C. Model View Controller D. command link interface C. Model View Controller 3. Early------- include PHPlib, Horde, and Pear. Most of the big names now launched in2005 or later. A. php framework B. ORM C. phplib D. command link interface C. phplib 4. Laravel,Symfony,CodeIgniter,Zend are the example of PHP frameworks. A. yes B. no C. can not say D. none of these A. yes 5. ----------- helps to developed web page using a PHP framework. A. Object-Relational Mapping B. object random map C. Model View Controller D. command link interface D. command link interface 6. Controller functions are used to access and update the database in php framework. A. yes B. no 107","C. can not say D. none of these A. yes 6.7REFERENCES 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 108","UNIT - 7PACKAGES STRUCTURE 7.0.Learning Objectives 7.1.Introduction to packages 7.2.Inbuilt packages 7.3.how to install packages 7.4.Summary 7.5.Keywords 7.6.Learning Activity 7.7.Unit End Questions 7.8.References 7.0 LEARNING OBJECTIVES After studying this unit, you will be able to: \uf0b7 Know about packages \uf0b7 Understand Inbuilt packages \uf0b7 Know how to install packages 7.1INTRODUCTION TO PACKAGES Packages are the primary way of adding functionality to Laravel. Packages might be anything from a great way to work with dates like Carbon or a package that allows you to associate files with Eloquent models like Spatie's Laravel Media Library. There are different types of packages. Some packages are stand-alone, meaning they work with any PHP framework. Carbon and PHPUnit are examples of stand-alone packages. Any of these packages may be used with Laravel by requiring them in your composer.json file. On the other hand, other packages are specifically intended for use with Laravel. These packages may have routes, controllers, views, and configuration specifically intended to enhance a Laravel application. This guide primarily covers the development of those packages that are Laravel specific. 109","7.2INBUILT PACKAGES Packages are one of the great ways to accelerate web application development and save your valuable time from the tedious task of writing the code from scratch. It can be freely reused anywhere in the code. Laravel has different-different kinds of packages; some of them standalone \u2013 Behat and Carbon are the best examples of such pages as they can be freely used with all the frameworks requesting COMPOSER.JS file. In layman\u2019s terms, Laravel Packages, also known as laravel plugins or bundles, are ready- to-use written scripts that you can plug and play into your application at your convenience. Laravel\u2019s packages deserve special attention because they minimize the code and improve the application\u2019s maintainability. Let\u2019s have a look at the best Laravel packages below, which you can use to optimize your application performance. 1. Spatie Roles and permissions form an important part of many web applications. Laravel historically had a lot of packages for them and improved the core code as well. Spatie Roles & Permission is one of there best permissions package. Advantages 1. Roles 2. Permissions 3. Direct Permissions 4. Middleware 5. Multiple Blade Directives 6. Artisan commands 2. Entrust 110","This package provides a flexible way to add Role-based Permissions to your Laravel 5 application. This package creates four tables: roles table for storing role records, permissions table for storing permission records, role_user table for storing one-to-many relations between roles and users, permission_role table for storing many-to-many relations between roles and permissions. You can create a role by writing the following code, $admin = new Role(); $admin->name = 'admin'; $admin->display_name = 'User Administrator'; \/\/ optional $admin->description = 'User is allowed to manage and edit other users'; \/\/ optional $admin->save(); Let\u2019s check how to assign the roles to the users, user = User::where('username', '=', 'michele')->first(); $user->attachRole($admin); Now, you must give permissions to these roles: $createPost = new Permission(); $createPost->name = 'create-post'; $createPost->display_name = 'Create Posts'; $createPost->description = 'create new blog posts'; $createPost->save(); $admin->attachPermission($createPost); 3. Laravel Debugbar 111","Laravel Debugbar is one of those best Laravel packages that help users add a developer toolbar to their application(s). This package is mainly used for debugging purposes. There are a lot of options available in Debugbar. It will help you to show all the queries that your application offers \u2013 everything related to the route \u2013 that you have called will show all the rendered templates, as well as all the parameters that you have passed. You can add messages using the Fa\u00e7ade (when added), and it will show under the \u2018Messages\u2019 tab in Laravel Debugbar. Debugbar::info($object); Debugbar::error('Error!'); Debugbar::warning('Watch out\u2026'); Debugbar::addMessage('Another message', 'mylabel') 4. Laravel User Verification This package allows you to handle user verification and validates email(s). It generates and stores a verification token for the registered user, sends or queue an email with the verification token link, handles the token verification, sets the user as verified. This package also provides functionality, i.e verified route middleware. public function register(Request $request) 112","{ $this->validator($request->all())->validate(); $user = $this->create($request->all()); event(new Registered($user)); $this->guard()->login($user); UserVerification::generate($user); UserVerification::send($user, 'My Custom E-mail Subject'); return $this->registered($request, $user) ?: redirect($this->redirectPath()); } 5. Socialite Socialite offers a simple and easy way to handle OAuth authentication. It allows the users to login via some of the most popular social networks and services including Facebook, Twitter, Google, GitHub, and BitBucket. $user = Socialite::driver('github')->user(); \/\/ OAuth Two Providers $token = $user->token; $refreshToken = $user->refreshToken; \/\/ not always provided $expiresIn = $user->expiresIn; \/\/ All Providers $user->getId(); $user->getName() $user->getEmail(); $user->getAvatar(); 6.Laravel Mix 113","Formerly known as Laravel Elixir, Laravel Mix provides a clean and rich Application Programming Interface (API) for defining webpack-build steps for your project. It is the most powerful asset compilation tool available for Laravel today. mix.js('resources\/assets\/js\/app.js', 'public\/js') .sass('resources\/assets\/sass\/app.scss', 'public\/css'); 7. Eloquent-Sluggable Slugging is the process of creating a simplified, URL-friendly version of a string by converting it to one case and removing spaces, accented letters, ampersands, etc. With Eloquent-Sluggable, you can easily create slugs for all the Eloquent models in your project. class Post extends Eloquent { use Sluggable; protected $fillable = ['title']; public function sluggable() { return [ 'slug' => [ 'source' => ['title'] ] ]; } 114","} $post = new Post([ 'title' => 'My Awesome Blog Post', ]); \/\/ $post->slug is \\\"my-awesome-blog-post 8. Migration Generator Migration generator is a Laravel package that you can use to generate migrations from an existing database, including indexes and foreign keys. When you run the following command, you can create migrations for all the tables in your database. php artisan migrate:generate You can also choose only certain tables that you want to migrate: php artisan migrate:generate table1,table2 9.Laravel Backup This Laravel package creates a backup of all your files within an application. It creates a zip file that contains all files in the directories you specify along with a dump of your database. You can store a backup on any file system. To create a backup, all you need to do is to run the following command: php artisan backup:run 10.No Captcha No Captcha is a package for implementing Google reCaptcha validation and protecting forms from spamming. First, you need to obtain a free API key from reCaptcha. NoCaptcha::shouldReceive('verifyResponse') 115","->once() ->andReturn(true); $response = $this->json('POST', '\/register', [ 'g-recaptcha-response' => '1', 'name' => 'Pardeep', 'email' => '[email protected]', 'password' => '123456', 'password_confirmation' => '123456', ]); 11.Laravel GraphQL GraphQL is a data query language that provides an alternative to traditional REST architecture. Besides, GraphQL you can also read more about the laravel forge alternative. Developers define the structure of the data required and get the same structure from the server. This package will help you set up and use GraphQL in your Laravel apps. Laravel Admin Panel Generator There are two big groups of admin panel generators: visual builders and console-based. The choice depends on your preferences, whether you like to use GUI or type Artisan commands with parameters. Also, an important term to remember here is a CRUD\u2014this abbreviation stands for \u201cCreate, Read, Update, Delete\u201d\u2014these core operations are the building blocks of all admin panels. 12. Voyager: The Missing Laravel Admin Voyager stands out with a polished and professional interface, but the main point is that it just works. Clear usage instructions, user-friendly front-end theme, no obvious bugs or unfinished parts\u2014that\u2019s Voyager for you. Even the icons like the captain\u2019s picture make it look nice overall. Voyager offers interesting features, such as dummy-data, media manager, etc. 13.LaraAdmin: Admin Panel + CRM 116","After installing and logging into your admin panel, this package allows you to visually create modules, which represent your CRUDs. 14. Orchid RAD platform works fittingly well for building a business application using the Laravel framework. It can act as the core base for web applications or can perform the functions of CMS, CMF, or admin panel for your website. Laravel Ecommerce Packages 15 Bagisto Bagisto is an open-source Laravel eCommerce package that has managed to catch the eyes of the Laravel community, in a very short period. It offers out-of-the-box Laravel user management, multi-warehouse inventory management options, and much more. Also, the Laravel CMS package is bundled with built-in user-friendly admin panel navigation, offers functionalities like Multi-Currency, Localization, Access Control Level, Multi-Channel, Payment integration, and much more. 16 AvoRed You can easily customize the Open Source Laravel Shopping Cart as per your needs. It offers a mobile-friendly interface layout by default, that is why also called one of the best Laravel SEO packages. The platform allows you to create product entities like category, attributes, etc. with efficient order management capabilities to keep track of your order, customer information and inventory management, etc. 17. Laravel Telescope Laravel Telescope is an elegant PHP debugger for the Laravel framework. It provides vivid insights into the requests coming onto your application, exceptions, log entries, database queries, queued jobs, mail, notifications, cache operations, scheduled tasks, variable dumps, and much more. The telescope makes a wonderful companion to your local Laravel development environment. Scalable, Fast & Secure Managed Laravel Hosting 117","Laravel SEO Packages Laravel Meta Manager By using Laravel Meta Manager, you can optimize your website\u2019s SEO, thereby helping your website rank higher on the first page of the search engine. It emphasizes on the application\u2019s Meta tags, helps you to correct them according to the best practices of SEO. The package comes with recommended Meta tags including Standard SEO, Dublin Core, Google Plus, Facebook Open Graph, and many others. SEOTools SEOTools gives you the ease to optimize your Laravel SEO according to the latest techniques of the search engine rankings. Both Laravel 5+ and Lumen frameworks support SEOTools. It offers great website optimization features. The package is very easy to integrate within the projects, as it has a user-friendly interface that helps even beginners to quickly get started with it. It provides specific techniques to set titles and Meta tags both for Twitter and Open Graph. AutoMeta AutoMeta is an excellent SEO optimization tool for Laravel that helps developers with some common SEO techniques. It is one of the top SEO tools for Laravel that provides easy management of the website\u2019s meta tags. The package also helps to fix some common SEO bugs in the application and make a code simple to crawl for search engine bots. Laravel Seoable Laravel Seoable is one of the most used SEO packages for Laravel projects. It offers adequate SEO techniques that fine-tune the Laravel apps for search engine rankings. The package defines some core Laravel functions according to the best practices of SEO, such as mapping Eloquent attributes to SEO Meta tags, setting custom templates for page title\/description, defining custom SEO data for application models, and many others. Laravel-seo Laravel-seo is another handy SEO package that allows you to insert, manage, and delete website Meta tags with ease. By using this package, you can also insert structured data into the Laravel projects and can manage some of the most used SEO Meta tags like Facebook Open Graph, Dublin Core, and others effortlessly. 118","7.3HOW TO INSTALL PACKAGES To avoid a general Hello world example, let\u2019s take a more practical idea: say\u2026 a package which shows current time in various timezones. Still very simple, but somewhat useful. Ok, here we go. 1. Fresh Laravel 5.6 installation At the time of writing let\u2019s download latest build to start fresh I will use this one: composer create-project laravel\/laravel --prefer-dist . 2. Package folder and name Let\u2019s create a folder \/packages in our root, and we will put our package there. Now, every package has to have a name, which actually consists of two parts: [VENDOR or CREATOR] \/ [PACKAGE NAME]. For example, Laravel itself has a full name of laravel\/laravel (same vendor), and one of the most popular packages Jeffrey Way\u2019s Generators has a name of way\/generators. So logic is simple: package has a creator name and its own name. So let\u2019s call our package laraveldaily\/timezones \u2013 then we need to create a folder inside our \/packages: Then inside of it we need to create another folder called \/src: Ok, folder structure ready, now let\u2019s give our package an \u201cofficial description\u201d with Composer: 3. Composer.json file for the package 119","Every package needs to have composer.json file, which contains not only potential dependancies, but also information about the package itself. So we go to our timezones folder and run this command: composer init You will get a guide of questions to fill-in your future composer.json file. If you answer then one by one (don\u2019t worry if you make any mistake or skip something, you can add it later), you will end up with something like this generated: { \\\"name\\\": \\\"laraveldaily\/timezones\\\", \\\"description\\\": \\\"Demo-package to show time\\\", \\\"authors\\\": [ { \\\"name\\\": \\\"Laravel Daily\\\", \\\"email\\\": \\\"[email protected]\\\" } ], \\\"minimum-stability\\\": \\\"dev\\\", \\\"require\\\": {} } That\u2019s it \u2013 in our case, no external requirements, nothing fancy. But that\u2019s enough. 4. Loading package via main composer.json Now, let\u2019s make our package \u201cvisible\u201d to main Laravel structure, and assign alias to it, we do that by adding this line to main composer.json: \\\"repositories\\\": [ { \\\"type\\\": \\\"path\\\", 120","\\\"url\\\": \\\"packages\/laraveldaily\/timezones\\\", \\\"options\\\": { \\\"symlink\\\": true } } ], \\\"require\\\": { \/\/ ... \\\"laraveldaily\/timezones\\\": \\\"dev-master\\\" }, And then we run this command from main folder: composer update 5. Creating a Service Provider This might sound a little complicated at first, if you want to dig deeper into what a Service Essentially, Service Provider is a Class which would contain main information about package \u2013 what Controllers does it use, what Routes file or Views to load etc. You can look at it as a set of rules for the package. So, how do we create it? There\u2019s an Artisan command to create a service provider: php artisan make:providerTimezonesServiceProvider It will generate a file called TimezonesServiceProvider.php in folder app\/Providers \u2013 then we should move that file to our folder \/packages\/laraveldaily\/timezones\/src. After that don\u2019t forget to change the namespace of the Provider class \u2013 it should be the same as we specified in main composer.json file \u2013 in our case, Laraveldaily\\\\Timezones: 121","As you can see, we have a generated class with two methods: boot() and register(). A little later we will fill them in with actions, but now \u2013 let\u2019s register our Service Provider. From Laravel 5.5 there\u2019s a great function called auto-discovery, so here\u2019s what we need to add into our package\u2019s composer.json: \\\"extra\\\": { \\\"laravel\\\": { \\\"providers\\\": [ \\\"Laraveldaily\\\\\\\\Timezones\\\\\\\\TimezonesServiceProvider\\\" ] } } Cool, we\u2019re done for now with Service Provider, let\u2019s move on to Controllers. 6. Create a Controller Our example package will have only one Controller, let\u2019s call it TimezonesController \u2013 and we create it in the same src folder of our package. 122","Controller will have only one method index($timezone) which will just show time in specified timezone \u2013 we use Carbon library for that (you don\u2019t need to install it, it\u2019s already within Laravel). So, here\u2019s our packages\\\\laraveldaily\\\\timezones\\\\src\\\\TimezonesController.php: namespace Laraveldaily\\\\Timezones; use App\\\\Http\\\\Controllers\\\\Controller; use Carbon\\\\Carbon; class TimezonesController extends Controller { public function index($timezone) { echo Carbon::now($timezone)->toDateTimeString(); } } Again, don\u2019t forget correct namespace and adding use App\\\\Http\\\\Controllers\\\\Controller on top. 7. Create our Routes file You are probably familiar with usual routes\/web.php file, so we have to create our own similar file in our package folder. Again, it will be a simple one-liner: packages\\\\laraveldaily\\\\timezones\\\\src\\\\routes\\\\web.php: Route::get('timezones\/{timezone}', 'laraveldaily\\\\timezones\\\\TimezonesController@index'); Now, how does Laravel know about this routes\/web.php file and our Controller? This is where our Service Provider comes in: we add these lines to its method register(): class TimezonesServiceProvider extends ServiceProvider { 123","public function register() { include __DIR__.'\/routes\/web.php'; $this->app->make('Laraveldaily\\\\Timezones\\\\TimezonesController'); } } 8. That\u2019s it \u2013 load URL in the browser! Now, here I immediately think of two potential problems: \uf0b7 What if user specifies a timezone with slash symbol (\/) \u2013 it would count as URL \uf0b7 Maybe we should have a default timezone, if none specified? For that, let\u2019s make an assumption that user would add timezones with dash \u2013 instead of slash \/ and we str_replace it. Also, we make that parameter optional and default to whatever timezone is in our config\/app.php file. packages\\\\laraveldaily\\\\timezones\\\\routes\\\\web.php \u2013 added question mark: Route::get('timezones\/{timezone?}', 'laraveldaily\\\\timezones\\\\TimezonesController@index'); packages\\\\laraveldaily\\\\timezones\\\\TimezonesController.php: public function index($timezone = NULL) { $time = ($timezone) ? Carbon::now(str_replace('-', '\/', $timezone)) 124",": Carbon::now(); echo $time->toDateTimeString(); } Now, we can load URLs like \/timezones or \/timezones\/Europe-London. Ok, so we have the basics of our package, and it works! Yay! But there are some additional things you might want to add. 9. What about the Views? Of course, you wouldn\u2019t just echo into the browser like that in real world \u2013 there should be at least some basic HTML template, which should be stored in a View file. Let\u2019s do exactly that \u2013 we need to create a folder \/src\/views and then put a View file in it. Let\u2019s copy a default Laravel 5 welcome.blade.php with adding just one variable $current_time. src\/views\/time.blade.php: <title>Laravel Timezones<\/title> <link href=\\\"https:\/\/fonts.googleapis.com\/css?family=Lato:100\\\" rel=\\\"stylesheet\\\" type=\\\"text\/css\\\"> <style> html, body { height: 100%; } body { margin: 0; padding: 0; width: 100%; display: table; font-weight: 100; font-family: 'Lato'; } 125",".container { text-align: center; display: table-cell; vertical-align: middle; } .content { text-align: center; display: inline-block; } .title { font-size: 96px; } <\/style> <div class=\\\"container\\\"> <div class=\\\"content\\\"> <div class=\\\"title\\\">{{ $current_time }}<\/div> <\/div> <\/div> Now, let\u2019s return to our Service Provider and this time we will use boot() method by adding a command, where to load our views from. The second parameter is our Namespace which we will use in the next step. class TimezonesServiceProvider extends ServiceProvider { public function boot() { $this->loadViewsFrom(__DIR__.'\/views', 'timezones'); } 126","Next thing \u2013 we need to change our Controller to load this view with a parameter. Now, notice that we are loading the view with the specific namespace of our package that we just specified in Service Provider. class TimezonesController extends Controller { public function index($timezone = NULL) { $current_time = ($timezone) ? Carbon::now(str_replace('-', '\/', $timezone)) : Carbon::now(); return view('timezones::time', compact('current_time')); } } And, here we go \u2013 reload the browser: So, this is how we use and load the views in the package. 10. Publishing the Views 127","And the last step \u2013 what if we want user of our package to customize that view himself? That\u2019s a pretty common scenario \u2013 we provide a basic template, but then user wants it to look as his app, not ours. But they wouldn\u2019t go to our package folder and edit views directly \u2013 that would ruin all future updates process. That means we should copy our views into Laravel folder resources\/views. To do that, we add this line to Service Provider\u2019s boot() method: $this->publishes([ __DIR__.'\/views' =>base_path('resources\/views\/laraveldaily\/timezones'), ]); As you can see, we are copying not to views, but deeper \u2013 to stay with our structure. And then, to perform actual copying, user should publish our views, with Artisan command: php artisan vendor:publish This is the result \u2013 we now have views in both our package folder and Laravel folder: Bonus: publishing your package to Packagist 128","The last last thing is if you want to show your package to the world, so that other people would add it to their composer.json file. I won\u2019t provide detailed instructions on this, cause it kinda goes outside Laravel topic, but here are basic steps: 1. You form your package as a repository and upload it to GitHub; 2. You register on Packagist.org; 3. You make sure that your composer.json contains all necessary information; 4. You submit a link to your GitHub repository to Packagist \u2013 and then \u2013 BOOM! \u2013 magic happens! 5. For all detailed information about composer.json fields, package versioning and other topics \u2013 see Packagist documentation. 7.4SUMMARY \uf0b7 Here is the basic way to create a package. Of course, you can grow it much bigger with Models, Assets and your own sub-folder structure, but I will leave it for you to play with. \uf0b7 And if you create your own package with the help of this tutorial, don\u2019t forget to give the link in the comments \u2013 tell the world about your achievement! 7.5KEYWORDS \uf0b7 Accessor A method defined on an Eloquent model that customizes how a given property will be returned. Accessors make it possible to define that getting a given property from a model will return a different (or, more likely, differently formatted) value than what is stored in the database for that property. \uf0b7 ActiveRecord A common database ORM pattern, and also the pattern that Laravel\u2019s 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. \uf0b7 API Technically application programming interface, but most commonly used to refer to a series of endpoints (and instructions on how to use them) that can be used to make HTTP-based calls to read and modify data from outside of a system. Sometimes, the term API is also used to describe the set of interfaces, or affordances, any given package or library or class exposes to its consumers. 129","\uf0b7 Application test Often called acceptance or functional tests, application tests test the entire behavior ofthe application, usually at an outer boundary, by employing something like a DOM crawler\u2014which is exactly what Laravel\u2019s application test suite offers. \uf0b7 Argument (Artisan) Arguments are parameters that can be passed to Artisan console commands. Arguments aren\u2019t prefaced with -- or followed by = 7.6LEARNING ACTIVITY List all Inbuilt packages Write steps for how to install packages 7.7UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. State the difference between get and post method. 2. List default packages of Laravel 5.6. 3. What is service container in Laravel? 4. How can you enable query log in Laravel? Long Questions 1. Explain the concept of events in Laravel. 2. Explain dependency injection and their types. 3. What are the advantages of using Laravel? 4. Explain validation concept in Laravel. 5. What does ORM stand for? 6. How can you reduce memory usage in Laravel? B. Multiple Choice Questions 1. Calling a non-static method statically generates _____ . A. an E_STRICT level warning B. an E_DEPRECATED level warning C. an E_RECOVERABLE_ERROR level warning D. no warning Answer :A 2. Which of those is not magic method? A. __autoload 130","B. __clone C. __sleep D. __toint Answer :D 3. What function creates a cookie? A. create_cookie() B. set_cookie() C. setcookie() D. None of the above Answer :C 4. What function split an array into chunks? A. array_chunk() B. array_split() C. array_split_chunk D. array_chunks() Answer :A 5. What is input sanitization? A. Secure user input B. Converting input into a format that PHP supports C. Removing or cleaning potentially malicious user input. D. All of the above Answer :C 6. If class implementing the interface does not use exact same method signatures as are defined in the interface. Will show A. No Error B. Fatal Error 131","C. Warning Error D. Notice Error Answer :B 7.8REFERENCES 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 132","UNIT - 8LOOPING STATEMENTS IN LARAVEL STRUCTURE 8.0.Learning Objectives 8.1.Introduction 8.2.while loop 8.3.do while 8.4.for loop 8.5.foreach loop 8.6.Summary 8.7.Keywords 8.8.Learning Activity 8.9.Unit End Questions 8.10. References 8.0 LEARNING OBJECTIVES After studying this unit, you will be able to: \uf0b7 Understand while loop \uf0b7 Use do while \uf0b7 Use and implement for loop \uf0b7 Use and implement foreach loop 8.1INTRODUCTION In addition to template inheritance and displaying data, Blade also provides convenient shortcuts for common PHP control structures, such as conditional statements and loops. These shortcuts provide a very clean, terse way of working with PHP control structures, while also remaining familiar to their PHP counterparts. Blade provides convenient syntax for common PHP control structures. Each of the control structures begins with @[structure] and ends with @[endstructure]. Notice that within the tags, we are just typing normal HTML and including variables with the Blade syntax. 133","8.2WHILE LOOP It has the following syntax <?php while (condition){ block of code to be executed; } ?> HERE, \uf0b7 \u201cwhile(\u2026){\u2026}\u201d is the while loop block code \uf0b7 \u201ccondition\u201d is the condition to be evaluated by the while loop \uf0b7 \u201cblock of code\u2026\u201d is the code to be executed if the condition gets satisfied How it works The flow chart shown below illustrates how the while\u2026 loop works Practical example The code below uses the while\u2026 loop to print numbers 1 to 5. <?php 134","$i = 0; while ($i< 5){ echo $i + 1 . \\\"<br>\\\"; $i++; } ?> Output: 1 2 3 4 5 8.3DO WHILE The difference between While\u2026 loop and Do\u2026 while loop is do\u2026 while is executed at-least once before the condition is evaluated. Let\u2019s now look at the basic syntax of a do\u2026 while loop <?php do{ block of code to be executed } ?> while(condition); HERE, \uf0b7 \u201cdo{\u2026} while(\u2026)\u201d is the do\u2026 while loop block code \uf0b7 \u201ccondition\u201d is the condition to be evaluated by the while loop \uf0b7 \u201cblock of code\u2026\u201d is the code that is executed at least once by the do\u2026 while loop 135","How it works The flow chart shown below illustrates how the while\u2026 loop works Practical example We are now going to modify the while\u2026 loop example and implement it using the do\u2026 while loop and set the counter initial value to 9. The code below implements the above modified example <?php $i = 9; do{ echo \\\"$i is\\\".\\\" <br>\\\"; } 136","while($i< 9); ?> The above code outputs: 9 8.4FOR LOOP Let\u2019s now look at them separately. For loop It has the following basic syntax <?php for (initialize; condition; increment){ \/\/code to be executed } ?> HERE, \uf0b7 \u201cfor\u2026{\u2026}\u201d is the loop block \uf0b7 \u201cinitialize\u201d usually an integer; it is used to set the counter\u2019s initial value. \uf0b7 \u201ccondition\u201d the condition that is evaluated for each php execution. If it evaluates to true, then execution of the for\u2026 loop continues. If it evaluates to false, the execution of the for\u2026 loop is terminated. \uf0b7 \u201cincrement\u201d is used to increment the initial value of counter integer. How it works The flowchart shown below illustrates how for loop in php works 137","How to code The code below uses the \u201cfor\u2026 loop\u201d to print values of multiplying 10 by 0 through to 10 <?php for ($i = 0; $i< 10; $i++){ $product = 10 * $i; echo \\\"The product of 10 * $i is $product <br\/>\\\"; } ?> Output: The product of 10 x 0 is 0 The product of 10 x 1 is 10 The product of 10 x 2 is 20 The product of 10 x 3 is 30 The product of 10 x 4 is 40 138","The product of 10 x 5 is 50 The product of 10 x 6 is 60 The product of 10 x 7 is 70 The product of 10 x 8 is 80 The product of 10 x 9 is 90 8.5FOREACH LOOP The php foreach loop is used to iterate through array values. It has the following basic syntax <?php foreach($array_variable as $array_values){ block of code to be executed } ?> HERE, \uf0b7 \u201cforeach(\u2026){\u2026}\u201d is the foreach php loop block code \uf0b7 \u201c$array_data\u201d is the array variable to be looped through \uf0b7 \u201c$array_value \u201c is the temporary variable that holds the current array item values. \uf0b7 \u201cblock of code\u2026\u201d is the piece of code that operates on the array values How it works The flowchart shown below illustrates how the for\u2026 each\u2026 loop works 139","Practical examples The code below uses for\u2026 each loop to read and print the elements of an array. <?php $animals_list = array(\\\"Lion\\\",\\\"Wolf\\\",\\\"Dog\\\",\\\"Leopard\\\",\\\"Tiger\\\"); foreach($animals_list as $array_values){ echo $array_values . \\\"<br>\\\"; } 140","?> Output: Lion Wolf Dog Leopard Tiger Let\u2019s look at another example that loops through an associative array. An associative array uses alphanumeric words for access keys. <?php $persons = array(\\\"Mary\\\" => \\\"Female\\\", \\\"John\\\" => \\\"Male\\\", \\\"Mirriam\\\" => \\\"Female\\\"); foreach($persons as $key => $value){ echo \\\"$key is $value\\\".\\\"<br>\\\"; } ?> The names have been used as array keys and gender as the values. Output: Mary is Female John is Male Mirriam is Female 141","8.6SUMMARY \uf0b7 The for\u2026 loop is used to execute a block of a specified number of times \uf0b7 The foreach\u2026 loop is used to loop through arrays \uf0b7 While\u2026 loop is used to execute a block of code as long as the set condition is made to be false \uf0b7 The do\u2026 while loop is used to execute the block of code at least once then the rest of the execution is dependent on the evaluation of the set condition 8.7KEYWORDS \uf0b7 If Statements You may construct if statements using the @if, @elseif, @else, and @endif directives. These directives function identically to their PHP counterparts: @if (count($records) === 1) I have one record! @elseif (count($records) > 1) I have multiple records! @else I don't have any records! @endif For convenience, Blade also provides an @unless directive: 142","@unless (Auth::check()) You are not signed in. @endunless \uf0b7 Loops In addition to conditional statements, Blade provides simple directives for working with PHP's loop structures. Again, each of these directives functions identically to their PHP counterparts: @for ($i = 0; $i< 10; $i++) The current value is {{ $i }} @endfor @foreach ($users as $user) <p>This is user {{ $user->id }}<\/p> @endforeach @forelse ($users as $user) <li>{{ $user->name }}<\/li> @empty <p>No users<\/p> @endforelse @while (true) <p>I'm looping forever.<\/p> @endwhile 143","When looping, you may use the loop variable to gain valuable information about the loop, such as whether you are in the first or last iteration through the loop. When using loops you may also end the loop or skip the current iteration: @foreach ($users as $user) @if ($user->type == 1) @continue @endif <li>{{ $user->name }}<\/li> @if ($user->number == 5) @break @endif @endforeach You may also include the condition with the directive declaration in one line: @foreach ($users as $user) @continue($user->type == 1) <li>{{ $user->name }}<\/li> 144","@break($user->number == 5) @endforeach \uf0b7 The Loop Variable When looping, a $loop variable will be available inside of your loop. This variable provides access to some useful bits of information such as the current loop index and whether this is the first or last iteration through the loop: @foreach ($users as $user) @if ($loop->first) This is the first iteration. @endif @if ($loop->last) This is the last iteration. @endif <p>This is user {{ $user->id }}<\/p> @endforeach If you are in a nested loop, you may access the parent loop's $loop variable via the parent property: @foreach ($users as $user) @foreach ($user->posts as $post) @if ($loop->parent->first) This is first iteration of the parent loop. 145","@endif @endforeach @endforeach The $loop variable also contains a variety of other useful properties: \uf0b7 Property Description $loop->index The index of the current loop iteration (starts at 0). $loop->iteration The current loop iteration (starts at 1). $loop->remaining The iteration remaining in the loop. $loop->count The total number of items in the array being iterated. $loop->first Whether this is the first iteration through the loop. $loop->last Whether this is the last iteration through the loop. $loop->depth The nesting level of the current loop. $loop->parent When in a nested loop, the parent's loop variable. Comments Blade also allows you to define comments in your views. However, unlike HTML comments, Blade comments are not included in the HTML returned by your application: {{-- This comment will not be present in the rendered HTML --}} PHP In some situations, it's useful to embed PHP code into your views. You can use the Blade @php directive to execute a block of plain PHP within your template: @php \/\/ 146","@endphp 8.8LEARNING ACTIVITY 1. Create a chess board using for loop 2. How to break a for each loop in laravel blade 8.9UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Write the syntax of while loop 2. Write the syntax of do while 3. Write the syntax of for loop 4. Write the syntax of foreach loop Long Questions 1. What is :: In Laravel? 2. What is blade in Laravel? 3. What is @yield used for in Laravel? 4. What is the use of foreach loop? 5. How to write the nested loop of laravel B. Multiple Choice Questions 1. PHP supports ____ types of looping techniques? A. 2 B. 3 C. 4 D. 5 Ans : C 2. How many main parameter are used in for loop? A. 2 B. 3 147","C. 4 D. 1 Ans : B 3. do-while loop is an _____ control loop ? A. exit B. exist C. easy D. entry Ans : A 4. while loop is an _____ control loop ? A. exit B. exist C. easy D. entry Ans : D 5. foreach loop is used to iterate over ____? A. number B. object C. function D. array View Answer Ans : D 8.10 REFERENCES Reference Books: - 1. Professional WordPress: Design and Development by Brad Williams 148","Step-By-Step WordPress for Beginners: How to Build a Beautiful Website on Your Own Domain from Scratch by Mike Taylor UNIT - 9CONDITIONAL STATEMENTS IN LARAVEL STRUCTURE 9.0.Learning Objectives 9.1.Introduction 9.2.if statement 9.3.if-else 9.4.Validation in Laravel 9.5.redirection in laravel, 9.6.Miration and seeding in laravel, 9.7.artisan commands in laravel 9.8.Summary 9.9.Keywords 9.10. Learning Activity 9.11. Unit End Questions 9.12. References 9 LEARNING OBJECTIVES After studying this unit, you will be able to: \uf0b7 Understand if statement \uf0b7 Use if-else \uf0b7 Learn about Validation in Laravel \uf0b7 Lean redirection in laravel, \uf0b7 Understand Miration and seeding in laravel, \uf0b7 Use artisan commands in laravel 9.1INTRODUCTION Code execution can be grouped into categories as shown below \uf0b7 Sequential \u2013 this one involves executing all the codes in the order in which they have been written. 149","\uf0b7 Decision \u2013 this one involves making a choice given a number of options. The code executed depends on the value of the condition. A control structure is a block of code that decides the execution path of a program depending on the value of the set condition. 9.2IF STATEMENT Here i give you full example of blade if condition in laravel. Example: if...endif Condition In this example, I will use if condition in blade file. Syntax @if (condition) \/\/ Statements inside body of if @endif Example @if (count($type) === 1) I have one record! @endif 9.3IF-ELSE If\u2026 then\u2026 else is the simplest control structure. It evaluates the conditions using Boolean logic When to use if\u2026 then\u2026 else \uf0b7 You have a block of code that should be executed only if a certain condition is true \uf0b7 You have two options, and you have to select one. \uf0b7 If\u2026 then\u2026 else if\u2026 is used when you have to select more than two options and you have to select one or more Syntax The syntax for if\u2026 then\u2026 else is; <?php 150"]


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