Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Laravel Application Development Cookbook
Laravel Application Development Cookbook

Laravel Application Development Cookbook: Since Laravel is so versatile, one of the best learning routes is a cookbook. We've included lots of recipes and guidance on building web application, both simple and complex. It's a pick & mix approach that works brilliantly.

Arrow left icon
Profile Icon Terry Matula
Arrow right icon
Can$34.98 Can$49.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9 (10 Ratings)
eBook Oct 2013 272 pages 1st Edition
eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial
Arrow left icon
Profile Icon Terry Matula
Arrow right icon
Can$34.98 Can$49.99
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9 (10 Ratings)
eBook Oct 2013 272 pages 1st Edition
eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial
eBook
Can$34.98 Can$49.99
Paperback
Can$61.99
Subscription
Free Trial

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Laravel Application Development Cookbook

Chapter 2. Using Forms and Gathering Input

In this chapter, we will cover:

  • Creating a simple form

  • Gathering form input to display on another page

  • Validating user input

  • Creating a file uploader

  • Validating a file upload

  • Creating a custom error message

  • Adding a "honey pot" to a form

  • Uploading an image using Redactor

  • Cropping an image with Jcrop

  • Creating an autocomplete text input

  • Making a CAPTCHA style spam catcher

Introduction


In this chapter, we'll learn about using forms in Laravel, and how to accomplish some typical tasks. We'll begin with some simple form validation and file uploads, and move on to incorporating some frontend tools, such as Redactor and jCrop, into Laravel.

Creating a simple form


One of the most basic aspects of any web application is the form. Laravel provides easy ways to build HTML for our forms.

Getting ready

To get started, we need a fresh installation of Laravel.

How to do it...

To complete this recipe, follow these steps:

  1. In the app/views folder, create a new userform.php file.

  2. In routes.php, create a route to load the view:

    Route::get(userform, function()
    {
        return View::make('userform');
    });
  3. In the userform.php view, create a form using the following code:

    <h1>User Info</h1>
    <?= Form::open() ?>
    <?= Form::label('username', 'Username') ?>
    <?= Form::text('username') ?>
    <br>
    <?= Form::label('password', 'Password') ?>
    <?= Form::password('password') ?>
    <br>
    <?= Form::label('color', 'Favorite Color') ?>
    <?= Form::select('color', array('red' => 'red', 'green' =>'green', 'blue' => 'blue')) ?>
    <br>
    <?= Form::submit('Send it!') ?>
    <?= Form::close() ?>

View your...

Gathering form input to display on another page


After a user submits a form, we need to be able to take that information and pass it to another page. This recipe shows how we can use Laravel's built-in methods to handle our POST data.

Getting ready

We'll need the simple form set up from the Creating a simple form section.

How to do it...

Follow these steps to complete this recipe:

  1. Create a route to handle the POST data from the form:

    Route::post('userform', function()
    {
        // Process the data here
        return Redirect::to('userresults')-
            >withInput(Input::only('username', 'color'));
    });
    
  2. Create a route to redirect to, and to display the data:

    Route::get('userresults', function()
    {
        return 'Your username is: ' . Input::old('username')
            . '<br>Your favorite color is: '
            . Input::old('color');
    });
    

How it works...

In our simple form, we're POSTing the data back to the same URL, so we need to create a route that accepts POST using the same path. This is where we would...

Validating user input


In most web applications, there will be certain form fields that are required to process the form. We also want to be sure that all the e-mail addresses are formatted correctly, or the input must have a certain number of characters. Using Laravel's Validator class, we can check for these rules and let the user know if something is not correct.

Getting ready

For this recipe, we just need a standard installation of Laravel.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route to hold the form:

    Route::get('userform', function()
    {
        return View::make('userform');
    });
  2. Create a view named userform.php and add a form:

    <h1>User Info</h1>
    <?php $messages =  $errors->all('<pstyle="color:red">:message</p>') ?>
    <?php
    foreach ($messages as $msg)
    {
        echo $msg;
    }
    ?>
    <?= Form::open() ?>
    <?= Form::label('email', 'Email') ?>
    <?= Form::text('email', Input::old('email')) ?>
    <br>
    <?= Form::label('username...

Creating a file uploader


There may be times when we'd like the user to upload a file to our server. This recipe shows how Laravel can handle file uploads through a web form.

Getting ready

To create a file uploader, we need a standard version of Laravel installed.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route in our routes.php file to hold the form:

    Route::get('fileform', function()
    {
        return View::make('fileform');
    });
  2. Create the fileform.php View in our app/views directory:

    <h1>File Upload</h1>
    <?= Form::open(array('files' => TRUE)) ?>
    <?= Form::label('myfile', 'My File') ?>
    <br>
    <?= Form::file('myfile') ?>
    <br>
    <?= Form::submit('Send it!') ?>
    <?= Form::close() ?>
  3. Create a route to upload and save the file:

    Route::post('fileform', function()
    {
        $file = Input::file('myfile');
        $ext = $file->guessExtension();
        if ($file->move('files', 'newfilename.' . $ext))
        {
            return 'Success';
        ...

Validating a file upload


If we want to allow users to upload a file through our web form, we may want to restrict which kind of file they upload. Using Laravel's Validator class, we can check for a specific file type, and even limit the upload to a certain file size.

Getting ready

For this recipe, we need a standard Laravel installation, and an example file to test our upload.

How to do it...

Follow these steps to complete this recipe:

  1. Create a route for the form in our routes.php file:

    Route::get('fileform', function()
    {
        return View::make('fileform');
    });
  2. Create the form view:

    <h1>File Upload</h1>
    <?php $messages =  $errors->all('<p style="color:red">:message</p>') ?>
    <?php
    foreach ($messages as $msg)
    {
        echo $msg;
    }
    ?>
    <?= Form::open(array('files' => TRUE)) ?>
    <?= Form::label('myfile', 'My File (Word or Text doc)') ?>
    <br>
    <?= Form::file('myfile') ?>
    <br>
    <?= Form::submit('Send it!') ?>
    <?= Form::close() ?...

Creating a custom error message


Laravel has built-in error messages if a validation fails, but we may want to customize those messages to make our application unique. This recipe shows a few different ways to create custom error messages.

Getting ready

For this recipe, we just need a standard installation of Laravel.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route in routes.php to hold the form:

    Route::get('myform', function()
    {
        return View::make('myform');
    });
  2. Create a view named myform.php and add a form:

    <h1>User Info</h1>
    <?php $messages =  $errors->all
        ('<p style="color:red">:message</p>') ?>
    <?php
    foreach ($messages as $msg) 
    {
        echo $msg;
    }
    ?>
    <?= Form::open() ?>
    <?= Form::label('email', 'Email') ?>
    <?= Form::text('email', Input::old('email')) ?>
    <br>
    <?= Form::label('username', 'Username') ?>
    <?= Form::text('username', Input::old('username')) ?>
    <br>
    <?= Form::label...

Adding a honey pot to a form


A sad reality of the Web is that there are "spam bots" that search the web and look for forms to submit spam to. One way to help combat this is to use a technique called a honey pot. In this recipe, we'll create a custom validation to check for spam submissions.

Getting ready

For this recipe, we just need a standard Laravel installation.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route in routes.php to hold our form:

    Route::get('myform', function()
    {
        return View::make('myapp');
    });
  2. Create a view in our app/view directory named as myform.php and add the form:

    <h1>User Info</h1>
    <?php $messages =  $errors->all('<p style ="color:red">:message</p>') ?>
    <?php
    foreach ($messages as $msg)
    {
        echo $msg;
    }
    ?>
    <?= Form::open() ?>
    <?= Form::label('email', 'Email') ?>
    <?= Form::text('email', Input::old('email')) ?>
    <br>
    <?= Form::label('username', 'Username') ?>
    <?= Form::text...

Uploading an image using Redactor


There are a few different JavaScript libraries that can turn a form's text area into a WYSIWYG editor. Redactor is a newer library but is very well coded and has gained quite a bit of popularity in a short amount of time. For this recipe, we'll apply Redactor to our Laravel form, and create routes to allow for image uploads through Redactor.

Getting ready

We need to download a copy of Redactor from https://github.com/dybskiy/redactor-js/tree/master/redactor. Download redactor.min.js and save it to the public/js directory. Download redactor.css and save it to the public/css directory.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route in our routes.php file to hold our form with the redactor field:

    Route::get('redactor', function() 
    {
        return View::make('redactor');
    });
  2. Create a view in our app/views directory and name it as redactor.php:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Laravel and Redactor<...

Cropping an image with Jcrop


Image editing and manipulation can sometimes be a difficult thing to implement in our application. Using Laravel and the Jcrop JavaScript library, we can make the task much simpler.

Tip

Downloading the example code

You can download the example code files for all Packt books you have purchased from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

Getting ready

We need to download the Jcrop library from http://deepliquid.com/content/Jcrop_Download.html and unzip it. Put the file jquery.Jcrop.min.js into our public/js directory, and the jquery.Jcrop.min.css and Jcrop.gif files into our public/css directory. We'll use the Google CDN version of jQuery. We also need to make sure we have the GD library installed on our server, so we can do image manipulation. In our public directory, we'll need an images folder to store the images, and should...

Creating an autocomplete text input


On our web forms, there may be times when we want to have an autocomplete text field. This can be handy for populating common search terms or product names. Using the jQueryUI Autocomplete library along with Laravel, that becomes an easy task.

Getting ready

In this recipe, we'll be using the CDN versions of jQuery and jQueryUI; however, we could also download them and place them in our public/js directory, if we wanted to have them locally.

How to do it...

To complete this recipe, follow these steps:

  1. Create a route to hold our autocomplete form:

    Route::get('autocomplete', function()
    {
        return View::make('autocomplete');
    });
  2. Make a view in the app/views directory named autocomplete.php with our form's HTML and JavaScript:

    <!DOCTYPE html>
    <html>
        <head>
            <title>Laravel Autocomplete</title>
            <meta charset="utf-8">
            <link rel="stylesheet"href="//codeorigin.jquery.com/ui/1.10.2/themes/smoothness/jquery...

Making a CAPTCHA-style spam catcher


One way to combat "bots" that automatically fill in web forms is by using the CAPTCHA technique. This shows the user an image with some random letters; the user must fill in a text field with those letters. In this recipe, we will create a CAPTCHA image and verify that the user has entered it correctly.

Getting ready

We need a standard Laravel installation and make sure we have the GD2 library installed on our server, so we can create an image.

How to do it...

To complete this recipe, follow these steps:

  1. In our app directory, create a directory named libraries, and in our composer.json file, update it as follows:

    "autoload": {
        "classmap": [
            "app/commands",
            "app/controllers",
            "app/models",
            "app/database/migrations",
            "app/database/seeds",
            "app/tests/TestCase.php",
            "app/libraries"
        ]
    },
  2. In our app/libraries directory, create a file named Captcha.php to hold our simple Captcha class:

    <?php
    class Captcha...
Left arrow icon Right arrow icon

Key benefits

  • Install and set up a Laravel application and then deploy and integrate third parties in your application
  • Create a secure authentication system and build a RESTful API
  • Build your own Composer Package and incorporate JavaScript and AJAX methods into Laravel

Description

When creating a web application, there are many PHP frameworks from which to choose. Some are very easy to set up, and some have a much steeper learning curve. Laravel offers both paths. You can do a quick installation and have your app up-and-running in no time, or you can use Laravel's extensibility to create an advanced and fully-featured app.Laravel Application Development Cookbook provides you with working code examples for many of the common problems that web developers face. In the process, it will also allow both new and existing Laravel users to expand their knowledge of the framework.This book will walk you through all aspects of Laravel development. It begins with basic set up and installation procedures, and continues through more advanced use cases. You will also learn about all the helpful features that Laravel provides to make your development quick and easy. For more advanced needs, you will also see how to utilize Laravel's authentication features and how to create a RESTful API.In the Laravel Application Development Cookbook, you will learn everything you need to know about a great PHP framework, with working code that will get you up-and-running in no time.

Who is this book for?

The Laravel Application Development Cookbook is for PHP developers who are new to Laravel or development frameworks in general, as well as experienced Laravel developers looking to expand their knowledge. This book assumes that the reader has some familiarity with PHP.

What you will learn

  • Set up a virtual host and development environment in Apache
  • Set up a user authentication system
  • Use the RESTful controllers
  • Debug and profile your application
  • Store and retrieve content from the cloud
  • Use the Artisan command-line tool
  • Integrate JavaScript and jQuery into your Laravel app
  • Write unit tests for Laravel

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 25, 2013
Length: 272 pages
Edition : 1st
Language : English
ISBN-13 : 9781782162834
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Oct 25, 2013
Length: 272 pages
Edition : 1st
Language : English
ISBN-13 : 9781782162834
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just Can$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total Can$ 61.99
Laravel Application Development Cookbook
Can$61.99
Total Can$ 61.99 Stars icon

Table of Contents

11 Chapters
Setting Up and Installing Laravel Chevron down icon Chevron up icon
Using Forms and Gathering Input Chevron down icon Chevron up icon
Authenticating Your Application Chevron down icon Chevron up icon
Storing and Using Data Chevron down icon Chevron up icon
Using Controllers and Routes for URLs and APIs Chevron down icon Chevron up icon
Displaying Your Views Chevron down icon Chevron up icon
Creating and Using Composer Packages Chevron down icon Chevron up icon
Using Ajax and jQuery Chevron down icon Chevron up icon
Using Security and Sessions Effectively Chevron down icon Chevron up icon
Testing and Debugging Your App Chevron down icon Chevron up icon
Deploying and Integrating Third-party Services into Your Application Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.9
(10 Ratings)
5 star 30%
4 star 30%
3 star 40%
2 star 0%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




saad guessous Dec 08, 2013
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This is the kind of book I wish was available 6 months ago when I encountered Laravel for the first time and started to experiment with it. For somebody starting development with Laravel and having no prior experience with the framework this book is a must, as the recipes included covers most of the stuff ranging from beginner to intermediate level and beyond, with whole chapters dealing with basics as installing and setting up, authentication, data storage and querying using ORM, ajax, security, testing and debugging. Although Laravel is a familiar framework, I decided to re-read the chapters on controllers, views, form handling and users authentication and to my surprise I picked up a whole bunch of new information in the process, the chapters on composer and particularly the one on ajax where welcomed as I was seeking similar info on the net... And the one thing I appreciate the most is to have all of the information in one bundle, as it makes the book a good reference to go back to.I'm really pleased with the outcome and I feel the author did a really great job and lastly I would wholeheartedly recommend this book to any developer wishing to use Laravel for his upcoming project.
Amazon Verified review Amazon
DJ Far Oct 31, 2014
Full star icon Full star icon Full star icon Full star icon Full star icon 5
This a very well-written, easy to follow reference which serves exactly the purpose for which I bought it. It's not a basic primer on Laravel, but a how-to for specific tasks you always need to do with a framework. A very good collection of recipes.
Amazon Verified review Amazon
Manuel Ambulo Mar 22, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Excellent book
Amazon Verified review Amazon
リク丸 Mar 26, 2014
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Laravelの開発と基本、事例などがわかります。Laravel4のネット上のマニュアル&APIリファレンスなどとあわせて見るのに適していると思います。対象は、Laravel未経験者です。(ディープな内容は書いていないです)php経験は必要ですが他のフレームワーク経験がなくても読める本かと思いました。Laravelのクセなどがつかめます。(ネットマニュアル & 記事だけだと若干不安なので読んで見ました)一部で少し情報が古い点もありますが、最新のLaravel4開発でもほとんど通用すると思います。
Amazon Verified review Amazon
Gregory M. Sanders Dec 17, 2013
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Terry Matula’s Laravel Application Development Cookbook is a good resource for PHP developers who are familiar with MVC code frameworks and want to quickly get up to speed on Laravel. It’s especially valuable for developers like me who have heard about many time-saving dev tools (such as SublimeText2) but never had time to dig into them. This book is totally hands-on, which is great when you’re trying to get a working app up in a short time frame. This isn’t an MVC introduction -- If you haven’t worked with MVC frameworks before, this book might not confuse you, but it might leave you wondering why the code works the way it does.Laravel Application Development Cookbook embraces the reality that today’s dev tools work in integrated development environments, not as self-standing pieces of software. Specific tools used in the book include: Git (with Laravel installed as a submodule) for source control; Apache web server; Sublime Text and NetBeans IDE; Composer as a dependency package installer; OAuth (optionally) for user authorization; Fluent for query building; jQuery for AJAX and general UI functions; Bootstrap for dynamic styling and sizing; PHPUnit for unit testing. Due to the hands-on nature of the narrative, and its reliance on specific tools that integrate well with Laravel, this cookbook’s sample code might be awkward for devs who already have a favorite development toolkit and aren’t interested in adopting new pieces. But for me, this was a huge bonus: learn Laravel and simultaneously get a painless introduction to some good productivity tools. Laravel Application Development Cookbook also gives a good introduction to some of Laravel’s specialized built-in tools: Artisan command line; Eloquent ORM and Blade templating engine, for example.Most of the book’s chapters cover common situations such as creating a textbox with autocomplete, returning data as JSON, validating a user login and displaying nested views. There are also some niche use cases like reading RSS feeds as a data source.This book is well worth reading if you’re interested in trying out Laravel for the first time, or using it more effectively. Full disclosure: I received a free preview copy of this book. I jumped at the chance to preview this because Laravel has gotten good reviews and I needed a good book to get me started on it. I was definitely not disappointed.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.