🔙 Quay lấi trang tải sĂĄch pdf ebook Laravel 5 Cookbook Enhance Your Amazing Applications Ebooks NhĂłm Zalo Laravel 5 Cookbook Enhance Your Amazing Applications Nathan Wu Š 2015 - 2016 Nathan Wu Contents Book Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Book Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 What You Will Get . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Book Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Translation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Book Status, Changelog and Contributors . . . . . . . . . . . . . . . . . . . . . . . . . . 4 Changelog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Current Version . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 Laravel 5 Cookbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6 Chapter 1: Back End Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Project Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 List Of Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7 Recipe 1 - Introducing CLI (Command Line Interface) . . . . . . . . . . . . . . . . . . . . 8 Recipe 2 - All About Git . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Recipe 3 - Build A Laravel Starter App . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Recipe 4 - Create A User Authentication System with Facebook and Socialite . . . . . . . 31 Recipe 5 - Create A User Authentication System Using Laravel Auth Scaffold . . . . . . . 42 Recipe 6 - Image Upload In Laravel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50 Recipe 7 - Seeding Your App Using Faker . . . . . . . . . . . . . . . . . . . . . . . . . . 61 Recipe 8 - Pagination . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 Recipe 9 - Testing Your App . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71 Recipe 10 - Writing APIs with Laravel . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Chapter 2: Front End Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 List Of Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 Recipe 201 - Notifications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 CONTENTS Recipe 202 - Integrating Buttons With Built-in Loading Indicators . . . . . . . . . . . . . 116 Recipe 203 - Create A Registration Page Using AJAX and jQuery . . . . . . . . . . . . . 123 Recipe 204 - Create A Login Page Using AJAX And jQuery . . . . . . . . . . . . . . . . . 139 Recipe 205 - Upload Files Using AJAX And jQuery . . . . . . . . . . . . . . . . . . . . . 148 Recipe 206 - Cropping Images Using jQuery . . . . . . . . . . . . . . . . . . . . . . . . . 167 Chapter 3: Deployment Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 List Of Recipes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185 Recipe 301 - Deploying your applications using DigitalOcean (PHP 7 and Nginx) . . . . . 185 Recipe 302 - Deploying your applications using Heroku . . . . . . . . . . . . . . . . . . . 200 Recipe 303 - Deploying your applications blazingly fast using GIT . . . . . . . . . . . . . 208 Book Information 1 Book Description If you’re looking for a book that can help you to build amazing web applications, this is the book for you! Aimed at people who have some experience with Laravel, this cookbook has your back! There are many proven code rich recipes for working with Laravel. Each recipe includes practical advice, tips and tricks for working with jQuery, AJAX, JSON, API, data persistence, complex application structure, modular PHP, testing, deployment and more. Think about this book as a collection of all premium Laravel tutorials or the successor to the popular Learning Laravel 5 book. Laravel 5 Cookbook also includes tested code that you can download and reuse in your own applications. You’ll save time, learn more about Laravel and other related technologies in the process. We also have a forum for discussion and debate. You can freely ask any questions, provide your valuable feedback and help others. It’s time to discover Laravel more! Requirements The projects in this book are intended to help people who have grasped the basics of PHP and HTML to move forward, developing more complex projects, using Laravel advanced techniques. The fundamentals of the PHP and Laravel are not covered, you will need to: • Read Learning Laravel 5 book. (optional) • Have a basic knowledge of PHP, HTML, CSS and Laravel. • Love Laravel. What You Will Get • Lifetime access to the online book. (Premium Only) • Digital books: PDF, MOBI, EPUB (Premium Only) • Full source code (Premium Only) • Access new chapters of the book while it’s being written (Premium Only) • A community of 20000+ students learning together. • Amazing bundles and freebies to help you become a successful developer. • iPhone, iPad and Android Accessibility. 2 Book Description 3 Book Structure Note: This is a draft version. This book is still under active development, that means some chapters and its content may change. The book also may have some errors and bugs. For any feedback, please send us an email. Thank you. Chapter 1 - Back End Recipes Building APIs and large applications using modern technologies can be a daunting task. In this chapter, you’ll learn best practices and modern techniques for back-end development, starting with an introduction to the command line and Git. These complete, easy-to-use recipes show you how to use cookies, sessions, web storage and some popular Laravel packages. You’ll also learn about writing APIs and debugging techniques. In addition to mastering the technologies, you’ll understand when they’re needed and how to use them. Chapter 2 - Front End Recipes Whether you are a beginner or intermediate web developer, if you wish to make good interactive web applications, then this chapter is for you. In this chapter, you’ll be getting some recipes about front-end web technologies and popular front end tools. These recipes cover best practices and modern techniques for front-end development such as: integrating Twitter Bootstrap, AJAX loading, notifications, cropping images, file uploads and many more. By the end, you should have a better understanding of how to work with AJAX, Jquery, front end frameworks and responsive design. You can apply these techniques to build beautiful applications and add that interactivity to any site you work on. Chapter 3 - Deployment Recipes After learning some tricky topics to successfully build a full stack application, it’s time to deploy your app. This chapter contains some helpful recipes about working with Heroku, Digital Ocean, etc. Deploy your applications blazingly fast using GIT and secret techniques are also discussed in the book! Book Description 4 Feedback Feedback from our readers is always welcome. Let us know what you liked or may have disliked. Simply send an email to [email protected]. We’re always here. Translation We’re also looking for translators who can help to translate our book to other languages. Feel free to contact us at [email protected]. Here is a list of our current translators: List of Translatorsš Book Status, Changelog and Contributors You can always check the book status, changelog and view the list of contributors at: Book Status² ChangelogÂł Contributors⁴ šhttp://learninglaravel.net/books/laravelcookbook/cookbook-translators ²http://learninglaravel.net/books/laravelcookbook/cookbook-status Âłhttp://learninglaravel.net/books/laravelcookbook/cookbook-changelog ⁴http://learninglaravel.net/books/laravelcookbook/cookbook-contributors Changelog Current Version Latest version the book: • Version: 0.20 • Status: Complete (Beta Version) • Updated: May 15th, 2016 5 Laravel 5 Cookbook 6 Chapter 1: Back End Recipes Introduction Building APIs and large applications using modern technologies can be a daunting task. In this chapter, you’ll learn best practices and modern techniques for back-end development, starting with an introduction to the command line and Git. These complete, easy-to-use recipes show you how to use cookies, sessions, web storage and some popular Laravel packages. You’ll also learn about writing APIs and debugging techniques. In addition to mastering the technologies, you’ll understand when they’re needed and how to use them. Project Files All project files of this book can be downloaded at: https://github.com/LearningLaravel/cookbook/releases⁾ At the end of each recipe, you can find the recipe’s project files (Tag). Feel free to use each of them at any stage of your development process. List Of Recipes Note: As this is a cookbook, you may skip any recipe that you know already. The book is still under active development, that means some chapters and its recipes may change. The book also may have some errors and bugs. For any feedback, please send us an email. Backend recipes • Recipe 1 - Introducing CLI (Command Line Interface) • Recipe 2 - All About Git • Recipe 3 - Build A Laravel Starter App • Recipe 4 - Create A User Authentication System with Facebook and Socialite ⁾https://github.com/LearningLaravel/cookbook/releases 7 Chapter 1: Back End Recipes 8 • Recipe 5 - Create A User Authentication System Using Laravel Auth Scaffold • Recipe 6 - Image Upload In Laravel • Recipe 7 - Seeding Your App Using Faker • Recipe 8 - Pagination • Recipe 9 - Testing Your App • Recipe 10 - Writing APIs with Laravel • (More recipes will be added later) Recipe 1 - Introducing CLI (Command Line Interface) Laravel 5 Cookbook contains many recipes to create interactive web applications. These recipes are premium tutorials for web developers of all skill levels. For most of the recipes in this book, you will need to use Git to install sample code and Homestead to execute your code. If you don’t have Homestead installed yet, you can follow these instructions to install it: http://learninglaravel.net/laravel5/installing-laravel Working with Laravel and GIT requires a lot of interactions with the CLI, thus you will need to know how to use it. What will we learn? This recipe shows you how to use the command line on PC and Mac. CLI for MAC OSX Luckily, on Mac, you can find a good CLI called Terminal at /Applications/Utilities. Most of what you do in the Terminal is enter specific text strings, then press Return to execute them. Alternatively, you can use iTerms 2⁜. ⁜https://www.iterm2.com Chapter 1: Back End Recipes 9 Iterm inteface CLI for Windows Unfortunately, the default CLI for Windows (cmd.exe) is not good, you may need another one. The most popular one called Git Bash. You can download and install it here: http://msysgit.github.io⁡ Most of what you do in Git Bash is enter specific text strings, then press Enter to execute them. CLI for Linux On Linux, the CLI is called Terminal or Konsole. If you know how to install and use Linux, I guess you’ve known how to use the CLI already. ⁡http://msysgit.github.io Chapter 1: Back End Recipes 10 Recipe 2 - All About Git There’s a chance you may already know about Git! Today, most programmers prefer Git over other distributed version control systems. What will we learn? This recipe introduces Git and provides a list of some important Git commands to get you going with Git. What is Version Control? Version Control System (VCS) let you store different versions of your projects and all its files. You can roll back to an earlier version or take a look at an older snapshot to see which files have been changed. Here is a nice infographic about Version Controler System: Iterm inteface Chapter 1: Back End Recipes 11 Why do you need to use Git? Git is becoming an ‘industry standard’. If you want to become a better developer, you may need to use Git to develop software and collaborate with other developers. Git lets you manage code development in a virtually endless variety of way. Here are benefits of using Version Control System/Git: • Git allows you to create as many branches of your project as you want. You can use each branch to test, create a new feature, fix bugs, etc. • You can see what was changed in your project’s files. This helps you understand what happened and improve your code. • You can easily store all the versions of your site and restore previous versions whenever you want. • Store your files on cloud-based Git repository host services like Github and Bitbucket. • You can easily share your files with others. • A VCS or Git helps your team work more efficiently. Everyone knows what is going on and can merge the changes into a common version. How to install Git? Note: if you don’t know how to run a command, please read the Recipe 1 - Introducing CLI (Command Line Interface). Install Git on Mac The easiest way is to install the Xcode Command Line Tools. You can do this by simply running this command: 1 xcode-select --install Click Install to download Command Line Tools package. Alternatively, you can also find the OSX Git installer at this website: http://git-scm.com/download/mac⁸ Install Git on Windows You can download GitHub for Windows to install Git: https://windows.github.com⁚ Install Git on Linux/Unix You can install Git by running this command: ⁸http://git-scm.com/download/mac ⁚https://windows.github.com Chapter 1: Back End Recipes 12 1 sudo yum install git If you’re on a Debian-based distribution, use this: 1 sudo apt-get install git For more information and other methods, you can see this guide: https://git-scm.com/book/en/v2/Getting-Started-Installing-Gitš⁰ Configuring Git When you first install Git, you should set your name, email address and enable coloring to pretty up command outputs. Open your CLI and run these commands: 1 git config --global user.name "Your Name" 2 git config --global user.email "Your Email Address" 3 git config --global color.ui auto Note: Remember to replace Your Name and Your Email Address. Start versioning your project using Git Git is very simple to use. First, you need to go to your working directory: 1 cd Code/Laravel Note: If you’re using Homestead, the Code directory is where we will put our Laravel apps. Code/Laravel is your working directory. You can use Git on Homestead or on your local machine, it’s up to you. Now we can use the git init command to initialize Git: 1 git init This command creates an empty Git repository. If you’re using Homestead, the path of the Git directory is: š⁰https://git-scm.com/book/en/v2/Getting-Started-Installing-Git Chapter 1: Back End Recipes 13 1 /home/vagrant/Code/Laravel/.git/ “.git” is a hidden folder and it doesn’t contain your project’s files yet. Add and commit your files Now we can use git status command to check the status of our working directory: 1 git status You will see a list of untracked files, that means Git doesn’t monitor those files yet. Untracked files To tell Git that you want to include all these files, use the git add -A command: 1 git add -A Note: Alternatively, you can use git add –a or git add –all or git add . command. Chapter 1: Back End Recipes 14 When we run the git status command again, you’ll see: Add files The git add command tells git to add changes in your project to the staging area. However, those changes aren’t saved yet until you run git commit: 1 git commit -m "First commit" You can use the -m flag (stands for message) to give a comment on the command line. My message is “First commit”, but you can use whatever you like. Well done! You’ve made your first commit! Chapter 1: Back End Recipes 15 Store your files on Git repository host services You can store all your files on cloud-based Git repository host services and access them anywhere, anytime. The two most popular services are Githubšš and Bitbucketš². We’ll use Github in this book, but feel free to use what you like. Let’s register an account on Github if you don’t have one yet. After that, click the New repository button to create a new repository. New repository This repository contains all your project’s files. ššhttp://github.com š²http://bitbucket.org Chapter 1: Back End Recipes 16 Creata a new repository When creating a new repository, you can choose any name that you like. Choose Private if you don’t want anyone access your files. Note: Don’t worry too much about the settings, you can change those settings later. Click Create repository to confirm. Great! You now have a new Github repository! Push your project to Github You should see Github’s quick setup guide: Chapter 1: Back End Recipes 17 Creata a new repository Your new repository (repo) is empty. You need to upload your files to that Github repo. Every repository has a unique remote URL, your remote URL should look like this: https://github.com/YourGithubUsername/YourRepoName.git Take note of this link. Good! We will try to upload our Laravel app (/Code/Laravel) to Github. Navigate to the working directory (on your Homestead or local machine): 1 cd /Code/Laravel Add a new remote by using git remote add command: 1 git remote add origin https://github.com/LearningLaravel/Laravel.git origin is the remote name, https://github.com/LearningLaravel/Laravel.git is the remote URL. Note: Your remote URL should be different. Be sure to use your remote URL. After adding a new remote, we can push our files to Github using the git push command: 1 git push -u origin master If it asks for a password, enter your Github password. origin is the remote that we’ve just added. master is your working directory. When we use the -u (stands for upstream) flag, we add the upstream reference. If we successfully push our files to the repo, Git will remember it, so we don’t have to type origin master next time. That means, if we want to upload our files again, we can just type: Chapter 1: Back End Recipes 18 1 git push You now have your files on the cloud! Cloning a repository To download any repo, you can use the git clone command. First, navigate to the location where you want to place the cloned directory: 1 cd Code Type git clone and the unique remote URL to clone the repo: 1 git clone https://github.com/YourGithubUsername/YourRepoName.git This command creates a local clone of the repository on your computer. Note: you can clone any public repository. If you don’t want anyone to download your repo, set it private. Recipe 2 Wrap-up In this recipe, you learned some major Git commands. Throughout this book, we’ll use Git to download the source code, front end components and deploy our Laravel applications. We won’t talk about it anymore because this is a Laravel book, not a Git book. If you wish to learn more about Git, check these sites out: Atlassian Git Tutorialsš³ Git-Towerš⁴ Codeschool - Try Gitš⁾ Super Useful Need To Know Git Commandsš⁜ It’s time to start learning about Laravel! š³https://git-scm.com/book/en/v2/Getting-Started-Installing-Git š⁴https://www.git-tower.com/learn/git/ebook š⁾https://www.codeschool.com/courses/try-git š⁜http://zackperdue.com/tutorials/super-useful-need-to-know-git-commands Chapter 1: Back End Recipes 19 Recipe 3 - Build A Laravel Starter App What will we learn? We will build a simple app and use it as a template for our next recipes. Throughout this process, we will learn how to run multiple Laravel sites on Homestead and how to integrate Twitter Bootstrap into our apps. Installing Laravel Let’s start by installing Laravel! Note: Please note that I’m using Homestead. If you don’t use Homestead, the process could be different. First, SSH into our Homestead: 1 vagrant ssh Then navigate to our Code directory. 1 cd Code Be sure to have the latest version of Laravel Installer by running this command: 1 Composer global require "laravel/installer" New repository Now let’s create a new cookbook app: Chapter 1: Back End Recipes 20 1 laravel new cookbook Great! You should have a new Laravel app! Feel free to change the name of the app to your liking. Note: If you’re not familiar with this process, please read the Learning Laravel 5 book. Create multiple Laravel apps on Homestead You can’t access your new app because Homestead doesn’t know about it yet. Therefore, let’s follow these steps to activate your site: Note: Be sure to backup your current projects’ files and databases. First, we have to go to the Homestead directory: 1 cd ~/.homestead And edit the Homestead.yaml file: 1 vim Homestead.yaml We use VIM to edit the file. If you don’t know how to use VI or VIM, you can open it with your favorite editor by using this command: 1 open Homestead.yaml Find: 1 sites: 2 - map: homestead.app 3 to: /home/vagrant/Code/Laravel/public Just a quick reminder, this section allows us to map a domain to a folder on our VM. For example, we can map homestead.app to the public folder of our Laravel project, and then we can easily access our Laravel app via this address: “http://homestead.app”. Our new app is called cookbook, and I would like to access it via this address:“http://cookbook.app”. So, let’s add the following code: Chapter 1: Back End Recipes 21 1 - map: cookbook.app 2 to: /home/vagrant/Code/cookbook/public Save the file. Tip: if you’re using VIM, press ESC and then write :wq (write quit) to save and exit Remember that, when we add any domain, we must edit the hosts file on our local machine to redirect requests to our Homestead environment. On Linux or Mac, you can find the hosts file at etc/hosts or /private/etc/hosts. You can edit the hosts file using this command: 1 sudo vim /private/etc/hosts On Windows, you can find the hosts file at C:WindowsSystem32\drivers\etc\hosts. After opening the file, we need to add this line at the end of the file: 1 192.168.10.10 cookbook.app Note: All sites will be accessible by HTTP via port 8000 and HTTPS via port 44300 by default. To let the system know that we’ve edited the hosts file, run this command: 1 source /private/etc/hosts Finally, SSH into our Homestead (by using vagrant ssh or homestead ssh), and use the serve command to activate our new site: 1 serve cookbook.app /home/vagrant/Code/cookbook/public/ Good job! If everything is working correctly, we should see our app’s home page: Chapter 1: Back End Recipes 22 New home page Creating Our Home Page Note: If you don’t understand any step in this section, be sure to check out the Learning Laravel 5 book. If you don’t want to follow along, you may skip these steps and download the sample app at the end of this recipe. We will create a new home page for our app. First, let’s create a home view (views/home.blade.php) for our homepage: Chapter 1: Back End Recipes 23 1 2 3 Home Page 4 5 7 8 40 41 42
Chapter 1: Back End Recipes 24 43
44
Home Page
45
Our Home page!
46
47
48 49 After that, generate a new PagesController: 1 php artisan make:controller PagesController Open PagesController, which can be found at app/Http/Controllers, and create a new home action: 1 ?php namespace App\Http\Controllers; 2 3 use App\Http\Requests; 4 use App\Http\Controllers\Controller; 5 6 use Illuminate\Http\Request; 7 8 class PagesController extends Controller { 9 10 public function home() 11 { 12 return view('home'); 13 } 14 15 } When you have the PagesController, the next thing to do is modifying our routes! Open routes.php file. Change the default route to: 1 Route::get('/', 'PagesController@home'); Great! We should now have a new home page! Chapter 1: Back End Recipes 25 New home page Integrating Twitter Bootstrap Nowadays, the most popular front-end framework is Twitter Bootstrap. It’s free, open source and has a large active community. Using Twitter Bootstrap, we can quickly develop responsive, mobile-ready web applications. Millions of beautiful and popular sites across the world are built with Bootstrap. In this section, we will learn how to integrate Twitter Bootstrap into our Laravel application. You can get Bootstrap and read its official documentation here: http://getbootstrap.com¹⁷ There are three ways to integrate Bootstrap: 1. Using Bootstrap CDN 2. Using Precompiled Bootstrap Files 3. Using Bootstrap Source Code (Less) ¹⁷http://getbootstrap.com Chapter 1: Back End Recipes 26 In this book, we will use the first one (using Bootstrap CDN). This is also the fastest method. Let’s open home.blade.php, remove the Lato font and these css styles: 1 3 4 Place these links inside the head tag Chapter 1: Back End Recipes 27 1 3 5 6 7 Done! You now have fully integrated Twitter Bootstrap into our app! Create a master layout, app navigation bar and other pages It’s time to create a master layout (master.blade.php) for our app: 1 2 3 @yield('title') 4 6 8 9 10 12 13 14 15 @include('shared.navbar') 16 17 @yield('content') 18 19 20 Next, create a new navbar view and place it at shared/navbar.blade.php: Chapter 1: Back End Recipes 28 1 We can now change our home view to extend the master layout. Chapter 1: Back End Recipes 29 1 @extends('master') 2 @section('title', 'Home') 3 4 @section('content') 5
6
7
Home Page
8
Our Home page!
9
10
11 @endsection Refresh your browser, we should have a new home page with a nice navigation bar: New home page We can then continue to create the about and contact page: about view (about.blade.php): Chapter 1: Back End Recipes 30 1 @extends('master') 2 @section('title', 'About') 3 4 @section('content') 5
6
7
About Page
8
Our about page!
9
10
11 @endsection contact view (contact.blade.php): 1 @extends('master') 2 @section('title', 'Contact') 3 4 @section('content') 5
6
7
Contact Page
8
Our contact page!
9
10
11 @endsection Edit the routes.php file. Add the following lines: 1 Route::get('/about', 'PagesController@about'); 2 Route::get('/contact', 'PagesController@contact'); Please note that we’re using Laravel 5.2, so we need to add these routes into the web middleware group: 1 Route::group(['middleware' => ['web']], function () { 2 Route::get('login/facebook', 'Auth\AuthController@redirectToFacebook'); 3 Route::get('login/facebook/callback', 'Auth\AuthController@getFacebookCallba\ 4 ck'); 5 }); Open PagesController, add: Chapter 1: Back End Recipes 31 1 public function about() 2 { 3 return view('about'); 4 } 5 6 public function contact() 7 { 8 return view('contact'); 9 } Congratulations! You’ve just taken the first step in building awesome Laravel applications! Note: If you’re using Git, this is a good time to initialize your repo with git init. This will be our starter template. Recipe 3 Wrap-up Tag: Version 0.1 - Recipe 3¹⁸ Good job! We’ve got our app running. As you can see, our main app template is very simple and it isn’t what we really want. Therefore, let’s start adding more features into it! Recipe 4 - Create A User Authentication System with Facebook and Socialite What will we learn? We will learn how to use Socialite - a new Laravel 5 feature - to let users log in using their Facebook account. After learning this recipe, you may apply the technique to authenticate users with other social networks (Twitter, Github, Gmail, etc.) as well. ¹⁸https://github.com/LearningLaravel/cookbook/releases/tag/v0.1 Chapter 1: Back End Recipes 32 Installing Socialite In most web frameworks, authenticating users using 3rd party providers is never as easy as it could be. Luckily, Laravel 5 provides a simple way to authenticate with OAuth providers using Socialite. Currently, Socialite officially supports authentication with Facebook, GitHub, Google, Twitter and Bitbucket. If you want to use Socialite with other providers (Youtube, Wordpress, etc.), check out SocialiteProviders¹⁹, which is a collection of OAuth 1 and 2 packages that extends Socialite. Actually, Socialite is an official package, and it’s not included in Laravel by default. To use Socialite, we have to install it by running this command: 1 composer require laravel/socialite Alternatively, you may edit the composer.json file, add below code into the require section and run composer update: 1 "laravel/socialite": "~2.0" Next, open config/app.php. Add the following line into the providers array: 1 Laravel\Socialite\SocialiteServiceProvider::class, Add the Socialite facade into the aliases array: 1 'Socialite' => Laravel\Socialite\Facades\Socialite::class, Done! Socialte is now ready to use! Create a Facebook app In order to use Facebook as our authentication provider, we must create a Facebook app. Don’t worry, it’s very simple. First, let’s go to: https://developers.facebook.com Register a Facebook account or login if you have one already. There is an Account Menu at the top right corner of the page. ¹⁹https://socialiteproviders.github.io Chapter 1: Back End Recipes 33 New home page Click Add a New App and choose Website to create a Facebook app. Alternatively, you can access this link: https://developers.facebook.com/quickstarts/?platform=web Enter your app’s name and click Create New Facebook App ID: Chapter 1: Back End Recipes 34 New home page Choose a Category for your app and then click Create App ID Click Skip Quick Start to access your App Dashboard New home page That’s it! You can get your App ID and App Secret here. Create a Facebook Test App If you’re working on Homestead, you will have to create a Test App to test the authentication locally. Find the Test Apps button, which is on the left menu: Chapter 1: Back End Recipes 35 Create a test app Follow the instructions to create a test app. You can name the app whatever you want. After that, click Settings -> Add Platforms -> Website Enter your app URL into the Site URL field. (For example, cookbook.app) Chapter 1: Back End Recipes 36 Add platform and app domain Enter your app URL into the App Domains field, too. Click Save Changes to update your Test App. Well done! Don’t forget to grab your Test App ID and Test App Secret. Tell Laravel about your Facebook app After creating your Facebook app, you can connect it to your Laravel app by simply editing the config/services.php file. Add this: 1 'facebook' => [ 2 'client_id' => 'yourFacebookAppID', 3 'client_secret' => 'yourFacebookAppSecret', 4 'redirect' => 'http://yourLaravelAppURL/login/facebook/callback', 5 ], If you’re using the .env config file, you may use the following instead: Chapter 1: Back End Recipes 37 1 'facebook' => [ 2 'client_id' => env('FACEBOOK_ID'), 3 'client_secret' => env('FACEBOOK_SECRET'), 4 'redirect' => env('FACEBOOK_URL'), 5 ], Edit your .env files: 1 FACEBOOK_ID=yourFacebookAppID 2 FACEBOOK_SECRET=yourFacebookAppSecret 3 FACEBOOK_URL=http://yourLaravelAppURL/login/facebook/callback Done! Laravel automatically detects your Facebook app information and prepares everything for you! Note: If you’re using Homestead, use your Test App ID and Secret. Update Users Migration We have to update our database to store users’ Facebook Unique ID and other related information. This is a new app, so we just need to update the create_users_table migration. Note: Laravel includes the create_users_table by default (2014_10_12_000000_create_- users_table.php), we don’t need to create it. Open database/migrations/timestamps_create_users_table.php file and update the up method: 1 public function up() 2 { 3 Schema::create('users', function (Blueprint $table) { 4 $table->increments('id'); 5 $table->string('facebook_id')->unique(); 6 $table->string('name'); 7 $table->string('email')->unique(); 8 $table->string('password', 60); 9 $table->rememberToken(); 10 $table->timestamps(); 11 }); 12 } This migration will create a new users table with the facebook_id column. If you have an existing app, you have to create a new migration to update the users table: Chapter 1: Back End Recipes 38 1 php artisan make:migration update_users_table Open the update_users_table file and update the code as follows: 1 string('facebook_id')->unique(); 15 }); 16 } 17 } 18 19 public function down() 20 { 21 Schema::table('users', function ($table) { 22 $table->dropColumn('facebook_id'); 23 }); 24 } 25 } Next, don’t forget to run php artisan migrate to update your database. Note: If you don’t have a database yet, create a new one. The name of our database is cookbook. If you wish to learn more about working with databases, read Learning Laravel 5 book’s Chapter 3²⁰. One last step, open app/User.php file and update our User Model: ²⁰http://learninglaravel.net/laravel5/building-a-support-ticket-system Chapter 1: Back End Recipes 39 1 protected $fillable = [ 2 'name', 'email', 'password', 'facebook_id', 3 ]; Update our Routes and AuthController We will need two routes: 1. A route that redirects users to our OAuth provider, which is Facebook. 2. Another route that receives a response (callback) from Facebook. Let’s open our routes.php file and add these routes: 1 Route::get('login/facebook', 'Auth\AuthController@redirectToFacebook'); 2 Route::get('login/facebook/callback', 'Auth\AuthController@getFacebookCallback'); When users visit http://cookbook.app/login/facebook, Laravel redirects users to Facebook and receive the callback at this route http://cookbook.app/login/facebook/callback. Easy? Now we need to create two controller methods, open Auth/AuthController, add: The redirectToFacebook method: 1 public function redirectToFacebook() 2 { 3 return Socialite::with('facebook')->redirect(); 4 } The getFacebookCallback method: 1 public function getFacebookCallback() 2 { 3 4 $data = Socialite::with('facebook')->user(); 5 $user = User::where('email', $data->email)->first(); 6 7 if(!is_null($user)) { 8 Auth::login($user); 9 $user->name = $data->user['name']; 10 $user->facebook_id = $data->id; Chapter 1: Back End Recipes 40 11 $user->save(); 12 } else { 13 $user = User::where('facebook_id', $data->id)->first(); 14 if(is_null($user)){ 15 // Create a new user 16 $user = new User(); 17 $user->name = $data->user['name']; 18 $user->email = $data->email; 19 $user->facebook_id = $data->id; 20 $user->save(); 21 } 22 23 Auth::login($user); 24 } 25 return redirect('/')->with('success', 'Successfully logged in!'); 26 } Note: Facebook now returns a full name instead of first name and last name. We have to use $data->user[‘name’] to get the name of the user. Because we’re using the Socialite facade and the Auth facade, be sure to tell Laravel about them. Find: 1 class AuthController extends Controller Add above: 1 use Socialite; 2 use Auth; Done! We can now be able to log in or register a new account using Facebook. Login or register using Facebook Now, let’s visit this link: http://cookbook.app/login/facebook We’ll be redirected to Facebook for authentication. If everything is ok, Facebook will redirect us back to our application. Check our users table using Sequel Pro or your favorite database management app, we should see a new user has been created. Just for testing purposes, let’s modify our home page: Chapter 1: Back End Recipes 41 1 @section('content') 2
3
4
Home Page
5 @if(!Auth::check()) 6
Our Home page!
7 @else 8
You are now logged in!
9 @endif 10
11
12 @endsection We use Auth::check() to check if the user is already logged into our application. If the user is authenticated, we display the You are now logged in message. Once again, because we’re using Laravel 5.2, we have to put our routes into the web middleware group to use Session. The routes.php should look like this: 1 Route::group(['middleware' => ['web']], function () { 2 Route::get('login/facebook', 'Auth\AuthController@redirectToFacebook'); 3 Route::get('login/facebook/callback', 'Auth\AuthController@getFacebookCallba\ 4 ck'); 5 6 Route::get('/', function () { 7 return view('home'); 8 }); 9 10 Route::get('/about', 'PagesController@about'); 11 Route::get('/contact', 'PagesController@contact'); 12 13 Route::get('users/register', 'Auth\AuthController@getRegister'); 14 Route::post('users/register', 'Auth\AuthController@postRegister'); 15 16 }); Save the changes and reload our home page, we should see: Chapter 1: Back End Recipes 42 New home page Note: The users/register routes are optional. You may use them to build a registration page to create test users (Recipe 203 or Learning Laravel 5 book’s Chapter 4) and test the Facebook login feature. If you don’t need them, you may just remove them. Recipe 4 Wrap-up Tag: Version 0.2 - Recipe 4²¹ That’s it! You can now log in or register a new member using Facebook. Using this technique, you can use Socialite to authenticate users with other providers! By default, your Facebook app is in development mode (aka sandbox mode). Don’t forget to make your app live and use the real App ID and App Secret. If you want to add a Facebook login button to your app, simply add the following to wherever you want: 1
Login with Facebook
Note: We use Font Awesome here. If you want to learn how to integrate Font Awesome, please read the next recipe. Recipe 5 also shows how to add the Facebook button into your login page. Recipe 5 - Create A User Authentication System Using Laravel Auth Scaffold What will we learn? This recipe shows you how to use Laravel 5.2’s Auth Scaffold to build a user authentication system that has: user signup, login/logout, password reset and user dashboard. ²¹https://github.com/LearningLaravel/cookbook/releases/tag/v0.2 Chapter 1: Back End Recipes 43 Generate the user authentication system Laravel 5.2 comes with a new auth scaffold that we can use to generate a complete user authentica tion system with just one line of code. Let’s start by running this Artisan command: 1 php artisan make:auth Make:auth command As you see, Laravel has generated some views, created a new HomeController and updated our routes.php file. Go ahead and reload our home page: Make:auth command With all this done, we now have a complete user authentication system! Understanding the auth scaffold When you run the Artisan command, these views are generated: • auth/login.blade.php - the login page • auth/register.blade.php - the signup page • auth/passwords/email.blade.php - the password reset confirmation page Chapter 1: Back End Recipes 44 • auth/passwords/reset.blade.php - the password reset page • auth/emails/password.blade.php - the password reset email • home.blade.php - the user dashboard page • welcome.blade.php - the new welcome page The routes.php has been changed: 1 Route::group(['middleware' => 'web'], function () { 2 Route::auth(); 3 4 Route::get('/home', 'HomeController@index'); 5 }); The home route (user dashboard) and HomeController are also created. The Routes::auth() method is used to define the login route, the register route and the password reset routes. You may realize that our home page and other pages now have a different master layout. The new layout is views/layouts/app.blade.php: 1 2 3 4 5 6 7 8 Laravel 9 10 11 13 15 16 17 19 {{-- --}} 20 21 30 31 32 81 82 @yield('content') 83 84 85 87 89 {{-- --}} 90 91 This master layout also has Bootstrap, jQuery, Font Awesome, Lato font and a navigation bar. Updating our app’s layout Now we’re going to update the current layout. We’ll use the old master layout that we’ve created because it’s much cleaner. First, clear the contents of views/layouts/app.blade.php. Next, copy the contents of views/master.blade.php into views/layouts/app.blade.php. To save time, you can copy the code below: Chapter 1: Back End Recipes 47 1 2 3 @yield('title') 4 6 8 9 10 12 13 14 15 @include('shared.navbar') 16 17 @yield('content') 18 19 20 Last step, open views/shared/navbar.blade.php and find: 1 Replace with: 1 Chapter 1: Back End Recipes 48 We now have a new layout. All the pages are still working fine. Login page To test out the new pages, you can try to register a new member, login and logout. Sadly, our app still has one bug. Let’s see what it is and how to fix it in the next section. Fixing the “new member” bug If you use Socialite, when you try to register a new member multiple times, you may encounter this error: New member error As you may have guessed, the facebook_id column should be unique. To fix this bug, open our AuthController file. Update the create method as follows: Chapter 1: Back End Recipes 49 1 protected function create(array $data) 2 { 3 return User::create([ 4 'name' => $data['name'], 5 'email' => $data['email'], 6 'password' => bcrypt($data['password']), 7 'facebook_id' => $data['email'], 8 ]); 9 } It’s fairly simple to fix. When users register a new account, their facebook id is set as their provided email, which should be unique. Now that we’ve taken care of the bug! Adding a Facebook login button So far, we’ve worked our way through building an awesome Facebook user authentication. Let’s add a Facebook login button to our login and register page, when users click on that button, they can be able to log into our app. First, open views/auth/login.blade.php, and find: 1 Add the Facebook login button below: 1
Login with Facebook
Next, open views/auth/register.blade.php, and find: 1 Add the Facebook login button below: Chapter 1: Back End Recipes 50 1
Login with Facebook
We’re using Font Awesome here, so let’s add the following inside of our master layout’s head tag to integrate Font Awesome: 1 Now we can see a nice Facebook login button: Login Facebook button Recipe 5 Wrap-up Tag: Version 0.3 - Recipe 5²² Our user authentication system is working perfectly! Please note that there are many ways to implement authentication, this is just a quick look at implementing a good basis of authentication for our application. If you have time, try to create a user authentication system manually to understand more about it. Recipe 6 - Image Upload In Laravel What will we learn? This recipe shows you how to upload and handle images in Laravel 5. ²²https://github.com/LearningLaravel/cookbook/releases/tag/v0.3 Chapter 1: Back End Recipes 51 Installing Intervention Image Intervention Image is one of the most popular open source PHP image handling and manipulation libraries. Using the package, you can easily create, edit and compose images. The best thing is, Intervention Image doesn’t require Laravel or any other framework, it only needs the following components to work correctly: • PHP >= 5.4 • Fileinfo Extension • GD Library (>=2.0) or Imagick PHP extension (>=6.5.7) To install Intervention Image, run the following command: 1 composer require intervention/image Next, open your config/app.php file. Add the following line into your $providers array: 1 Intervention\Image\ImageServiceProvider::class, Add this Intervention Image’s facade into your ** $aliases ** array: 1 'Image' => Intervention\Image\Facades\Image::class, Intervention Image supports both PHP’s GD library and Imagick extension. You can choose which one that you want to use in Intervention Image’s configuration file. Let’s generate the configuration file by running this command: 1 php artisan vendor:publish --provider="Intervention\Image\ImageServiceProviderLa\ 2 ravel5" The configuration file is copied to config/image.php. We did it! You can now use Intervention Image to manipulate all images! There’s lots more to learn: • Uploading images • Display images • Manipulating images (resize, crop, etc.) In the next section, we’re going to implement a cover image for our home page. Chapter 1: Back End Recipes 52 Creating an upload form Let’s start by building an Image Upload form. To keep things simple, let’s put the form at our home page. Here’s the very beginnings of our home view (home.blade.php): 1 @extends('layouts.app') 2 3 @section('content') 4 5
6
7
8
9 10
Dashboard
11 12
13 14
16 17 @foreach ($errors->all() as $error) 18

{{ $error }}

19 @endforeach 20 21 @if (session('status')) 22
23 {{ session('status') }} 24
25 @endif 26 27 {!! csrf_field() !!} 28 29
30 31 32
33 34
40
41
42
43
44 @endsection As you see, we’ve just inserted a new form: 1
2 3 @foreach ($errors->all() as $error) 4

{{ $error }}

5 @endforeach 6 7 @if (session('status')) 8
9 {{ session('status') }} 10
11 @endif 12 13 {!! csrf_field() !!} 14 15
16 17 18
19 20 21 22
Please keep in mind that when you upload a file, you need to include this line in your form: 1 enctype="multipart/form-data" Just a quick reminder, we display the errors when the form is not valid. If the validator fails, Laravel will store all errors in the session. We can easily access the errors via $errors object: Chapter 1: Back End Recipes 54 1 @foreach ($errors->all() as $error) 2

{{ $error }}

3 @endforeach We also display a status message if the image is uploaded successfully: 1 @if (session('status')) 2
3 {{ session('status') }} 4
5 @endif Note: If you want to learn more about how to work with forms, read the Learning Laravel 5 book’s Chapter 3²³ Now we can see the upload form in our browser: Upload image form Storing images To validate the form, we will create a new ImageFormRequest: 1 php artisan make:request ImageFormRequest Go ahead and define the form’s rules here: ²³http://learninglaravel.net/laravel5/building-a-support-ticket-system Chapter 1: Back End Recipes 55 1 'required', 28 ]; 29 } 30 } The next step is to wire the form to a controller and process it. Let’s generate a new ImagesController: 1 php artisan make:controller ImagesController Next, create a store action to handle images: Chapter 1: Back End Recipes 56 1 public function store(ImageFormRequest $request) 2 { 3 4 if ($request->hasFile('image')) { 5 6 $file = $request->file('image'); 7 8 $name = $file->getClientOriginalName(); 9 10 $file->move(public_path() . '/images/', $name); 11 12 return redirect('/')->with('status', 'Your image has been uploaded s\ 13 uccessfully!'); 14 } 15 16 } That seems overwhelming at first, but it’s actually very easy to understand. First, we check if the form has a file (image) or not: 1 if ($request->hasFile('image')) { Once the validation is done, we may retrieve all of the input data using: 1 $file = $request->file('image'); Now we can get the image’s name: 1 $name = $file->getClientOriginalName(); Sweet! If everything looks good, we can store the file at our public/images folder: 1 $file->move(public_path() . '/images/', $name); Finally, redirect users back to our home page and display a status message: 1 return redirect('/')->with('status', 'Your image has been uploaded successfully!\ 2 '); Here is the entire ImagesController file: Chapter 1: Back End Recipes 57 1 hasFile('image')) { 14 15 $file = $request->file('image'); 16 17 $name = $file->getClientOriginalName(); 18 19 $file->move(public_path() . '/images/', $name); 20 21 return redirect('/')->with('status', 'Your image has been uploaded s\ 22 uccessfully!'); 23 } 24 25 } 26 } The last thing we need to do is create a route: 1 Route::post('upload', 'ImagesController@store'); Well done! Now when users make a POST request to this route, Laravel will execute the ImagesController’s store action. Let’s test what we’ve just made to make sure that it works properly: Chapter 1: Back End Recipes 58 Sample image I will try to upload this image, you may download it at: Laravel Cookbook Image²⁴ Note: Feel free to use your own image. Let’s view the site in your browser and try to upload the image: Upload image successfully Check your public/images directory, you will see the image there. Displaying images This is the simple part. Once we have that image file, we can easily display it on our home page. Open home.blade.php, find: 1
Dashboard
Add below: ²⁴images/chap1-pic24.png Chapter 1: Back End Recipes 59 1
Now we should be able to see our image: Cover image Note: If you’re using your own image, be sure to change the file name. Manipulating images What’s the point in installing Intervention Image if we don’t use it? It’s time to use “the power” of Intervention Image to manipulate our images! Note: We talked about Intervention Image earlier and this will be your first use of it. Let’s start by telling Intervention Image where our image is. First, open the ImagesController and find: 1 if ($request->hasFile('image')) { 2 3 $file = $request->file('image'); 4 5 $name = $file->getClientOriginalName(); 6 7 $file->move(public_path().'/images/', $name); Add below: Chapter 1: Back End Recipes 60 1 $imagePath = public_path().'/images/'.$name; When we have the path of our image, this is how we resize the image: 1 $image = Image::make($imagePath)->resize(1000, 250)->save(); Now try to upload the image again and check its size. The image should be resized to 1000x250 px: New image size Super simple stuff! The beauty of Intervention Image is that you can do many things more: crop, blur, flip, sharpen, etc. Don’t forget to take a look at the Intervention Image’s API: http://image.intervention.io²⁵ Now let’s try to use one more API: 1 $image = Image::make($imagePath)->resize(1000, 250)->greyscale()->save(); Greyscale API ²⁵http://image.intervention.io/ Chapter 1: Back End Recipes 61 As you see, the image has been converted to grayscale! This is what’s so cool about Intervention Image! Recipe 6 Wrap-up Tag: Version 0.4 - Recipe 6²⁶ Image upload is a hard concept to grasp if you are new to Laravel development. However, by using Intervention Image and Laravel Request, we have just created our first image upload function! As you see, the syntax is fairly straightforward. Recipe 7 - Seeding Your App Using Faker What will we learn? This recipe shows you how to use Faker - a popular PHP library - to generate fake data for testing purposes. What is Faker? Faker is a PHP library that we use to generate dummy data. It can be used to generate all sorts of data for testing purposes or bootstrapping our applications. If you’re using Laravel 5.1 or newer, the Faker library has been already installed by default. If you’re an old version of Laravel, you can install Faker by running this Composer command: 1 composer require fzaninotto/faker Faker can be used to generate: • Random Digit • Word • Paragraph • Name • City • Year • Domain Name • Credit Card Number ²⁶https://github.com/LearningLaravel/cookbook/releases/tag/v0.4 Chapter 1: Back End Recipes 62 … and many more. For more information, please visit Faker’s official documentation: https://github.com/fzaninotto/Faker²⁷ Creating blog posts using Faker Here is a quick overview of how to use Faker. The first step is creating our Post model and its migration: 1 php artisan make:model Post -m Note: You can generate the Post model and its migration at the same time by adding the -m option. Open timestamp_create_posts_table.php, which can be found in the migrations directory. Update the up method and the down method as follows: 1 public function up() 2 { 3 Schema::create('posts', function (Blueprint $table) { 4 $table->increments('id'); 5 $table->string('title', 255); 6 $table->text('content'); 7 $table->string('slug')->nullable(); 8 $table->tinyInteger('status')->default(1); 9 $table->integer('user_id'); 10 $table->timestamps(); 11 }); 12 } 13 14 public function down() 15 { 16 Schema::drop('posts'); 17 } Don’t forget to run: ²⁷https://github.com/fzaninotto/Faker Chapter 1: Back End Recipes 63 1 php artisan migrate Your database should now have a new posts table. Just like we create our Post model, run this command to create a new PostsTableSeeder file: 1 php artisan make:seeder PostsTableSeeder Open the app/database/seeds/PostsTableSeeder.php file, update the run method as follows: 1 public function run() 2 { 3 $faker = Faker::create(); 4 5 foreach(range(1,20) as $index) 6 { 7 $title = $faker->text(80); 8 9 Post::create([ 10 'title' => $title, 11 'content' =>$faker->paragraph(30), 12 'slug' => Str::slug($title, '-'), 13 'status' => 1, 14 'user_id' => $faker->numberBetween($min = 1, $max = 5), 15 ]); 16 } 17 18 } It’s very easy to understand, right? Find: 1 class PostsTableSeeder extends Seeder Add above: 1 use App\Post; 2 use Faker\Factory as Faker; 3 use Illuminate\Support\Str; In our app/database/seeds/DatabaseSeeder.php, update the run method as follows: Chapter 1: Back End Recipes 64 1 public function run() 2 { 3 $this->call(PostsTableSeeder::class); 4 } The last part needed to seed data is to run this Artisan command: 1 php artisan db:seed Check your database, you should see 20 new posts: 20 new posts Display all blog posts Once we have the dummy data, we can create a blog page to view all blog posts. Let’s register a blog route by adding the following code to our routes.php file: 1 Route::get('/blog', 'BlogController@index'); We would need to create the BlogController: 1 php artisan make:controller BlogController Insert the following code into it: Find: 1 class BlogController extends Controller Tell Laravel that you want to use the Post model in this controller. Add above: Chapter 1: Back End Recipes 65 1 use App\Post; Next, add the index action: 1 public function index() 2 { 3 $posts = Post::all(); 4 return view('blog.index', compact('posts')); 5 } Create a new index view at views/blog directory. The following are the contents of the views/blog/in dex.blade.php file: 1 @extends('master') 2 @section('title', 'Blog') 3 @section('content') 4 5
6 7 @if (session('status')) 8
9 {{ session('status') }} 10
11 @endif 12 13 @if ($posts->isEmpty()) 14

There is no post.

15 @else 16 @foreach ($posts as $post) 17
18
{!! $post->title !!}
19
20 {!! mb_substr($post->content,0,500) !!} 21
22
23 @endforeach 24 @endif 25
26 27 @endsection Chapter 1: Back End Recipes 66 We use mb_substr (Multibyte String) function to display only 500 characters of the post. If you want to learn more about the function, visit: http://php.net/manual/en/function.mb-substr.php²⁸ We should add a blog link to our navigation bar to access the blog page faster. Open shared/- navbar.blade.php and find: 1
  • About
  • Add above: 1
  • Blog
  • Head over to your browser and visit the blog page. The blog page Recipe 7 Wrap-up Tag: Version 0.5 - Recipe 7²⁚ ²⁸http://php.net/manual/en/function.mb-substr.php ²⁚https://github.com/LearningLaravel/cookbook/releases/tag/v0.5 Chapter 1: Back End Recipes 67 You now know how to use Faker to generate good-looking dummy data! This technique can be applied to more than just posts. You can use it to create larger applications and test your apps. Recipe 8 - Pagination What will we learn? We will learn how to implement pagination in your Laravel application. Simple pagination Recently, we showed all blog posts in one page. Eventually, if thousands of posts are posted, this will become problematic. Pagination is a good solution to this overload issue. As you may know, creating pagination from scratch is not an easy task. Luckily, Laravel has a paginate method that we can use to create the pagination without having to write any extra code. Let’s open our BlogController, find: 1 $posts = Post::all(); Replace with: 1 $posts = Post::paginate(10); As you see, we use the paginate method to create the pagination. This will return an instance of IlluminatePaginationLengthAwarePaginator. Alternatively, you can use the new simplePaginate method. This will return an instance of IlluminatePaginationPaginatorThis Paginator class. 1 $posts = Post::simplePaginate(10); These objects provide several useful methods that we can use to customize and display our pagination. I want to display 10 posts on a page, so I put 10 as the parameter. If you would like to use Query Builder, you may write: Chapter 1: Back End Recipes 68 1 $posts = DB::table('posts')->paginate(10); For more information, be sure to read the official documentation: https://laravel.com/docs/master/pagination Next, open the blog/index.blade.php view and find: 1 @if ($posts->isEmpty()) 2

    There is no post.

    3 @else 4 @foreach ($posts as $post) 5
    6
    {!! $post->title !!}
    7
    8 {!! mb_substr($post->content,0,500) !!} 9
    10
    11 @endforeach 12 @endif Add below: 1 {!! $posts->render() !!} Good job! Let’s give our brand new pagination system a try: Pagination If you use the simplePaginate method, you should now see something like this: Simple Pagination Chapter 1: Back End Recipes 69 Additional helper methods The Paginator instances also have many useful methods that you can access: • $posts->count() • $posts->currentPage() • $posts->hasMorePages() • $posts->lastPage() (Not available when using simplePaginate) • $posts->nextPageUrl() • $posts->perPage() • $posts->previousPageUrl() • $posts->total() (Not available when using simplePaginate) • $posts->url($page) As Laravel is constantly updated, be sure to check the documentation to know all latest helper methods: https://laravel.com/docs/master/pagination³⁰ Ajax pagination When creating Ajax pagination, we will need to return the pagination as JSON. The Paginator classes implement the IlluminateContractsSupportJsonableInterface contract and have toJson method. That means you can easily convert the result instance to JSON by simply returning it from a route or controller action. Let’s try to return the pagination as JSON from our BlogController’s index action: 1 use Response; 2 class BlogController extends Controller 3 { 4 public function index() 5 { 6 $posts = Post::paginate(10); 7 $response = Response::json($posts,200); 8 return $response; 9 } 10 } ³⁰https://laravel.com/docs/master/pagination Chapter 1: Back End Recipes 70 Here is the new blog: Retuning the pagination as JSON Now let’s try to return the instance from a route. Open our routes.php file, add a new route: 1 Route::get('json', function () { 2 return App\Post::paginate(); 3 }); Visit cookbook.app/json, you should see: Chapter 1: Back End Recipes 71 Retuning the pagination as JSON from a route Recipe 8 Wrap-up Tag: Version 0.6 - Recipe 8³¹ Great! Having the knowledge of the above will let you create a simple pagination or ajax pagination in no time. Now this won’t do much for our app yet, but these techniques can be used to build many applications in all sorts of different styles. Recipe 9 - Testing Your App What will we learn? No code is safe! This recipe shows you how to do testing to make sure that everything is working like it’s supposed to. Why should we do testing? Most of the time, you can successfully deploy and run your apps without any problems. Unfortu nately, sometimes things might go terribly horribly wrong. That’s when you need testing skills to pinpoint at the right issues. ³¹https://github.com/LearningLaravel/cookbook/releases/tag/v0.6 Chapter 1: Back End Recipes 72 Testing is really boring and there’s a lot of code which is hard to unit test properly. That is true. However, not having a comprehensive test suite means that our applications may not meet the stated requirements and we’re taking more risks. “Even good programmers make mistakes. The difference between a good programmer and a bad one is that a good one detects it sooner by using automated tests” - Sebastian Bergmann That may sound a bit exaggerated, but we should know how to write and test our code effectively to improve the quality of our applications. To beginners of Laravel, testing can truly seem like a very difficult job. But don’t worry. Remember that, if you can write PHP, you can write tests. Now let’s get started and talk more about these concepts as we go along! Manual testing and automated testing There are many ways to test your app. When talking about testing, people usually think about automated test, but we can always go for a manual testing approach as well. • Manual Testing: is the process of running series of tasks manually to find the defects in our applications. • Automated Testing: is the process of using automated tools to run tests based on algorithms to check your applications. There are different types of automated tests. Here are the popular ones: • Unit tests • Integration tests • Acceptance tests (aka Functional tests) In this recipe, we will talk about some useful tools and techniques that we can use to manually test our app. We also learn about PHPUnit and write some automated tests to check our application. dd(), var_dump(), print_r() and Kint Laravel has a popular helper function that we can use to display structured information of the given variable and stop the script’s execution: dd(). Now let’s open our BlogController, and add this function to our index action: Chapter 1: Back End Recipes 73 1 public function index() 2 { 3 $posts = Post::paginate(10); 4 dd($posts); Visit our blog to see the changes: Use dd() function Using the paginate method, we will receive an instance of IlluminatePaginationLengthAwarePag inator. The dd() function helps us to see the contents of the instance. If you don’t get the instance or the information is not correct, then your app is probably having a bug somewhere. As you see, we can read the title and content of our posts (and many things more) without using Chapter 1: Back End Recipes 74 views to display it. We can also use the dd() function to dump the response object as well: 1 $response = Response::json($posts,200); 2 dd($response); Or we can just display a simple text: 1 dd("This is a test"); Amazing, right? You’ll be using this function a lot since it’s very useful for showing off data and debugging our app. Alternatively, we can use var_dump() and print_r() PHP function to display the information about a variable. These functions are very useful when working with arrays. W3resouce has a really good tutorial about them, you may check it out at: http://www.w3resource.com/php/function-reference/var_dump.php³² Recently, Kint - a powerful and modern PHP debugging tool - is also becoming very popular. It’s a good replacement for var_dump() and print_r(). Using Kint in conjunction with the dd() function is a powerful combination. You can install Kint by simply running this Composer command: 1 composer require raveren/kint Or add it into your composer.json file. 1 "require": { 2 "raveren/kint": "^1.0" 3 } For more information, check out Kint’s official home page: https://github.com/raveren/kint³³ ³²http://www.w3resource.com/php/function-reference/var_dump.php ³³https://github.com/raveren/kint Chapter 1: Back End Recipes 75 Useful tools, extensions and packages As PHP is the most popular open source server-side scripting language, it has ready-to-use tools, well-supported extensions, and free packages that can help us properly test, debug and optimize our application. Here is a list of interesting tools that I use when developing different types of applications: Developer Tools:³⁴ The Developer Tools are part of the open source Webkit project. They are bundled and available in Chrome, Safari, Opera and any Webkit browser. If you’re using Chrome, you should use Chrome Developer Tools (aka Chrome DevTools). The tools let you do many things: inspect elements, view raw html/css, manipulate DOM, debug local browser storage, etc. You can open the DevTools by right click and choose Inspect or use this shortcut: Ctrl + Shift + I (Windows), F12 (Windows), or Cmd + Opt + I (Mac) Chrome DevTools Want to learn how to use Devtools? CodeSchool has a nice video course about it (free): http://discover-devtools.codeschool.com³⁵ You may also check the Chrome Devtools’ documentation: https://developers.google.com/web/tools/chrome-devtools/iterate/inspect-styles/shortcuts ³⁶ vardumpling() extension:³⁷ This Google Chrome extension beautifies your var_dumps and makes them easier to read. ³⁴https://developers.google.com/web/tools/chrome-devtools/iterate/inspect-styles/shortcuts ³⁵http://discover-devtools.codeschool.com ³⁶https://developers.google.com/web/tools/chrome-devtools/iterate/inspect-styles/shortcuts ³⁷https://chrome.google.com/webstore/detail/vardumpling/aikblkmigebodlhkdepmfmgdgmbokkdn Chapter 1: Back End Recipes 76 vardumpling JSON Formatter extension:³⁸ Similar to the vardumpling extension, if you want to view JSON files directly on your browser, you’ll love this Chrome’s plugin. ³⁸https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa