Preview only show first 10 pages with watermark. For full document please download
Begining Laravel
Excellent book to learn laravel
-
Rating
-
Date
September 2017 -
Size
2.2MB -
Views
3,405 -
Categories
Transcript
Beginning Laravel A beginner’s guide to application development with Laravel 5.3 — Sanjib Sinha Beginning Laravel A beginner’s guide to application development with Laravel 5.3 Sanjib Sinha Beginning Laravel Sanjib Sinha Howrah, West Bengal, India ISBN-13 (pbk): 978-1-4842-2537-0 DOI 10.1007/978-1-4842-2538-7 ISBN-13 (electronic): 978-1-4842-2538-7 Library of Congress Control Number: 2016962198 Copyright © 2017 by Sanjib Sinha This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights. While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein. Managing Director: Welmoed Spahr Lead Editor: Nikhil Karkal Technical Reviewer: Yogesh Sharma & Gaurav Yadav Editorial Board: Steve Anglin, Pramila Balan, Laura Berendson, Aaron Black, Louise Corrigan, Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, Nikhil Karkal, James Markham, Susan McDermott, Matthew Moodie, Natalie Pao, Gwenan Spearing Coordinating Editor: Prachi Mehta Copy Editor: Brendan Frost Compositor: SPi Global Indexer: SPi Global Artist: SPi Global Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation. For information on translations, please e-mail [email protected], or visit www.apress.com. Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales. Any source code or other supplementary materials referenced by the author in this text are available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/. Readers can also access source code at SpringerLink in the Supplementary Material section for each chapter. Printed on acid-free paper IN MEMORY OF DR. BAIDYANATH HALDAR. Sir, I truly miss you. Contents at a Glance About the Author������������������������������������������������������������������������������ ix About the Technical Reviewers�������������������������������������������������������� xi Acknowledgments�������������������������������������������������������������������������� xiii ■Chapter ■ 1: Composer���������������������������������������������������������������������� 1 ■Chapter ■ 2: Laravel Homestead, Virtual Box, and Vagrant��������������� 7 ■Chapter ■ 3: File Structure�������������������������������������������������������������� 15 ■Chapter ■ 4: Routing, a Static Method��������������������������������������������� 21 ■Chapter ■ 5: Controller Class����������������������������������������������������������� 29 ■Chapter ■ 6: View and Blade����������������������������������������������������������� 41 ■Chapter ■ 7: Environment���������������������������������������������������������������� 47 ■Chapter ■ 8: Database Migration����������������������������������������������������� 49 ■Chapter ■ 9: Eloquent���������������������������������������������������������������������� 53 ■Chapter ■ 10: Model, View, Controller Workflow����������������������������� 59 ■Chapter ■ 11: SQLite Is a Breeze!���������������������������������������������������� 63 ■Chapter ■ 12: Fiddly Feelings of Forms������������������������������������������� 65 ■Chapter ■ 13: A CRUD Application��������������������������������������������������� 67 ■Chapter ■ 14: Authentication and Authorization����������������������������� 81 ■Chapter ■ 15: More About Validation����������������������������������������������� 91 ■Chapter ■ 16: Eloquent Relations�������������������������������������������������� 123 v ■ Contents at a Glance ■Chapter ■ 17: How Security and Authentication Work Together��� 153 ■Chapter ■ 18: How Request, Response Work in Laravel 5������������� 161 ■Chapter ■ 19: Contracts vs. Facades��������������������������������������������� 167 ■Chapter ■ 20: Middleware, Layer Filter, and Extra Security���������� 173 Index���������������������������������������������������������������������������������������������� 187 vi Contents About the Author������������������������������������������������������������������������������ ix About the Technical Reviewers�������������������������������������������������������� xi Acknowledgments�������������������������������������������������������������������������� xiii ■Chapter ■ 1: Composer���������������������������������������������������������������������� 1 ■Chapter ■ 2: Laravel Homestead, Virtual Box, and Vagrant��������������� 7 2.1 Installing Virtual Box and Vagrant�������������������������������������������������� 7 2.2 Installing Homestead Vagrant Box������������������������������������������������� 9 2.3 Homestead Installation and Configuration����������������������������������� 10 ■Chapter ■ 3: File Structure�������������������������������������������������������������� 15 3.1 SOLID Design Principle����������������������������������������������������������������� 17 3.2 Interfaces and Method Injection�������������������������������������������������� 19 ■Chapter ■ 4: Routing, a Static Method��������������������������������������������� 21 4.1 Routing Best Practices ��������������������������������������������������������������� 25 4.2 Named Routes������������������������������������������������������������������������������ 26 4.3 Organize Files Through Route������������������������������������������������������ 27 4.4 Advanced Concept of Routing and Anonymous Functions����������� 28 ■Chapter ■ 5: Controller Class����������������������������������������������������������� 29 5.1 RESTful Controller������������������������������������������������������������������������ 32 5.2 Role of a Controller���������������������������������������������������������������������� 33 5.3 Resourceful Controller����������������������������������������������������������������� 34 vii ■ Contents 5.4 Controller, IoC Container, and Interface���������������������������������������� 35 5.5 Summary�������������������������������������������������������������������������������������� 38 ■Chapter ■ 6: View and Blade����������������������������������������������������������� 41 ■Chapter ■ 7: Environment���������������������������������������������������������������� 47 ■Chapter ■ 8: Database Migration����������������������������������������������������� 49 8.1 Summary�������������������������������������������������������������������������������������� 52 ■Chapter ■ 9: Eloquent���������������������������������������������������������������������� 53 ■Chapter ■ 10: Model, View, Controller Workflow����������������������������� 59 10.1 Summary������������������������������������������������������������������������������������ 61 10.1.1 Our Next Challenge����������������������������������������������������������������������������������� 61 ■Chapter ■ 11: SQLite Is a Breeze!���������������������������������������������������� 63 ■Chapter ■ 12: Fiddly Feelings of Forms������������������������������������������� 65 ■Chapter ■ 13: A CRUD Application��������������������������������������������������� 67 ■Chapter ■ 14: Authentication and Authorization����������������������������� 81 ■Chapter ■ 15: More About Validation����������������������������������������������� 91 15.1 Conditional Rules��������������������������������������������������������������������� 112 15.2 Custom Validation�������������������������������������������������������������������� 113 15.3 How Form Validation Works����������������������������������������������������� 119 ■Chapter ■ 16: Eloquent Relations�������������������������������������������������� 123 ■Chapter ■ 17: How Security and Authentication Work Together��� 153 ■Chapter ■ 18: How Request, Response Work in Laravel 5������������� 161 ■Chapter ■ 19: Contracts vs. Facades��������������������������������������������� 167 ■Chapter ■ 20: Middleware, Layer Filter, and Extra Security���������� 173 Index���������������������������������������������������������������������������������������������� 187 viii About the Author Sanjib Sinha writes stories and codes—not always in the same order. He started with C# and .NET framework and won the Microsoft Community Contributor Award in 2011. Later, the open source software movement attracted him and he became a Linux, PHP, and Python enthusiast, specializing and working on White Hat Ethical Hacking. As a beginner he always had to struggle a lot to find an easy way to learn coding. No one told him that coding is like writing—envisioning an image and bringing it down on the Earth with the help of words and symbols. Through all his books, he has tried to help beginners from their perspective—as a beginner. ix About the Technical Reviewers Yogesh Sharma I am a web developer, IT consultant and an entrepreneur based in Pune, India. I have experimented with many IT paradigm liked Cloud Services, NoSQL, Middleware but programming is at my heart.Graduated from Vidyalankar School of Information Technology, I am currently employed with a fortune 500 company as Senior Infrastructure Engineer. I really like to see the big picture with eye for distinctive intricacies. I have 8 years of cumulative experience across various domains in IT and also served clientele across the globe developing projects ranging from Asset Management to Manufacturing and Logistics. I like to tinker with IoT, AI, Speech and Simulation. If I am not these, you might find me brewing an espresso shot!" Gaurav Yadav is a Full Stack Web Developer and blogger. Sportsperson by heart and loves football. He has experience with various frameworks in php, python and javascript. Loves to explore new frameworks and evolve with the trending technology. xi Acknowledgments KARTICK PAUL, SYSTEM MANAGER, AAJKAAL, KOLKATA: Without his persistent and inspiring help, I could not have written this book. xiii CHAPTER 1 Composer Composer is a dependency management tool in PHP (Figure 1-1). For any PHP project you need to use your library of codes. Composer easily manages that task on your behalf, helping you to declare those codes. You can also install or update any code in your library through Composer. Please visit https://getcomposer.org for more details. Figure 1-1. Composer home page In the opening page of https://getcomposer.org, click the ‘getting started’ link (Figure 1-2). Electronic supplementary material The online version of this chapter (doi:10.1007/978-1-4842-2538-7_1) contains supplementary material, which is available to authorized users. © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_1 1 Chapter 1 ■ Composer Figure 1-2. Getting started page in Composer website In the page shown in Figure 1-2, you find two links: ‘locally’ and ‘globally’. It stands for two options. Suppose you don’t want to run Composer globally or centrally in your system. In that case, you have to download and install Composer each time for every project. But the global option is always preferable because once Composer is installed in your system bin folder, you can call it anytime for any project. If you are already accustomed to any Linux distribution like Ubuntu, you know that for any local PHP project we used to go to ‘/var/www/html’ folder. Suppose we are going to build a simple Laravel project and we want to name it ‘MyFirstLaravelProject’. Open up your Ubuntu terminal (ctrl+alt+t) and go to that folder first. To reach there, you need to type the following command on your terminal: cd /var/www/html/ Once you’ve reached it, you can make a directory here with a simple command: sudo mkdir MyFirstLaravelProject It will ask for your ‘root’ user password. Type the password and a folder called ‘MyFirstLaravelProject’ will be created. Next in this folder we’ll download and install ‘composer’. Considering you are a beginner, for the sake of brevity I want to download and install Composer locally on our Laravel project. 2 Chapter 1 ■ Composer Next, issue these two commands, one after another. First you type this: sudo php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" It’ll take some time. Next type this: sudo php composer-setup.php It’ll organize your Composer setup file to go further. Actually your Composer is ready to download packages for your coming project. You can test it by creating a ‘composer. json’ file inside your ‘MyFirstLaravelProject’ folder. In that ‘composer.json’ file type this: { "require": { "monolog/monolog": "1.0.*" } } What does this mean? It means you’re installing ‘monolog’ PHP package for your Laravel project. Will it come to any immediate use? The answer is ‘NO’. We’re actually testing our Composer installer and want to see how it works. Now you can issue the command that will install ‘monolog’ package for you. Type this command on your terminal: sudo php composer.phar install It’ll take a little time to install the ‘monolog’ package. It depends on your Internet speed. After the installation is over you’ll find a ‘vendor’ folder and a few ‘composer’ files inside your project. Feel free to discover what is inside the ‘vendor’ folder. There you’ll find two folders: ‘composer’ and ‘monolog’. Again you can see what they have inside them. As a beginner it’s an endless journey to discover new things. Try to get acquainted with everything new you have found. The time has come to install Laravel 5.2 through Composer. You can install Laravel just like monolog. It means that you can write that instruction in your ‘composer.json’ file and just update your Composer. But as a beginner I recommend following the simplest method. Open up your terminal and write the following: sudo composer create-project --prefer-dist laravel/laravel blog It’ll install Laravel latest version in the folder ‘blog’ in your Laravel project ‘MyFirstLaravelProject’. Once it’s done you’ll get this message on your terminal: Application key [base64:FrbQTSPezY8wQq+2+bZ/ieA8InA4KjA9N4A44AMbqas=] set successfully. 3 Chapter 1 ■ Composer It’s a random key generated each time you install Laravel. It means you have successfully installed Laravel 5.3. • First step completed: you’ve installed Laravel in the ‘/var/www/ html/MyFirstLaravelProject/blog’ folder. Now you can go inside that folder and issue a Linux command ‘ls -la’ to see what’s inside. You can also type ‘php artisan serve’ command to run your first Laravel application so that you can go to http://localhost:8000 to see the welcome page. This installation has been done locally. There is another, easier method. You can install Composer globally in your Linux system. Open your terminal and make a directory named ‘Code’ on the desktop. Open up your terminal and type this: cd /Desktop Now you are inside your desktop. You’re going to make the ‘Code’ directory there. Type the following: mkdir Code Now you must go inside your ‘Code’ directory by writing ‘cd Code’ on your terminal. Next, inside ‘Code’ folder make a directory ‘test’, where you’ll create your first Laravel application. Not only that, after the ‘Laravel/Homestead’ is installed, you can type http://test. app to run your first Laravel application. I’ll show you that step by step. Now it’s time to install Composer globally. Type these commands one after another: sudo php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');" sudo php composer-setup.php sudo php composer.phar install It’ll take a few minutes to install Composer globally. Once you have done it, you can create any Laravel project anywhere. Next you can create your first Laravel project inside the ‘Code/test’ folder by typing this command: sudo composer create-project --prefer-dist laravel/laravel blog Inside the ‘test’ folder, the Laravel project is installed as ‘blog’. While installing, you can change this name to your choice. It’ll take a few minutes depending on the speed of your Internet connection. 4 Chapter 1 ■ Composer Once done, it’ll give this message: Application key [base64:FrbQTSPezY8wQq+2+bZ/ieA8InA4KjA9N4A44AMbqas=] set successfully. You have installed the latest version of Laravel 5.2.4 on your ‘/Desktop/Cd/test/ blog’ folder. And you have done it globally. Feel free to create any folder and subfolders anywhere in your machine and install Laravel through Composer. • Second step completed: Laravel installed in ‘/Desktop/Code/test/ blog’ folder, and you’ve done it globally. In the next chapter, we’ll learn a little about installing Laravel Homestead. 5 CHAPTER 2 Laravel Homestead, Virtual Box, and Vagrant Laravel Homestead is an official, prepackaged Vagrant box. An absolute beginner may find that concept a little bit quirky. You can imagine it as a scaffold platform or magical box that contains everything for building Laravel applications on your local machine. I encourage you to search and learn about the Laravel Homestead package. If you have Laravel Homestead installed, you need not worry about the latest PHP and Linux versions. It also comes with a web server and all types of server software that you need to develop some awesome PHP applications besides Laravel! Before running Laravel/Homestead you must have Virtual Box 5.x: https://www.virtualbox.org/wiki/Downloads. You also must install Vagrant: http://www.vagrantup.com/downloads.html. 2.1 Installing Virtual Box and Vagrant The first question that comes to our mind is the following: why do we need a “virtual box” when we have a default operating system in place? There are several reasons. The most important reason is that in Virtual Box we can play with any operating system without any fear of messing it up, even breaking it. There is every possibility that while testing a hacking tool we could break a system. I encourage you to do that. It is a virtual machine. So, go ahead. Test everything that comes to mind. Another great reason of using Virtual Box is the safety. When you visit a web site you might consider it to be safe but in reality it could not be so. But nothing matters in the case of Virtual Box. It is not your original machine with confidential data. Visiting unsafe web sites is not annoying (or worse) any more. There is only one thing you need to remember. Stay within the law. While testing your hacking tools or running codes, you can’t jeopardize any other system. The Oracle Virtual Box official web site offers plenty of download options. You can choose any one of them. According to your OS, you go to the “download” section and see what is available for you. From Figure 2-1, you will gain an idea of how to proceed further. © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_2 7 Chapter 2 ■ Laravel Homestead, Virtual Box, and Vagrant Figure 2-1. Virtual Box download section for Linux hosts The selected line in Figure 2-1 shows the default operating system I am running currently. That is “Ubuntu 14.04 (Trusty)” and the architecture is “AMD64”. Virtual Box is very easy to install. Whatever your OS is—Mac OS X, Windows, or Linux—you can install it. First you need to know about your operating system itself. It could be either 32-bit or 64-bit architecture. In any Linux distribution it is extremely easy to learn. Just open up the terminal and type “uname -a”. The terminal will spit out some vital information that includes all data regarding the current default system. In this case, Linux is version 3.19.0 and the superuser’s name is “hagudu”; finally, it also indicates what type of system architecture is being used. As in my case, it is “x86_64” which stands for 64 bit. In the Virtual Box official download page for all Linux distribution, you first download the required packages and then install them according to the nature of your OS. For Red Hat, Fedora, or any Linux distribution belonging to that category, you will notice that the last extension is “.rpm”. In that case you can move to the Virtual Box folder and issue commands like “rpm -i” or “yum install” in case you run Red Hat or Fedora. But there are simpler methods to install Virtual Box. For absolute beginners, it is very helpful to run “UBUNTU” Linux distribution as your default OS. You can install Virtual Box from the software center directly without opening up the terminal or issuing any command. “UBUNTU” software center has many categories. One of them shows the “Installed” software. 8 Chapter 2 ■ Laravel Homestead, Virtual Box, and Vagrant You may not find it there by default. In that case it is extremely easy to install. You can just type “Virtual Box” on the search text box and it will pop up. Move ahead and press the installation button and it will get installed in your system. Installing Vagrant is also easy. Go to the official web site and download it according to your operating systems. The installation process is also easy. For Ubuntu, just extract the content anywhere and install it according to the procedure mentioned in the site. Search the Internet you’ll get a ton of guides. Through Virtual Box you can run different operating systems on your machine (Figure 2-2). Figure 2-2. A Virtual Box running Kali Linux and Windows XP Having installed Virtual Box you can issue 'vagrant -v' command on your terminal and the message will pop up as 'vagrant 1.8.5'. It’s running. Now it’s time to install Laravel/Homestead. 2.2 Installing Homestead Vagrant Box Once you have installed Virtual Box and Vagrant, you can add ‘laravel/homestead’ box to your Vagrant box using this command on your terminal: vagrant box add laravel/homestead It will take some time, anywhere from 15 minutes to an hour, depending on your Internet speed. 9 Chapter 2 ■ Laravel Homestead, Virtual Box, and Vagrant 2.3 Homestead Installation and Configuration Next you can install Homestead by cloning Homestead repository to your ‘/home/ Homestead’ folder using this command: git clone https://github.com/laravel/homestead.git Homestead It’ll take a few seconds. Next you need to initialize your Homestead and create the configuration file. bash init.sh Next, run an 'ls -la' command to find out the hidden './homestead' directory. Type 'cd ./homestead' command to enter into it and run 'ls -la' command again. You’ll find a file called 'Homestead.yaml'. You may consider this file as the brain of your ‘laravel/homestead’ local developmental environment. Through this file, you can instruct the local web server. You can mention the path of your project root. You can decide the name of your local application. I think it’s always wise to adopt the same name that you are going to use in your production environment. Suppose your final application in the production level will be named ‘www.example.com’; in that case, it’s good to use the same name locally so that you can type http://example. com in your browser to test the application locally. Before editing ‘Homestead.yaml’ file, you can do two more things. First, check your ‘laravel/homestead’ version and if necessary run this command: 'sudo composer global require laravel/homestead:v2.0.8'. Always try to keep the latest one. Check it in the Internet. Next, you can run this command also: 'export PATH="~/.composer/vendor/ bin:$PATH"'. It’ll help you to run 'homestead' command from anywhere on your system. Now you need to edit the ‘Homestead.yaml’ file for keeping two major things in place. The first is the provider. Run 'sudo gedit Homestead.yaml' command to open up the file on the text editor. By default you’d see 'provider: virtualbox' in your file. So you need not change this. Next, you check this part. The second part is very important. By default the ‘Homestead.yaml’ file comes up with this folder and site structure: folders: - map: ~/Code to: /home/vagrant/Code sites: - map: homestead.app to: /home/vagrant/Code/Laravel/public 10 Chapter 2 ■ Laravel Homestead, Virtual Box, and Vagrant We have already installed Laravel at the ‘Code/test/blog’ folder on the desktop. So we need to add that in this folder and site section first. folders: - map: ~/Code to: /home/vagrant/Code - map: ~Desktop/Code/test/blog to: /home/vagrant/ Desktop/Code/test/blog sites: - map: homestead.app to: /home/vagrant/Code/Laravel/public - map: test.app to: /home/vagrant/ Desktop/Code/test/blog/public The added lines are marked in red. Please note that I have mentioned the full path. Wherever you keep your Laravel application, you need to mention the full path. So, we have almost come to the close. You’ve probably noticed that we‘ve named our application ‘test.app’. Next you need to add the “domains” for your local sites to the ‘hosts’ file on your machine. The ‘hosts’ file will redirect requests for your Homestead sites into your Homestead machine. On Mac and Linux, this file is located at ‘/etc/hosts’. Open this file in your text editor. sudo gedit /etc/hosts/ Generally it comes up with two lines on the top. You must add your ‘test.app’ after the two lines. 127.0.0.1 localhost test.app 127.0.0.1 hagudu-H81M-S1 192.168.10.10 Everything done, you may now fire up Vagrant and run your site. Go to the Laravel folder 'cd /Desktop/Code/test/blog' and issue this command: 'vagrant up'. The terminal usually looks like the image in Figure 2-3. It may look different depending on your operating system. 11 Chapter 2 ■ Laravel Homestead, Virtual Box, and Vagrant Figure 2-3. The terminal after issuing ‘vagrant up’ command It normally takes a few seconds to fire it up. Give it that time, and next you can safely type http://test.app on your browser to see the Laravel welcome page. Being on your Laravel folder, you may run ‘php artisan serve’ command to run the same application. In that case, you must type http://localhost:8000 on your browser. However, there are lots of differences with the Homestead server. When you run Homestead you get the latest php version that is php 7. Look at the following image. I have simply kept the ‘phpinfo()’ method in my ‘test. app’ Laravel home page (Figure 2-4). 12 Chapter 2 ■ Laravel Homestead, Virtual Box, and Vagrant Figure 2-4. test.app running the php 7 information I hope you can do it. If by any chance if you’re stuck, feel free to drop me a line at [email protected]. I’ll definitely try to help. 13 CHAPTER 3 File Structure Let us see what’s inside the installed Laravel folder ‘blog’. It has folders like ‘app’, ‘bootstrap’, ‘config’, ‘database’, ‘public’, ‘resources’, ‘storage’, ‘tests’, ‘vendor’, and a few more files, including a ‘composer.json’ file. Let us first see how the file structure looks (Figure 3-1). Figure 3-1. Laravel 5.3.18 file structure As you see, each folder and its included files have their own roles clearly defined. You should not try to change or tweak any source code. The ‘app’ folder is extremely important. It has, again, many significant folders inside. Presently we’ll look forward for the ‘Http’ folder that has controllers, middleware, models, and the ‘routes.php’ file. Actually, we put our business logic in this folder through route and controllers. It helps us maintain the loosely coupled object-oriented design pattern. © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_3 15 Chapter 3 ■ File Structure The ‘bootstrap’ folder is needed for the startup of Laravel, and you need ‘config’ folder for many configuration files. As a PHP programmer, you know that session configuration or authentication configuration is important. Laravel manages it through this ‘config’ folder. The role of ‘database’ folder is also very vital for migrations and seeds, which we will discuss later in great detail. Presently you may think of database migrations as PHP files that write SQL codes and perform database operations directly on your application. You need not go to any MySQL interface like PHPMYADMIN. You write PHP codes and through the Laravel command line you can execute database operations. You can fill database tables with data, manipulating them accordingly. I think it’s one of the greatest features of Laravel. In the 'public' folder we have files that are available publically: '.htaccess', 'robots.txt', 'favicon.ico', and index.php'. These files play important roles in keeping your project in the search engines. The 'resources' folder has the important sub-folders like ‘views’, where your viewable PHP/HTML codes are stored. In ‘storage’, cache and log files are kept, and the ‘tests’ folder is exclusively for unit testing. Finally, you meet the 'vendor' folder again here, but it’s only for the third-party packages that Laravel uses. I encourage you to enter each folder, open every file, and see how they are written. You only remember one thing: never change any source code. Our Laravel installation is complete. We’ve first installed it in the '/var/www/html/ MyFirstLaravelProject/blog' folder. Next we have installed it in '/Desktop/Code/ test/blog' folder. The first one will be used for the MySQL database operations and the second one will be used for SQLite database operations. All we now need to see is that it works perfectly. Let us go the first one. Open up your terminal and write the following: cd /var/www/html/MyFirstLaravelProject/blog We have reached our Laravel project. Now issue this command: php artisan serve It will start the local development environment server so that if you open your web browser and type http://localhost:8000, it will open up the home page of your Laravel project. It should look like this (Figure 3-2): 16 Chapter 3 ■ File Structure Figure 3-2. Laravel 5.3.18 home page All browsers usually give simple HTML output. In that sense, there must be some HTML codes hidden somewhere in our Laravel project. In Chapter 4, we’ll see how we can change this HTML output. Besides that, we’ll very briefly discuss some points of ‘views’ folder where we actually need to store these HTML codes. Later in the book, in the ‘views and blades’ chapter, we’ll learn it in detail. 3.1 SOLID Design Principle Yes, this is quite an advanced thing that you need to learn better beforehand. From Laravel 4 the SOLID design principle has been maintained, and in Laravel 5 it becomes more familiar so that you can avoid hard coding and write cleaner codes. Let us see what this SOLID design principle is. This book is not the place to put forward a detailed description of the SOLID principle. But at least we can present something about it in a nutshell. SOLID consists of the five design principles articulated by Robert “Uncle Bob” Martin. Here they are in brief, one by one. In the final part I will discuss it in detail, and hopefully by that time you will have become acquainted with the basic principles of Laravel application logic. 17 Chapter 3 ■ File Structure SOLID stands for 1) Single Responsibility Principle 2) Open Closed Principle 3) Liskov Substitution Principle 4) Interface Segregation Principle 5) Dependency Inversion Principle The Single Responsibility Principle means a class should have one, and I mean only one, reason to change. Limiting class knowledge is important. The class’s scope should be narrowly focused. A class would do its job and not be affected at all by the change that takes place on its dependencies. Remember, if we can build a library of small classes with well-defined responsibilities, our code will be more decoupled and easy to test and run. The Open Closed Principle means a class is always open for extension but closed for modification. How is that? Nothing except that any changes to behavior should be made without modification of source codes. If you can do your job without touching the source code, then you are following the Open Closed Principle! Remember what Uncle Bob says: “Separate extensible behavior behind an interface and flip the dependencies.” The thing is that any time you modify your code, there is a possibility to break the old functionalities completely, adding new bugs. But if you can plan your application in the beginning based on Open Closed Principle, you could modify your code base as quickly as possible without getting affected. What is the Liskov Substitution Principle? Don’t get frightened. This looks intimidating, but as a principle it is extremely helpful and easy to understand. It says: Derived classes must be substitutable for their based class. It means objects should be replaceable with instances of their subtypes without altering the correctness of program. If you can’t follow that, just move on; I will explain these principles in detail with examples and screenshots, so that the picture will be much clearer. The Interface Segregation Principle is an echo of Singular Responsibilities. If it is broken, Singular Responsibility is broken. In a nutshell, it says that interface is granular and focused. No implementation of interface should be forced on methods that it does not use. Accordingly, break into small interfaces as you require them for your implementation. Plan it before and enjoy the decoupled easy-going ride. Finally, the Dependency Inversion Principle states that highlevel codes should not depend on lowlevel codes. Instead the highlevel code depends on ‘Abstraction’ that acts as a middle-man between highlevel and lowlevel. The second aspect is that abstraction does not depend upon details but details depend upon abstractions. For beginners, these principles may look not comfortable enough, but don’t worry, as we will discuss it in detail with examples; by that time you will have gained enough confidence to tackle this conceptual lingo. You have already found the terms “Interface” and “Abstraction” more than once, perhaps many times, to be a deserving candidate for discussion. So let’s spend some time with those omnipresent terms that we so often come across in our Laravel application. 18 Chapter 3 ■ File Structure 3.2 Interfaces and Method Injection Abstraction in OOP involves extraction of relevant details. Consider the role of a car salesman. There are many types of consumer. Everyone wants to buy a car, no doubt, but each one has different criteria. Each of them is interested in one or two certain features. This attribute varies accordingly. Shape, color, engine power, power steering, price … the list is endless. The salesman knows all the details of the car but does he repeat the list one by one until someone finds his or her choice? No. He presents only the relevant information to the potential customer. As a result the salesman practices “Abstraction” and presents only relevant details to customer. Now consider abstraction from the perspective of a programmer who wants a user to add items to list. Abstraction does not mean that information is unavailable but it assures that the relevant information is provided to the user. PHP 5 introduces abstract classes and methods. Classes defined as abstract may not be instantiated and any class that contains at least one abstract method must also be abstract. Remember that abstract methods can not define the implementation. On the other hand, object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled. Interfaces are defined with the interface keyword, in the same way as a standard class, but without any of the methods having their contents defined. All methods declared in an interface must be public; this is the nature of an interface. I have a .NET background and found the usage of interfaces there almost ubiquitous. And in Laravel, the injection of interfaces to the classes is seen frequently, so you better get acquainted with the conceptual background. In Laravel Interface is considered as a Contract. Contract between whom? And why? Because an interface does not contain any code but it only defines a set of methods that an object implements. Having said that, I hope you now understand that they are interrelated. We talked about maintaining a library of small classes with clearly defined scopes, and this is achievable with the help of Interfaces. As the book progresses, you will find a lot of examples of Interfaces, so don’t worry, you will find these two words pretty often in the examples. Till then, have patience and read on. For a clear picture, I would like to give a small example so that we can understand this property of encapsulated contract behavior of Interface quickly. Let us imagine I have a ‘Connection’ folder inside a folder called ‘Bengaliana’ in which I have a connection class that would connect us to the database ‘sanjib’ and retrieve some data from the respective tables ‘users’ and ‘tasks’. I don’t want to make the ‘ConnectionClass’ know our datatarget. All it will do is just get the connection and retrieve the one attribute from a table. The attribute and table name I would like to supply dynamically so that from one method I can retrieve many kinds of data. It could be user names or simple task titles, et cetera. That will also conform to the homomorphism nature of our objects. 19 Chapter 3 ■ File Structure In Laravel 5, as document says, all major components implement interfaces which are located in the ‘illuminate/contracts’ repository. This repository has no external dependencies. Having a centralized set of interfaces make you free to use alternative optional decoupled classes and do some dependency injection more freely without Laravel Facades. It sets your choices more open and user friendly. Well, there are a lot of new staffs you will find as you progress and the new features will make your journey absolutely enjoyable. To name a few, there are Route Cache, Middleware, Controller Method Injection, and many more. In Laravel 5, authenticating users becomes easier, and the user registration, authentication, and password reset controllers are now included out of the box so that they can be easily used. Okay, enough introduction. Now it is time to catch the web artisans and do some codes so that we can make some awesome applications in the future. 20 CHAPTER 4 Routing, a Static Method Routing is the concept of setting up a new URI like http://localhost:8000/hello. It will take you to a destination web page. Laravel makes it extremely simple. It’s a static method that accepts two things: a URI and an anonymous function or Closure. In the 'app/Http/routes.php' it’s been defined primarily. Start your favorite text editor and open the file. What you see? You see some code like this: Route::get('/', function () { return view('welcome'); }); Here 'Route' is a class that has a static method ‘get’ that returns a ‘view’ method which presents a web page. When a user visits the home page he is taken to the ‘welcome’ page. This ‘welcome’ is actually a PHP file: 'welcome.blade.php'. It was stored by default in the ‘views’ folder while we had been installing Laravel. When we discuss the concept of ‘view’ and ‘blade’ template engine you’ll fully understand what’s happening in the presentation layer. Using HTTP protocol you can send another request instead of the default route. Route::get('/', function () { return 'welcome'; }); It will simply return the word ‘welcome’ on your home page. Try it or anything else. Look at the code; there is an anonymous function also. As a PHP programmer I assume you know about anonymous function or closure. It’s a very useful function we often use in building applications. Laravel also uses this concept. Now we have not yet defined our route, so if we hit the browser on the URL http:// localhost:8000/hello we will get an error page. So let us create it first. Go to the ‘routes. php’ file and add this code: //requesting a new page Route::get('/hello', function () { echo 'Hello
'; }); © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_4 21 Chapter 4 ■ Routing, a Static Method Let us see how it looks and if we can add any new HTML code into it to change the look. Primarily it looks like this (see Figure 4-1): Figure 4-1. Routing to http://localhost:8000/hello URL Now we’d like to add more CSS style into it. I change the previous code into this: //requesting a new page Route::get('/hello', function () { echo "" "Hello, Dear Reader
How are you? I hope you would love this book!
"; } 37 Chapter 5 ■ Controller Class Now the logic is clear and very lucid to follow. Now we are free to change the data target any time just changing inside the class or creating another class. Here we have used ‘MySql’ but we can change it any time to any database you like. The most important thing is that our controller would never know what is going on inside. But the final hacking lies inside our ‘route’ file, because we have to bind the class and the interface and the great IoC container plays the pivotal role here. This is very simple with your ‘App’ Facades. The code is as follows: App::bind('AllUsers', 'GetAllUsers'); As you see, our ‘App’ Facades bind the class and interface together so that a nice layer has been included between our data source and the transport mechanism. Moreover, our controller does not know about what has been going on inside that layer. Our application becomes more decoupled and you easily test it with ‘phpUnit’ without directly hitting the database. 5.5 Summary We normally organize our transport mechanism or web layer through controller class. So this is a good practice to make it ignorant about our domain logic and use interfaces as a medium between web and data layer. Through controller classes we organize our routelevel logic and besides we can use modern features like dependency injections. Use interface and let controllers maintain their singularity of job which should be concerned only with the web layer. Since we use Composer to autoload our PHP classes, it can live anywhere in the file system as long as controller knows about it. And routing to controller is entirely decoupled from the file system. Resourceful controllers usually make RESTful controller around resources. Finally, we can conclude with the filter part, which is extremely important in managing the administration of an application. You can either control it through route level or explicitly use it inside your controller. Route::get('profile', array('before' => 'auth', 'uses' => 'UserController@showProfile')); Or you may specifically mention it inside the controller: Class UserController extends BaseController { public function __construct() { $this >beforeFilter('auth', array('except' => 'getLogin')); $this >beforeFilter('csrf', array('on' => 'post')); $this >afterFilter('log', array('only' => array('fooAction', 'barAction'))); } } 38 Chapter 5 ■ Controller Class And finally filter can be used through constructor like this: class UserController extends BaseController { public function __construct() { $this>beforeFilter(function() { // some code }); } } After mastering the basic controller, it is good to consult the Laravel official documentation to hone your skills. 39 CHAPTER 6 View and Blade In the MVC framework, the part ‘view’ has an important role. First of all it should look good and appealing. It deals with HTML, CSS, JavaScript, and many other codes that make a page look great. At present a little knowledge is necessary. You need not be an expert to learn this chapter. ‘Views’ folder stays inside ‘resources’ folder. You need to keep your html codes here. To make it look awesome, you may wish to have a great CSS style! That CSS file and other necessary JavaScript files should go to inside ‘public’ folder. Laravel connects them easily. We’ll learn this process step by step. First we’ll create few static pages. Second we’ll pass dynamic data so that we can later build a dynamic application on the top of that. Suppose we want to have an ‘About’ page in your application. Let us create it and connect it to our 'MyController' and finally route it to the browser. It’s quite natural that we won’t stop at having only one static page. Later we might need a ‘Contact Us’ page or any number of other pages. Keeping that perspective in mind let’s create a folder ‘pages’ inside ‘views’ folder. In the ‘pages’ folder we first create a 'master.blade.php' file. This is a master layout page. It’s not compulsory that we should always call it a ‘master’. We can call it 'layout.blade.php' or 'default.blade.php' or we can choose any other meaningful name. This master page is a blueprint of our basic layout that other pages will follow. Remember, you can always create separate folders to keep separate master layouts for other pages. It’s needless to say that you should always have only one master layout for your entire application. Let us keep our master layout simple enough. Before going to write the codes, we may want to learn one thing: what does the term ‘blade’ mean? Well, ‘blade’ is the template engine of Laravel and it should be written in php. It has its own functions to make your life easier. And for that reason you need to add an extension of ‘blade.php’. Let us write a simple ‘master.blade.php’ code and it’ll have some special ‘blade’ templating functions. //resources/views/pages/master.blade.php © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_6 41 Chapter 6 ■ View and Blade @yield('head')
@yield('heading')
@yield('content')
43
Chapter 6 ■ View and Blade
Every Writing is a Problem!
There was a problem few minutes back. There was a problem few minutes back. There was a problem few minutes back. There was a problem few minutes back. There was a problem few minutes back.
I have just solved it.
Have a nice time folks.
@stop @section('footer') Home of Sanjib Sinha @stop At the top we use the function ‘extends’, which literally extends the modularity of the master page. After that, we continually use only two functions: ‘section’ and ‘stop’. These functions actually connect to the CSS styles you have defined earlier. Each section has its own division: ‘head’, ‘title’, ‘heading’, ‘content’, and ‘footer’. Each ‘section’ contains its own contents and then we use ‘stop’ function to stop that ‘section’. Inside the ‘head’ section of ‘master.blade.php’, we have used the CSS style link. You can also use the same link inside the ‘about.blade.php’. In that case, you need not use the CSS style link inside the ‘master.blade.php’ file. The top part of our ‘about.blade.php’ page turns out to be like this: //resources/views/pages/about.blade.php @extends('pages.master') @section('head') @stop But using CSS style inside ‘master.blade.php’ is always preferable. Now, hopefully you can make out a relationship between the functions of ‘master. blade.php’ and ‘about.blade.php.’ The master page plays the role of a parent and the about page is its child. The logic flows down from parent to the child. In the ‘about.blade.php’ we encounter two foreign terms in the ‘heading’ section: //resources/views/pages/about.blade.php @section('heading') {{ $name }} {{ $profession }} @stop 44 Chapter 6 ■ View and Blade You are smart enough to guess that they are the names of the variables that we have used in our controller. Otherwise, how they’d appear in our ‘about.blade.php’ files? We have not seen them in our master page. You have guessed right: they come from the controller, 'MyController.php' file. Earlier, we have talked about passing data dynamically through controller to the view blade. Since it’s an ‘about’ page we can pass a few pieces of interesting data about us. We have decided to pass two important data points through the controller: ‘name’ and ‘profession’. Let us see the MyController code first. //app/Http/Controllers/MyController.php public function about() { $name = 'John Doe,'; $profession = 'A Writer'; return view('pages.about', compact('name', 'profession')); } You see that we have defined two variables first and then return those variables using ‘view’ method to the ‘pages.about’. Here the term ‘pages’ refers to the folder name 'resources/views/pages'. The second part—‘about’—refers to the ‘about.blade.php’ file. We could have written it as 'pages/about' in MyController. But I personally prefer the ‘.’ notation as it reflects the object-oriented approach. This passing of data can be done using many tricks. We have shown the PHP ‘compact’ method. But it could have been done this way also. //app/Http/Controllers/MyController.php public function about() { $name = ' John Doe '; return view('pages.about')->with('name', $name); } Or we could have passed it as an array value, and you can pass a long array this way. //app/Http/Controllers/MyController.php public function about() { return view('pages.about')->with([ 'name'=>'John Doe', 'profession'=>'A Writer' ]); } Finally, we can check how it looks in our favorite browser. Type http://localhost: 8000/about and it opens up the page (Figure 6-1). 45 Chapter 6 ■ View and Blade Figure 6-1. We have dynamically passed data to view So far, we have learned a few tricks that will enable us to create static pages with some dynamically generated data through the controller. Having progressed a little bit, we have gained some confidence, and we can probably venture out now to take on some more difficult tasks. 46 CHAPTER 7 Environment Laravel comes with many stunning features. One of them is definitely database migrations. In the next chapter we’ll discuss migration in detail. Before that we need to understand our environment properly. What is environment in Laravel? If you look at the document root you will find an ‘.env’ file. It basically tells us about the database connections. Where would we get that default database setup file? In the ‘config’ folder, we have a ‘database.php’ file. Open it up and see the content. We see a line that tells us about the default database connection. //config/database.php 'default' => env('DB_CONNECTION', 'mysql'), It’s MySQL. We’re not going to change it for now although it’s temporary, because in the later part of the book we’ll see how we can work with SQLite database. At present just keep it as it is – our default database is MySQL. Now opening up our ‘.env’ file we add our database, username, and password. //.env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=testdb DB_USERNAME=root DB_PASSWORD=pass There is a catch, of course. Suppose we’d like to place our project in any cloud repository like ‘github’. In that case, our secrets may come out. Laravel has thought this through. In the '.gitignore' file, it has already added this line: //.gitignore /vendor /node_modules /public/storage Homestead.yaml Homestead.json .env © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_7 47 Chapter 7 ■ Environment When you place the whole project, it’ll automatically ignore the listed folders and files. Homestead.yaml and Homestead.json are among them. We’ve set up our environment and now we can safely move to our next big chapter: database migrations. After that we’ll discuss Eloquent, and then we’ll finally see how Model, View, and Controller workflow works. We’ll also see how we can “create, retrieve, update, and delete” our SQLite database. 48 CHAPTER 8 Database Migration Database migration is one of the best features that Laravel provides. As a beginner, you may find acquiring the concept a little bit difficult. But once you have learned about database migration, the experience of working with any kind of database becomes extremely easy and pleasant. In the past you need to create a database, table, and columns either by SQL coding or by using a tool like PHPMyAdmin. The task seems to be daunting sometimes. With Laravel, it’s no longer difficult. Besides, we have an extra advantage. As a developer, working in a team, you may get your database job well synchronized with your colleagues. In that sense it’s become like a version control. You can easily roll out your database table and update with new features through php codes inside your application. All you need to do is write a few lines of PHP code and Laravel will look after the next steps. It’s that simple. Let’s start with a simple ‘tasks’ table. We’ve already mentioned the database names and other staff in our ‘.env’ file. Now it’s time to create a ‘task’ table and add some columns to it. Before starting a new migration let us go to our 'database/migrations/' folder; we find that two PHP files have already been stored there. These migration files are ‘users’ and ‘password resets’. Laravel comes with them so we can have a look and try to understand how it works actually. Open the ‘users’ table. It has a long name: '2014_10_12_000000_create_users_ table.php'. //database/migrations/2014_10_12_000000_create_users_table.php increments('id'); $table->string('name'); © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_8 49 Chapter 8 ■ Database Migration $table->string('email')->unique(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } public function down() { Schema::drop('users'); } } As you see, there are only two functions: ‘up’ and ‘down’. The instructions written inside are fairly simple to understand. It tells us about creating columns in ‘users’ table. It mentions the characteristics of the columns: whether it’ll be ‘string’, or ‘text’, or have any extra feature of uniqueness. The method ‘up’ means you generate or update the tables. The method ‘down’ has a significant meaning. It means you can roll back your migrations any time, and generate it again. Suppose in the ‘tasks’ table, you suddenly think about changing the name of a certain column. You can roll back your old migration. You can update it in your migration PHP file and then you can run the command again. Let’s start creating our new ‘tasks’ table. Open up your terminal and issue this command: //making migration php artisan make:migration create_tasks_table --create="tasks" Once you have issued this command, it’ll automatically run the migration and it’ll show it up on your terminal. After creating the ‘tasks’ table, it’ll also show you the other migrations that have been shipped with Laravel. //run the migrate command php artisan migrate After a successful migration it will show all migrations at one place. //showing Migration Migrated: Migrated: Migrated: the migrations table created successfully. 2014_10_12_000000_create_users_table 2014_10_12_100000_create_password_resets_table 2016_08_30_024812_create_tasks_table Now we actually have three tables at hand. The new table ‘tasks’ has also been created successfully. You can either check it on your terminal or open up your MySQL tool and see it. Besides, we need to see how the migration PHP file has been created in our 'database/migrations' folder. 50 Chapter 8 ■ Database Migration There should be a file called '2016_08_30_024812_create_tasks_table.php' in that folder. Let us open it see what it has in store for us. //database/migrations/2016_08_30_024812_create_tasks_table.php increments('id'); $table->timestamps(); }); } public function down() { Schema::drop('tasks'); } } You see the difference between the default ‘users’ table and the newly created ‘tasks’ table. Our ‘tasks’ table comes up with two methods—as usual, ‘up’ and ‘down’—but it has only two columns: ‘id’ and ‘timestamps’. Remember, whenever you run a migration, a PHP file is generated inside 'database/ migrations' folder and it looks like this. Now, it’s our responsibility to add columns into it and again issue the migration command. We did the same thing here. We have changed this part. We’ve added title and body columns to complete our ‘tasks’ table. //database/migrations/2016_08_30_024812_create_tasks_table.php public function up() { Schema::create('tasks', function (Blueprint $table) { $table->increments('id'); $table->string('title'); $table->text('body'); $table->timestamps(); }); } We run ‘migrate’ command again to update the database table. After that it automatically updates itself. //run the migrate command php artisan migrate 51 Chapter 8 ■ Database Migration In this step, suppose we have forgotten a column in the newly created ‘tasks’ table. Can we add it after all the migrations are over? Yes, we can do that. The greatness of Laravel is it has already thought about every possibility that might happen. This time the command is slightly different. //adding a new column to the table php artisan make:migration add_reminder_to_tasks_table --table="tasks" Created Migration: 2016_08_30_035529_add_reminder_to_tasks_table We forgot to add a column ‘reminder’ into our ‘tasks’ table. We have just added it using migration command. Now we can have a look at our newly created ‘tasks’ database table in our phpMyAdmin tool (Figure 8-1). Figure 8-1. The ‘tasks’ table at phpMyAdmin tool Our ‘tasks’ table has all the columns now: ‘id’, ‘title’, ‘body’, ‘timestamps’, and finally ‘reminder’, which we added later. 8.1 Summary Database migration in Laravel is a technique that helps us to create, update, or delete the table and its columns. In a developmental scenario, when you work on a project participating from different destinations, you can easily modify or manipulate your database through a few simple php commands. 52 CHAPTER 9 Eloquent Eloquent Model class is used for Laravel’s ‘active record implementation’ methods. It literally means that we can easily ‘CREATE, RETRIEVE, UPDATE, or DELETE’ any database record using this Eloquent Model class. In the Laravel PHP artisan command we generate files through ‘make’. We have seen it before in case of ‘controllers’, ‘migrations’. Now we can do the same thing in our Model class. Remember one thing: if you have a table called ‘tasks’, then you must have a model called ‘Task’. If we have a table called ‘songs’, we must have a model called ‘Song’. In the model, the name starts with the capital letter and the last letter of the table is ignored. Let us create our first model class ‘Task’. As usual we open our terminal and issue this command: //creating model task php artisan make:model Task Model created successfully. Once we have issued this command, in the ‘app’ folder a PHP file is automatically generated. //app/Task.php >> $task = new App\Task; => App\Task {#632} >>> $task => App\Task {#632} >>> $task->title = 'My First task'; => "My First task" >>> $task->body = 'I will wake up early in the morning tomorrow.'; => "I will wake up early in the morning tomorrow." >>> $task->reminder = 'Do not forget'; => "Do not forget" >>> $task->toArray(); => [ "title" => "My First task", "body" => "I will wake up early in the morning tomorrow.", "reminder" => "Do not forget", ] >>> $task->save(); => true >>> //adding completed Actually we have created a ‘task’ object using the ‘Task’ class. Now that object can automatically access the columns almost like properties. Watch this part of the previous tinker operation. >>> $task->title = 'My First task'; => "My First task" It actually keeps those values in memory. When you finally call the save() method, it saves all the records in the table. Let us fill with another set of records. //create new set of record php artisan tinker 54 Chapter 9 ■ Eloquent Psy Shell v0.7.2 (PHP 5.5.9-1ubuntu4.14 — cli) by Justin Hileman >>> $task = new App\Task; => App\Task {#632} >>> $task->create(['title' => 'My Second Task', 'body' => 'I would like to get up early in the morning', 'reminder' => 'I need to buy medicines']); => App\Task {#643 title: "My Second Task", body: "I would like to get up early in the morning", reminder: "I need to buy medicines", updated_at: "2016-08-30 04:45:10", created_at: "2016-08-30 04:45:10", id: 2, } >>> //created successfully Can we update the first record now? Yes, of course we can. There are two methods through which you can update your previous records. The first method is the old method of writing it again and calling the save() method like before. //now you want to update the first record >>> $task = App\Task::find(1); => App\Task {#631 id: "1", title: "My First task", body: "I would like to go to market by nine.", created_at: "2016-08-30 04:20:53", updated_at: "2016-08-30 04:37:52", reminder: "You must go. You need to buy medicines.", } >>> $task->body = 'I will wake up in the morning.'; => "I will wake up in the morning." >>> $task->save(); => true >>> $task->reminder = 'I must do.'; => "I must do." >>> $task->save(); => true >>> //record successfully updated There is another method where you can call update() method directly to update your record. //another update method >>> $task->update(['reminder' => 'I must do and not forget!']); 55 Chapter 9 ■ Eloquent => true >>> //record successfully updated Finally we want to test a mass assignment using eloquent model class. >>> $task = new App\Task; => App\Task {#633} >>> $task->create(['title' => 'My Third Task', 'body' => 'I have to start car engine', 'reminder' => 'Battery will choke']); => App\Task {#646 title: "My Third Task", body: "I have to start car engine", reminder: "Battery will choke", updated_at: "2016-08-31 05:36:16", created_at: "2016-08-31 05:36:16", id: 3, } >>> It didn’t give any error. But it would have given the error had we not already changed the eloquent ‘Task’ model class. We had earlier added this line into that empty class. //app/Task.php {{ $task->title }} {{ $task->body }}
Reminder : {{ $task->reminder }}
@endforeach For each ‘$tasks’ as ‘$task’ we can directly get the data. The workflow is completed.
10.1 Summary It started from building up an environment file where we mentioned the default database as MySQL and named the database as ‘testdb’. Next we did the database migrations and using ‘tinker’ added and updated a few tasks. Further, we moved ahead and created an eloquent model class ‘Task’ since our database table name was ‘tasks’. Next we registered the route and created a TaskController class and through it we passed the data using ‘Task’ model to our view page ‘task.blade.php’.
10.1.1 Our Next Challenge For a small text-based database application, SQLite is fine. It’s fast and file based. Let us build a database-driven application that will create, retrieve, update, and delete ‘reviews’. This time we’ll not use ‘tinker’ for database operations. Instead we’ll learn about forms and build separate pages for those jobs. The ‘review’ page of a certain user, John Doe for example, will have a home page that will list the titles. If someone clicks that title she can read that review in a separate page. At the same time John can manage the whole database through a dashboard where authentication will be needed. Through that dashboard he will manage the ‘CRUD’. This time we use our Laravel/homestead box and name this application as ‘review.app’, so that if you type http://review.app you can see John’s reviews. And you can also insert, update, and delete data; it will be a total CRUD application. Let us stomp our feet on the beach! It’s fun…
61
CHAPTER 11
SQLite Is a Breeze! We’d like to make this application entirely based on SQLite database. Normally, for a big application people opt for MySQL or PgSQL as it can tackle more visitors. SQLite may not be big enough and basically file based and light in nature, but it can easily tackle small to medium applications with a hundred thousand visitors. So we can feel free to use it for our CRUD application. Especially for Laravel, SQLite is a breeze to use. In a minute you’ll understand why I sound so confident. To use SQLite in Laravel you need to change the default database setup. Two lines need to be changed. //Code/test/blog/config/databse.php 'default' => env('DB_CONNECTION', 'sqlite'), In the second line, you need to mention the SQLite database file path. //Code/test/blog/config/databse.php 'connections' => [ 'sqlite' => [ 'driver' => 'sqlite', //'database' => storage_path('database.sqlite'), 'database' => env('DB_DATABASE', database_path('/../database/database. sqlite')), 'prefix' => '', ], We are going to keep our SQLite file in the 'Code/test/blog/database/' folder. Many people go for the storage folder. Any one of them will work. Secondly, we need to change the ‘.env’ file. In the original file that comes with Laravel, the default database is mentioned as this: //Code/test/blog/.env DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306
© Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_11
63
Chapter 11 ■ SQLite Is a Breeze!
DB_DATABASE=testdb DB_USERNAME=root DB_PASSWORD=pass You must change it to this: //Code/test/blog/.env DB_CONNECTION=sqlite DB_HOST=127.0.0.1 DB_PORT=3306 Therefore, from now on, whatever database operation you’d do on your application will automatically be registered on SQLite database file that you create in the 'Code/ test/blog/database' folder. Normally, people don’t go for creating a new SQLite file in 'Code/test/blog/database' folder. They choose the 'Code/test/blog/storage/ databse.sqlite' file that comes with Laravel by default. In that case, in your database path 'Code/test/blog/config/databse.php' you need to change the path. We want to take a little break from usual path and create a ‘database.sqlite’ at 'Code/ test/blog/database' folder. To do that you must go to the desired folder first. cd Code/test/blog/database Next we have to use ‘touch’ command to create the file. touch database.sqlite Now you’re ready to make an awesome CRUD application using SQLite. And to do that, the first thing you have to do is fill up the forms with inputs. Through those inputs, you can insert or update data into your file-based SQLite database.
64
CHAPTER 12
Fiddly Feelings of Forms To fill up the forms, you need to feel the forms first. Since Laravel 5.2.45 this feeling is a little bit different. It’s become little bit tricky. You need to install HTML form builder so that you can use Laravel form blade template; this is really important for security reasons. But, there is a catch. Since Laravel 5.2.45 the old trick will not work. You can no longer use 'composer require illuminate/html' command to add form builder templates to your project. Instead, you have to issue this command: sudo composer require laravelcollective/html It’ll take few minutes for composer to update your system. Next it’ll search for 'providers' and 'aliases'. So you must open 'Code/test/blog/config/app.php' file and this line inside 'providers' array. //Code/test/blog/config/app.php 'providers' => [ /* * Laravel Framework Service Providers... */ ... 'Collective\Html\HtmlServiceProvider', ], Next you must add two lines between the 'aliases' array. //Code/test/blog/config/app.php 'aliases' => [ ... 'Form' => 'Collective\Html\FormFacade', 'Html' => 'Collective\Html\HtmlFacade', ], Now you’re fully loaded to use the Laravel form template. In the next chapter we’ll see extensive use of the forms. © Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_12
65
CHAPTER 13
A CRUD Application I don’t want to elaborate this application because I believe you’re smart enough to follow what will take place in a few minutes when you’ll have a look at the subsequent codes. The application we’re going to make is very simple. John Doe is a user who wants to create a review page for his web site. He must have an index page. From that index page one can go the detail section of the reviews he has been keeping. To do that, he has a database migration file first. First we create that file (consult the database migration chapter). Our file is named something like this: 2016_09_03_015541_create_reviews_table.php. The code is like this: increments('id'); $table->string('category'); $table->string('title'); $table->text('content'); $table->string('rating'); $table->timestamps(); }); } /** * Reverse the migrations.
© Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_13
67
Chapter 13 ■ A CRUD Application
* * @return void */ public function down() { Schema::drop('reviews'); } } You have already chosen SQLite database file to keep your data. So the next part is pretty simple. Write down the Model, Views, and Controllers. The model we use in this case, the old ‘Task’ model will not work any more. We need to create a new ‘Review’ model. Create it according to the trick you’ve learned. Issue the artisan command. It’ll automatically be created. The 'Review.php' file is created in your 'Code/test/blog/app' folder. //Code/test/blog/app/ Review.php reviews = $reviews; $this->requests = $requests; } public function index() { $tasks = $this->reviews->all(); return view('pages.index', compact('tasks')); } public function show($id) { //return $tasks by id; $tasks = Review::findOrFail($id); return view('pages.show', compact('tasks')); } public function create() { return view('pages.create'); } public function store(Request $request){ //$input = Request::all(); //return $input; //return $request->title; $review = new Review(); $review->category = $request->category; $review->title = $request->title; $review->content = $request->content; $review->rating = $request->rating; $review->save(); return "Success"; } public function editreview() { $tasks = $this->reviews->get(); //return all $tasks; return view('pages.editreview', compact('tasks')); } public function edit($id) { $tasks = $this->reviews->find($id); return View('pages.edit', compact('tasks')); } public function update($id) { $review = $this->reviews->find($id); $request = $this->requests; $review->category = $request->category;
69
Chapter 13 ■ A CRUD Application
$review->title = $request->title; $review->content = $request->content; $review->rating = $request->rating; $review->save(); return "Success"; } } From the controller class you understand that there are a few new methods other than the 'index'. The index method shows the home page of John Doe’s review page (Figure 13-1).
Figure 13-1. The review page of John Doe The controller method is like this: public function index() { $tasks = $this->reviews->all(); return view('pages.index', compact('tasks')); } The code of ‘index.blade.php’ page in the views folder is a mere repetition of the previous codes we had used in our early application development. It extends a master layout and follows a few simple rules.
70
Chapter 13 ■ A CRUD Application
//resources/views/pages/index.blade.php @extends('pages.master') @section('head') @stop @section('title') It's a newly created Task page @stop @section('heading') Review page of John Doe @stop @section('content') @foreach ($tasks as $task) Category : {{ $task->category }}
Title : {{ $task->title }} ⋅⋅⋅⋅⋅ Title : {{ $task->title }} ⋅⋅⋅⋅⋅ Title : {{ $task->title }}
@endforeach @stop @section('footer') ⋅⋅⋅⋅⋅ Create New Reviews ⋅⋅⋅⋅⋅ Home of John Doe @stop The required route for this page will be quite simple. We assume reviewing is our new task so we keep it as a simple task. //app/Http/routes.php Route::get('task', 'TaskController@index'); 71 Chapter 13 ■ A CRUD Application Once this index page of John Doe’s review has shown up, the visitor will be happy to click the titles and read the reviews. For that we’ve used the special ‘url’ function. Watch this part of the ‘index.blade.php’ page. Title : {{ $task->title }} ⋅⋅⋅⋅⋅ Title : {{ $task->title }} ⋅⋅⋅⋅⋅ Title : {{ $task->title }} We’ve used three methods just to show you the various flexible methods. In the real world you must use only one. If you ask my preference, I’ll vote for any one of them! The clickable links will take the visitors to the ‘show.blade.php’ page in the views folder (Figure 13-2).
Figure 13-2. The detail of the review page It’s fairly simple in our ‘TaskController’ part. Watch this code segment. //TaskConreoller.php public function index() { $tasks = $this->reviews->all(); return view('pages.index', compact('tasks')); } public function show($id) {
72
Chapter 13 ■ A CRUD Application
$tasks = Review::findOrFail($id); return view('pages.show', compact('tasks')); } The code of the ‘show.blade.php’ is a little bit tricky. But it needs no explanation at this stage. //show.blade.php @extends('pages.master') @section('head') @stop @section('title') It's a newly created Task page @stop @section('heading') Review page of John Doe @stop @section('content') Category : {{ $tasks->category }}
Title : {{ $tasks->title }}
Review : {{ $tasks->content }} Rating : {{ $tasks->rating }}
Back Home ⋅⋅⋅⋅⋅ @stop @section('footer') Create New Reviews Home of John Doe @stop Now we can route this page through the ‘routes.php’ file like this: //routes.php Route::get('task/{id}', 'TaskController@show'); Now the important part of the application comes up slowly. First comes the creation part. John Doe wants to create or add reviews to his pages. He will add categories, title, content and rating, one after another (Figure 13-3).
73
Chapter 13 ■ A CRUD Application
Figure 13-3. Create review page The process is not very difficult. In a simple php application it’d have taken probably a few hundred lines of code to make such an application. But Laravel makes life much simpler. In the ‘TaskController’ class the segment seeks your attention. We’ve written this part with two methods consecutively. //TaskController.php public function create() { return view('pages.create'); } public function store(Request $request){ //$input = Request::all(); //return $input; //return $request->title; $review = new Review(); $review->category = $request->category; $review->title = $request->title; $review->content = $request->content; $review->rating = $request->rating; $review->save(); return "Success"; } Next we must have a blade template view page where we can use the forms. The code of ‘create.blade.php’ is like the following.
74
Chapter 13 ■ A CRUD Application
//create.blade.php @extends('pages.master') @section('head') @stop @section('title') Creating Reviews @stop @section('heading') John Doe's going to Create new Reviews @stop @section('content') {!! Form::open(['url' => 'create/task']) !!}
@stop @section('footer') John Doe is not in the mood to add new reviews so he's going back home to edit his old reviews!
75
Chapter 13 ■ A CRUD Application
Home of John Doe @stop And to register the required route, we have to write this piece of code in our ‘routes. php’ file. //routes.php Route::get('create', 'TaskController@create'); Route::post('create/task', 'TaskController@store'); Finally, the most tricky part of our CRUD application is about to come. It sounds tricky but Laravel makes it much easier with the concept of model binding. Since the model ‘Review’ essentially plays the main role behind the scene, the ‘edit’ section is basically dealt by a special method. First thing is our controller part. //TaskController.php public function edit($id) { $tasks = $this->reviews->find($id); return View('pages.edit', compact('tasks')); } public function update($id) { $review = $this->reviews->find($id); $request = $this->requests; $review->category = $request->category; $review->title = $request->title; $review->content = $request->content; $review->rating = $request->rating; $review->save(); return "Success"; } As you see, we needed two methods. The first is the ‘edit’ method, which takes us to the ‘edit.blade.php’ page. The second part is obviously the ‘update’ method, which does the work behind. But at the end of the day, it’s the model binding that does the real trick behind the scene. First comes the ‘editreview’ page. If John Doe wants to edit his reviews, he will type this URL into his browser: http://test.app/editreview. We’re going to see the code in our ‘editreview.blade.php’ page. //editreview.blade.php @extends('pages.master') @section('head') @stop @section('title')
76
Chapter 13 ■ A CRUD Application
It's a newly created Task page @stop @section('heading') John Doe's going to edit Review page @stop @section('content') @foreach ($tasks as $task) {!! Form::label('category', 'Category') !!} {!! Form::text('category', null, ['class' => 'formcontrol', 'required'])!!}
{!! Form::label('title', 'Title') !!} {!! Form::text('title', null, ['class' => 'formcontrol', 'required'])!!}
{!! Form::label('content', 'Content') !!} {!! Form::textarea('content', null, ['class' => 'formcontrol', 'required']) !!}
{!! Form::label('rating', 'Rating') !!} {!! Form::text('rating', null, ['class' => 'formcontrol', 'required'])!!}
{!! Form::submit("Create Reviews") !!} {!! Form::close() !!}
Category : {{ $task->category }}
Title : {{ $task->title }}
@endforeach @stop @section('footer') Create New Reviews Home of John Doe @stop There’s nothing very special on this page. He clicks a link and reaches the ‘edit’ page. The code of ‘edit.blade.php’ is tricky on one line. Watch out for this! (See Figure 13-4.) Figure 13-4. Edit page of John Doe’s review 77 Chapter 13 ■ A CRUD Application The edit page where the actual editing will take place will be a little different. //edit.blade.php @extends('pages.master') @section('head') @stop @section('title') It's a newly created Task page @stop @section('heading') John Doe's going to edit Review page @stop @section('content') {!! Form::model($tasks, ["url" => "update/$tasks->id", "method" => "PATCH"]) !!}
@stop @section('footer') Create New Reviews
78
Chapter 13 ■ A CRUD Application
Home of John Doe @stop This part is tricky: {!! Form::model($tasks, ["url" => "update/$tasks->id", "method" => "PATCH"]) !!} The subsequent route will be registered in the ' routes.php' file. //routes.php Route::get('editreview', 'TaskController@editreview'); Route::get('edit/{id}', 'TaskController@edit'); Route::patch('update/{id}', 'TaskController@update'); The edit page of the John Doe’s review looks like this when he clicks the relevant title to edit them (Figure 13-5).
Figure 13-5. The editing page of John Doe’s review Our application is complete in a simple few lines of code. You did not need to write a hundred thousand of lines of code to accomplish this complex task. The index page shows the titles of the reviews. When somebody clicks the titles, she can reach the review page. The ‘show’ method in the ‘TaskController.php’ has taken her to the detail of the reviews. When John Doe wants to add reviews it’s quite easy. He adds it just by filling up his forms. Next comes the easiest part: the editing section. He clicks the title and reaches the edit page.
79
CHAPTER 14
Authentication and Authorization Laravel 5.3 makes Authentication extremely simple, and if you’re familiar with .NET Framework, it will remind you of the ASP.NET login and logout process. In fact you need not have to do anything at all. Everything is ready at your doorstep; all you need is just plug in and switch on, and the Authentication process will work like a breeze. People coming from Laravel 3.2 or 4.2 backgrounds, find it unbelievable at times. In fact you are not supposed to write long lines of code. It is so easy and handy. It works just out of the box because everything has been configured beforehand and you can go through the code of ‘config/app.php’. When you install Laravel 5, you see two controllers have already been set up in ‘app/Http/Controllers/Auth/’ folder. These two controllers are ‘AuthController’ and ‘PasswordController’. Let us see how ‘AuthController’ works. It is used for new user registration and login purposes. And through ‘PasswordController’ a user can reset her password. Each of these controllers uses Traits to have their necessary methods. So you initially you should not change these controllers, unless you are in a very special situation where you would like to customize your registration and login process. Let us see first what lies inside this ‘AuthController’ Controller, so that we can understand how it works out of the box. middleware('guest', ['except' => 'getLogout']); }
82
Chapter 14 ■ Authentication and Authorization
/** * Get a validator for an incoming registration request. * * @param
array
$data
* @return \Illuminate\Contracts\Validation\Validator */ protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255| unique:users', 'password' => 'required|confirmed| min:6', ]); } /** * Create a new user instance after a valid registration. * * @param
array
$data
* @return User */ protected function create(array $data) { return User::create([
83
Chapter 14 ■ Authentication and Authorization
'name' => $data['name'], 'email' => $data['email'], 'password' => bcrypt($data['password']), ]); } } When you create an instance of Authentication, it automatically calls back the ‘middleware’ property, and in your route you can set it so that if want to protect any page from unsigned visitor or guest you just mention it in your route. public function __construct()
{ $this>middleware('guest', ['except' => 'getLogout']); } The validator() method at the same time works so that when someone registers he is guided properly to maintain the rule. protected function validator(array $data) { return Validator::make($data, [ 'name' => 'required|max:255', 'email' => 'required|email|max:255| unique:users', 'password' => 'required|confirmed|min:6', ]); } So in a nutshell the ‘AuthController’ is shipped with all the guns to fire up in a crisis. Now let us start building up a nice Authentication process through which we can register and log in. And at the same time we will see how we can use ‘middleware’ property to
84
Chapter 14 ■ Authentication and Authorization
guard our users’ dashboards. To start with you need to create a ‘users’ table. You are supplied with a default user migration file in your ‘database/migration’ file. Let us set it up first like this: public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table>string('name'); $table->string('email')->unique(); $table->string('password', 60); $table>rememberToken(); $table->timestamps(); }); } You see I have set up the columns. Now issue the following command: php artisan migrate I have set up a database ‘MyApp’ in the ‘.env’ file beforehand so the ‘users’ have been added to that database now. Now we add four view pages to our ‘views’ folder. These pages are ‘login.blade.php’, ‘register.blade.php’, ‘dashboard.blade.php’, and ‘home.blade.php’. //codes of 'login.blade.php' starting @extends('auth.master') @section('title') Login Page @stop @section('content')
85
Chapter 14 ■ Authentication and Authorization
- {{ Form::label('category', 'Category:') }} {{ Form::text('category') }}
- {{ Form::label('title', 'Title:') }} {{ Form::text('title') }}
- {{ Form::label('content', 'Content:') }} {{ Form::textarea('content') }}
- {{ Form::label('rating', 'Rating:') }} {{ Form::text('rating') }}
- {{ Form::submit('Update', array('class' => 'btn btn-info')) }}
Sign In
@foreach ($errors->all() as $error)
{!! Form::open(["url" => "auth/login", "method" => "POST"]) !!}
@stop @section('footer') Users Registration page @stop //code ended Now let us create register page. //code of 'dashbaord.blade.php' starting @extends('auth.master') @section('title') Registration Page @stop @section('content') {!! Form::label('Name : ') !!} {!! Form::text('name')!!}
{!! Form::label('Email : ') !!} {!! Form::email('email')!!}
{!! Form::label('Password : ') !!} {!!
86
Chapter 14 ■ Authentication and Authorization
Form::password('password')!!}
{!! Form::submit('Sign In') !!} {!! Form::close() !!} Register
@foreach ($errors->all() as $error) {!! Form::open(["url" => "auth/register", "method" => "POST"]) !!}
@stop @section('footer') Registration Page @stop //code ended For brevity we will skip the codes for dashboard and home. Everything is the same except for one logout option. That is like this: {!! Form::label('Name : ') !!} {!! Form::text('name')!!}
{!! Form::label('Email : ') !!} {!! Form::email('email')!!}
{!! Form::label('Password : ') !!} {!! Form::password('password')!!}
{!! Form::label('Password Confirmation : ') !!} {!! Form::password('password_confirmation')!!}
88
Chapter 14 ■ Authentication and Authorization
{!! Form::submit('Register') !!} {!! Form::close() !!} {!! Form::open(["url" => "auth/logout", "method" => "POST"]) !!} {!! Form::submit('Sign Out') !!} {!! Form::close() !!} Now finally we add these methods ‘routes.php’ //codes of 'routes.php' starting // Authentication routes Route::get('auth/login', 'Auth\AuthController@getLogin'); Route::post('auth/login', 'Auth\AuthController@postLogin'); Route::get('auth/logout',
89
Chapter 14 ■ Authentication and Authorization
'Auth\AuthController@getLogout'); Route::post('auth/logout', 'Auth\AuthController@getLogout'); // Registration routes Route::get('auth/register', 'Auth\AuthController@getRegister'); Route::post('auth/register', 'Auth\AuthController@postRegister'); //how to protect your users page Route::group(['middleware' => 'auth'], function () { Route::get('home', function () { return view('auth.home'); }); Route::get('dashboard', function () { return view('auth.dashboard'); }); //it works //Route::get('test', 'MyController@test'); }); //code ended Now your register page automatically does the server-side validation. You see the ‘register.blade.php’ page $errors>all() method. It does the trick. If a user fills up all the fields properly and presses the register button, he will directed to the home page automatically. And if he logs in he will redirected to the dashboard. There he can signs out. So we can conclude that Authentication in Laravel 5 is just like a cakewalk. All you need to do is set the users table, create a few view pages, and add the necessary routes.
90
CHAPTER 15
More About Validation Okay, there is nothing new in the word validation. Even if you are a beginner you already know what the term validation means. Very simple. Sending blank forms might cause major problem for the server and as a developer you would also suffer from that. Another big problem is the user itself. The rule of thumb is not to trust the user. And that is true. You want user’s e-mail and some text is being supplied instead. How will tackle this menace? The answer is validation. And Laravel has made it really easy. Not only easy, but with so many choices, it really becomes something where the possibilities are endless. Let us consider a form like before: {{ Form::open(array('url' => '/')) }} {{ Form::label('username', 'Username') }} {{ Form::text('username') }} {{ Form::label('email', 'EMail Address') }} {{ Form::email('email', '[email protected]') }} {{ Password field. }} {{ Form::label('password', 'Password') }} {{ Form::password('password') }} {{ Password confirmation field. }} {{ Form::label('passwordConfirmation', 'Password confirmation') }} {{ Form::password('passwordConfirmation') }} {{ Form::open(array('url' => '/')) }}
© Sanjib Sinha 2017 S. Sinha, Beginning Laravel, DOI 10.1007/978-1-4842-2538-7_15
91
Chapter 15 ■ More About Validation
{{ Form::hidden('hagu', 'mutu') }} {{ Form::open(array( 'url' => 'test/test', 'files' => true )) }} {{ Form::label('avatar', 'Avatar') }} {{ Form::file('avatar') }} {{ Form::submit('Submit') }} {{ Form::close() }} //end of code The form is simple enough with some tricks included. But it targets the main opening page that can be changed to something like ’registration.blade.php’ or anything you like. And by default it uses ‘POST’ request verb. Now, how can we validate this form so that no one sends a blank request, causing severe problems for our application and burdening our server? Our first priority should be the form fields that should not have been left blank. A user must fill in the forms. Our application would look into that matter internally. Remember, the greatness of Laravel is that it usually looks after this mechanism fantastically. You need not worry about it at all. As you see, we can set more rules for our users here. For example, in username, there must be some alphanumeric value. We should force our user to follow the rule, otherwise it will not be maintained. As I say, the possibilities are endless; there are many more options. The rule is very simple. And Laravel will take the main responsibilities so you need not worry about it at all. It goes something like this: Route::post('/', function() { $postdata = Input::all(); //we are going to handle the form }); //end of code
92
Chapter 15 ■ More About Validation
And the next step would be pretty simple: Route::post('/', function() { $postdata = Input::all(); $check = array( 'username' => 'alpha_num' ); }); //end of code As you see, we set our users follow a rule which says that you should provide some alphanumeric value. Okay, I hope this is enough to provide a sample of how it works. Before embarking on a new journey to Laravel validation, we would like to see if we could have done some validation on our own if we were not given a superpower like Laravel! It will help us to clear up the concepts. We’re going to test almost same form making it a little shorter for brevity. We have three files: ‘form.php’, ‘validate.php’, and ‘action.php’. In the first file, ‘form.php’, the form will show up and is ready for checking two fields: username and e-mail. We force our users to obey some rules, like no blank submissions, e-mail must look like e-mail, et cetera. //first the form view page: