10 Must-have Laravel 5.1 Packages

Access all tutorials in sprocket icon.

June 25, 2015 from author Bill Keck.

I’m going to be doing a fairly long tutorial on image management and it occurred to me that it would be helpful if people who want to follow that tutorial had the intervention/image package installed because we are going to be using it. That got me thinking it might be nice to share some common packages that we would typically install in our Laravel 5.1 build.

Just a quick recap for anyone who is unfamiliar with packages and composer. I’m assuming that if you are using Laravel, you have installed composer and have a development environment setup. If you haven’t done this yet, please refer to my development environment tutorial, which comes with links for easy reference.

Ok, so if you have some experience with composer, you know that it makes installing 3rd party packages for Laravel a snap. You can find an amazing selection of Laravel packages at Packagist.org. I set the link to search for packages tagged for Laravel.

If you look at the number of downloads per package, obviously you can tell which ones are the most popular.

Here are 10 that I use for a typical fresh build of Laravel 5.1.

  1. laravelcollective/html
  2. barryvdh/laravel-debugbar
  3. patricktalmadge/bootstrapper
  4. cviebrock/eloquent-sluggable
  5. doctrine/dbal
  6. laracasts/generators
  7. laracasts/flash
  8. barryvdh/laravel-ide-helper
  9. creativeorange/gravatar
  10. intervention/image

If you want to pull them in through composer, you can add them to your require block in your composer.json file:



         "laravelcollective/html": "~5.0",
         "barryvdh/laravel-debugbar": "~2.0",
         "patricktalmadge/bootstrapper": "~5",
         "cviebrock/eloquent-sluggable": ">=3.0.0-alpha",
         "doctrine/dbal": "2.5.0",
         "laracasts/generators": "~1.1",
         "laracasts/flash": "~1.3",
         "barryvdh/laravel-ide-helper": "~2.0",
         "creativeorange/gravatar": "~1.0",
         "intervention/image": "~2.2"

Then run composer update. You can find instructions for each install in the links in the ordered list above. Typically, all you have to do is configure the config/app.php providers and aliases arrays. It really is super-simple, which is why everyone loves composer and Laravel’s application architecture.

I’m not listing the actual instructions here because I think it’s important that you get used to pulling that info from the source. There’s no way I can stay on top of all the updates and there’s no sense in duplicating information. I will of course add any special notes when appropriate.

Ok, so let’s briefly describe each one:

1. laravelcollective/html

This one replaces the illuminate/html class, since that class is no longer supported and is no longer included in the core as of laravel 5. This package is essential, if you like using the form model binding like so:



{!! Form::model($marketingImage, ['route' => ['marketingimage.destroy', $marketingImage->id],
        'method' => 'DELETE',
        'class' => 'form',
        'files' => true]
        ) !!}

But obviously this is not completely necessary, which is why it’s no longer in the core. You could simply create a form manually using bootstrap. You just have to remember to add:



 <input type="hidden" name="_token" value="{{ csrf_token() }}">

That will add your csrf token to the post data.

So obviously, using the Form helper does this for you, which is why I use it when I can. I find it very convenient.

When you are installing this, you will see instructions for adding the ‘Form’ alias. Please note that the bootstrapper package has Form alias as well and you cannot use both, because it will cause a conflict. So I solved this by simply not including the alias for the bootstrapper form alias.

Also note: Most instructions for adding to providers array and the alias array are not using the new PHP ::class syntax. I recommend using the new syntax, which is better to use because you can use your IDE to click into the class.

So for example, old style alias:



'Form'  => 'Collective\Html\FormFacade',

New style:



'Form'  => Collective\Html\FormFacade::class,

You can do the same for the providers, in this case it’s the html provider:



Collective\Html\HtmlServiceProvider::class,

2. barryvdh/laravel-debugbar

This is an absolute must for development. It installs a debug bar that sits at the bottom of the page that gives you helpful information on routes, DB queries and more.

3. patricktalmadge/bootstrapper

This is a pretty wrapper for a lot of bootstrap stuff. I haven’t gone too far deep into it, but I do use the breadcrumb widget. As I noted in the laravel collective html package, there is a conflict with the form alias, so leave that one out when you are updating the aliases array in config/app.php.

4. cviebrock/eloquent-sluggable

This is a very robust package for adding slugs to your url.

5. doctrine/dbal

We need this package in order to run migration:rollback. I had trouble installing this until I figured out the correct way to add it to composer.json, which I’ve given you above.

6. laracasts/generators

This one gives us an artisan command for creating pivot table migrations.

7. laracasts/flash

This is a nice handy helper to make your flash message syntax in your controller beautiful:



flash()->success('Marketing Image Created!');

8. barryvdh/laravel-ide-helper

This installs a helper class, which helps PhpStorm recognize your laravel classes, so you don’t end up with unnecessary error messages from your IDE. This one doesn’t need configuration in config/app.php. Instead, you have to initialize from artisan commands.

9. creativeorange/gravatar

This is a super-simple gravatar package that lets you display the users gravatar.

10. intervention/image

This is a very handy image helper class that lets you do things like save thumbnails of the image, set it as grayscale if you choose, and a whole lot more. Working with images is kind of a pain, and any help with syntax is worth it.

This group of packages will help you with my tutorials if you want to follow along. You can also view all of my tutorials for Laravel by clicking on the sprocket at the top of the page.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks.

I don’t have a donate button, but If you would like to support my work, you can do so by buying one of my 99¢ books, I really appreciate it.

View Partials in Laravel 5.1

Access all tutorials in sprocket icon.

June 17, 2015 from author Bill Keck.

How to make a view partial in Laravel 5.1.

Almost everything associated with using Laravel’s blade templating engine is incredibly easy. And this is true for creating view partials.

For those who are unfamiliar, a view partial is view that is meant to be called into another view. Common uses for this are form partials, where you have code that you don’t want to duplicated over and over. Also, view partials are handy for things like errors and alerts.

Here’a form view from my previous tutorial, Setting Up a Forgot Password Form and Controller in Laravel 5.1:



@extends('layouts.master')

@section('content')

<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
    @if (session('status'))
      <div class="alert alert-success">
             {{ session('status') }}
      </div>
    @endif

    @if (count($errors) > 0)
       <div class="alert alert-danger">
       <strong>Whoops!</strong> There were some problems with your input.<br><br>
       <ul>
           @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
           @endforeach
        </ul>
        </div>
      @endif

<form class="form-horizontal" role="form" method="POST" action="/password/email">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>

<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
         Send Password Reset Link
</button>
</div>
</div>
</form>

</div>
</div>
</div>
</div>
</div>

@endsection


This is a form to request a reset link for your password. Notice the if statement:



   @if (count($errors) > 0)
       <div class="alert alert-danger">
       <strong>Whoops!</strong> There were some problems with your input.<br><br>
       <ul>
           @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
           @endforeach
        </ul>
        </div>
      @endif

As you may already know, the $errors variable is always available to the view. So here we are iterating through them and displaying them if there are errors returned from the form input.

Now if you look at the other views associated with the forgot password controller, you can see that they all use the same exact code, which is code duplication and violates the DRY principle.

So one way to approach this is to make a partial view that just holds this code. If you have a new install of Larvel 5.1, it comes with an errors folder in the view folder, and this is the perfect place to put it.

So let’s create errors.blade.php in the errors folder and place the if statement in it as the only contents of that file.

When you are done with that, you can chop out the if statement from the other view, and in its place put:



@include('errors.errors')

You can see just how intuitive this syntax is. The file we need is in the errors folder and is named errors. Piece of cake!

Now, whenever you want to return the form errors, it’s one line of code.

From an organizational standpoint, you could create a partials folder inside of the view folder and place it there. There are lots of possibilities for this, so just do what is intuitive for you to work with.

Some people like to name their partials with an underscore in front, _errors.blade.php for example, but I don’t follow that practice.

Ok, so this was just a short tutorial on how to make a view partial in Laravel 5.1. I hope you enjoyed it. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks.

I don’t have a donate button, but If you would like to support my work, you can do so by buying one of my 99¢ books, I really appreciate it.

Setting Up a Forgot Password Form and Controller in Laravel 5.1

Access all tutorials in sprocket icon.

June 16, 2015 from author Bill Keck.

How to Setup Forgot Password in Laravel 5.1

Ok, so in my last tutorial, How to Make User Login and Registration Laravel 5.1, we setup a basic user registration and login, but we left the forgot password functionality out because the tutorial was going too long.

In Laravel 5.1, they are not including the views you need serve forgot password function out of the box. The controller and traits are in place, however.

So all we need to do is make sure that we have the route set and the proper views, and it will work perfectly.

The Route

You should have a route in app/Http/routes.php file as follows:



Route::controllers([
   'password' => 'Auth\PasswordController',
]);


If you still have the route the old AuthController, you can go ahead and delete the Auth\Authcontroller line, we will not be using it.

With this type of route, if we have for example, a getEmail function on our controller, the route will use the verb get from the function name to figure out what kind of request we are looking for.

We abandoned this approach for the login and registration controllers because we wanted a simpler approach. But since forgot password functionality is a little complicated, I’m leaving well-enough alone, especially since I don’t anticipate having to work on it in the future. It doesn’t seem likely to change, whereas I know for my registration, it could easily be different in the future, especially if I hook up social auth to it.

Ok, so we have our route in place, let’s look at the controller.

The Controller

The path is app/Http/Controllers/Auth/PasswordController.php.

It should look like this:



<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ResetsPasswords;

class PasswordController extends Controller
{
   /*
   |--------------------------------------------------------------------------
   | Password Reset Controller
   |--------------------------------------------------------------------------
   |
   | This controller is responsible for handling password reset requests
   | and uses a simple trait to include this behavior. You're free to
   | explore this trait and override any methods you wish to tweak.
   |
   */

   use ResetsPasswords;

   /**
    * Create a new password controller instance.
    *
    * @return void
    */
   public function __construct()
   {
       $this->middleware('guest');
   }
}

So where are all the actions? In the ResetsPasswords trait of course. Frankly, I don’t understand why it’s done this way. It doesn’t seem likely that the methods in the trait would be used for anything other than the forgot password feature.

Perhaps they were trying to keep the controller skinny.

The Trait

Here’s what the trait looks like:



<?php

namespace Illuminate\Foundation\Auth;

use Illuminate\Http\Request;
use Illuminate\Mail\Message;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Password;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

trait ResetsPasswords
{
   /**
    * Display the form to request a password reset link.
    *
    * @return \Illuminate\Http\Response
    */
   public function getEmail()
   {
       return view('auth.password');
   }

   /**
    * Send a reset link to the given user.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
   public function postEmail(Request $request)
   {
       $this->validate($request, ['email' => 'required|email']);

       $response = Password::sendResetLink($request->only('email'), function (Message $message) {
           $message->subject($this->getEmailSubject());

       });

       switch ($response) {
           case Password::RESET_LINK_SENT:
               return redirect()->back()->with('status', trans($response));

           case Password::INVALID_USER:
               return redirect()->back()->withErrors(['email' => trans($response)]);
       }
   }

   /**
    * Get the e-mail subject line to be used for the reset link email.
    *
    * @return string
    */
   protected function getEmailSubject()
   {
       return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
   }

   /**
    * Display the password reset view for the given token.
    *
    * @param  string  $token
    * @return \Illuminate\Http\Response
    */
   public function getReset($token = null)
   {
       if (is_null($token)) {
           throw new NotFoundHttpException;
       }

       return view('auth.reset')->with('token', $token);
   }

   /**
    * Reset the given user's password.
    *
    * @param  \Illuminate\Http\Request  $request
    * @return \Illuminate\Http\Response
    */
   public function postReset(Request $request)
   {
       $this->validate($request, [
           'token' => 'required',
           'email' => 'required|email',
           'password' => 'required|confirmed',
       ]);

       $credentials = $request->only(
           'email', 'password', 'password_confirmation', 'token'
       );

       $response = Password::reset($credentials, function ($user, $password) {
           $this->resetPassword($user, $password);
       });

       switch ($response) {
           case Password::PASSWORD_RESET:
               return redirect($this->redirectPath());

           default:
               return redirect()->back()
                           ->withInput($request->only('email'))
                           ->withErrors(['email' => trans($response)]);
       }
   }

   /**
    * Reset the given user's password.
    *
    * @param  \Illuminate\Contracts\Auth\CanResetPassword  $user
    * @param  string  $password
    * @return void
    */
   protected function resetPassword($user, $password)
   {
       $user->password = bcrypt($password);

       $user->save();

       Auth::login($user);
   }

   /**
    * Get the post register / login redirect path.
    *
    * @return string
    */
   public function redirectPath()
   {
       if (property_exists($this, 'redirectPath')) {
           return $this->redirectPath;
       }

       return property_exists($this, 'redirectTo') ? $this->redirectTo : '/home';
   }
}


One obvious improvement would be to get rid of the redirectPath function and simply use our RedirectsUsers trait, since that is the sole purpose of that trait and the methods are identical.

However the ResetsPasswords trait lives in the vendor/laravel/illuminate/Foundation/Auth directory, which means when we run composer update, the file can be overwritten, which is not what we want.

We could just copy the trait into our AuthTraits folder, give it a new name and then modify it how we want, but is it worth the bother? Probably not. Like I said, we will not be messing with this code much in the future, so it’s probably best just to leave it as is.

So let’s take a brief look at the methods in this trait, keeping in mind that I didn’t write them, so I don’t know every detail, but we can still get a general understanding of how it works.

The first method simply returns the form:



public function getEmail()
{
   return view('auth.password');
}


We can tell from the view method that we are expecting an auth folder in the views folder and a password.blade.php file within the auth folder.

When the user gives us his email and submits, we post the form:



public function postEmail(Request $request)
{
   $this->validate($request, ['email' => 'required|email']);

   $response = Password::sendResetLink($request->only('email'), function (Message $message) {
       $message->subject($this->getEmailSubject());

   });

   switch ($response) {
       case Password::RESET_LINK_SENT:
           return redirect()->back()->with('status', trans($response));

       case Password::INVALID_USER:
           return redirect()->back()->withErrors(['email' => trans($response)]);
   }
}



This one gets fairly complicated when we look under the hood. There is a class named PasswordBroker that lives in vendor/laravel/framework/src/Auth/Passwords/ that has the sendResetLink method.

So the simple explanation is the method tries to find a user with that email and send them a reset link. It switches on the response, and if it is successful it redirects back with status. If not, it returns an error message for invalid user.

Exactly how it’s all stitched together with all the dependencies would make an excellent Laracasts episode. Otherwise it’s beyond the scope of this tutorial.

The next method returns the email subject:



protected function getEmailSubject()
{
   return isset($this->subject) ? $this->subject : 'Your Password Reset Link';
}


Next we have the getReset method, which returns the reset view with the token. This will be the form where they type in the new password and confirm it.



public function getReset($token = null)
{
   if (is_null($token)) {
       throw new NotFoundHttpException;
   }

   return view('auth.reset')->with('token', $token);
}

Note the use of the default of null for the token. So no need to set up a try/catch, since it will have a value in any case. It’s a nice clean alternative to a try/catch block.

Next we have postReset:




public function postReset(Request $request)
{
   $this->validate($request, [
       'token' => 'required',
       'email' => 'required|email',
       'password' => 'required|confirmed',
   ]);

   $credentials = $request->only(
       'email', 'password', 'password_confirmation', 'token'
   );

   $response = Password::reset($credentials, function ($user, $password) {
       $this->resetPassword($user, $password);
   });

   switch ($response) {
       case Password::PASSWORD_RESET:
           return redirect($this->redirectPath());

       default:
           return redirect()->back()
                       ->withInput($request->only('email'))
                       ->withErrors(['email' => trans($response)]);
   }
}


Ok, so we validate, set the credentials from the form post, use the reset method of the PasswordBroker class, which is accessed via the Password facade.

Then depending on the response, either take them to destination set by redirectPath or go back to the form with errors.

If you are interested, the Password facade class is found at vendor/laravel/framework/src/Illuminate/Support/Facades/Password.php.

There’s a method in there name getFacadeAccessor. It’s probably worth following the chain here for a moment:



protected static function getFacadeAccessor()
{
   return 'auth.password';
}


This returns the name of the component. So now we can checkout the PasswordResetServiceProvider class, which you can find at:

vendor/framework/src/Illuminate/Auth/Passwords/PasswordResetServiceProvider.php

Let’s look at one method there:



protected function registerPasswordBroker()
{
   $this->app->singleton('auth.password', function ($app) {
       // The password token repository is responsible for storing the email addresses
       // and password reset tokens. It will be used to verify the tokens are valid
       // for the given e-mail addresses. We will resolve an implementation here.
       $tokens = $app['auth.password.tokens'];

       $users = $app['auth']->driver()->getProvider();

       $view = $app['config']['auth.password.email'];

       // The password broker uses a token repository to validate tokens and send user
       // password e-mails, as well as validating that password reset process as an
       // aggregate service of sorts providing a convenient interface for resets.
       return new PasswordBroker(
           $tokens, $users, $app['mailer'], $view
       );
   });
}

This is kind of complicated, too much for a beginning tutorial. But the main thing I wanted you to see is that ‘auth.password’ is bound to PasswordBroker. So, since the Password facade is linked to auth.password and auth.password is bound to PasswordBroker, we end up using the methods of PasswordBroker when we call Password.

If you read my service provider tutorial, which was simple, you get some sense of this, and here we have a very advanced example. I should also say it’s extremely well-commented.

If you are a beginner and all this seems like being dropped in the middle of an ocean without a lifejacket or raft, don’t worry, we’ve all been there. Just stay with it, eventually, you will get it.

You don’t have to memorize it all to make progress. Eventually, enough will stick so that you can use what you have as a knowledge base that you can build on. That’s how most of us do it.

Ok, heading back to our ResetsPasswords trait, we need to look at the resetPassword method:



protected function resetPassword($user, $password)
{
   $user->password = bcrypt($password);

   $user->save();

   Auth::login($user);
}

This is the method that sets and saves the new password and logs in the user. We use in our postReset method.

The final method is redirectPath, which we have already covered.

You can see just how involved the process of resetting a password is, and you can see why I didn’t want to build it from scratch or mess with it too much.

The Views

The last step to make our forgot password functionality operational is to create some views. Let’s start by creating the two folders that we will need, which will reside in the views folder. Make an emails folder and an auth folder inside the views folder.

Lets make a password.blade.php file and place it in the emails folder with the following contents:



Click here to reset your password: {{ url('password/reset/'.$token) }}

Things had to get easier sooner or later… You can of course add what ever messaging you want to this view. This is the email that will be sent to the user with the link they need to reset their password.

Next, we need to create reset.blade.php and place it within the auth folder with the following contents:



@extends('layouts.master')

@section('content')

<div class="container-fluid">
<div class="row">
 <div class="col-md-8 col-md-offset-2">
 <div class="panel panel-default">
 <div class="panel-heading">Reset Password</div>
 <div class="panel-body">

 @if (count($errors) > 0)
    <div class="alert alert-danger">
    <strong>Whoops!</strong> There were some problems with your input.<br><br>
    <ul>
        @foreach ($errors->all() as $error)
              <li>{{ $error }}</li>
        @endforeach
         </ul>
        </div>
@endif

<form class="form-horizontal" role="form" method="POST" action="/password/reset">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="token" value="{{ $token }}">

<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>

<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input type="password" class="form-control" name="password">
</div>
 </div>

 <div class="form-group">
 <label class="col-md-4 control-label">Confirm Password</label>
 <div class="col-md-6">
 <input type="password" class="form-control" name="password_confirmation">
 </div>
  </div>

 <div class="form-group">
 <div class="col-md-6 col-md-offset-4">
 <button type="submit" class="btn btn-primary">
             Reset Password
 </button>
 </div>
 </div>
 </form>

 </div>
 </div>
 </div>
 </div>
</div>

@endsection

This view is just the form for the password reset, so they can enter the new password.

And finally, we need to create a file named password.blade.php in the auth folder with the following contents:



@extends('layouts.master')

@section('content')

<div class="container-fluid">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Reset Password</div>
<div class="panel-body">
    @if (session('status'))
      <div class="alert alert-success">
             {{ session('status') }}
      </div>
    @endif

    @if (count($errors) > 0)
       <div class="alert alert-danger">
       <strong>Whoops!</strong> There were some problems with your input.<br><br>
       <ul>
           @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
           @endforeach
        </ul>
        </div>
      @endif

<form class="form-horizontal" role="form" method="POST" action="/password/email">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

<div class="form-group">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="{{ old('email') }}">
</div>
</div>

<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
         Send Password Reset Link
</button>
</div>
</div>
</form>

</div>
</div>
</div>
</div>
</div>

@endsection


This is another very simple form. Users enter their email and it posts to the postEmail method on the ResetsPasswords trait.

And that is all we need. If you click on the forgot password link in your login form, assuming you followed my How to Make User Login and Registration Laravel 5.1, you will then be taken to the auth.password view to do the lookup on email address and cause the email to be sent.

Then assuming the user receives the email, it will be formatted with the emails.password view, so they can click that link and get them to the reset view, where they can enter the new password.

We don’t cover configuration for sending an actual email in this tutorial, but if you go to app/config/mail.php, there is a setting you can change at the bottom of the file:



'pretend' => true,

 

When it’s set to true, it will send an email to your application log files, located at app/storage/logs/laravel.log.

You can test your forgot password implementation to the point where it will make an entry in the log file.

That’s gonna do it for this tutorial, I hope you enjoyed. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work, you can do so by buying one of my 99¢ books, I really appreciate it.

Database Setup Laravel 5.1

Access all tutorials in sprocket icon.

June 14, 2015 from author Bill Keck.

Beginner Tutorial for setting up your database connection to your Laravel 5.1 application.

Step 1. Create the Database

If you are following along with my beginner’s development environment, we are using MAMP, which comes with a MySql build that is ready to use. It also has PhpMyAdmin implemented, so you easily interact with the database.

You are not obligated to use this development environment, but my instructions will be for this type of setup.

So to get to the PhpMyAdmin interface, open the MAMP application and click on Open WebStart page. Next you’ll see:

MySQL

MySQL can be administered with phpMyAdmin.

Click the phpMyAdmin link, and this will pull up the phpMyAdmin page. Select the Databases tab, and below that you will see an input field for database name and a dropdown list for collation.

I typically name the DB the same name as the project, all lowercase. The collation we use is utf8_unicode_ci. We use that collation because it supports proper sorting in multiple languages. After you select your collation, press the create button, and your database will be created for you.

Step 2. Set the Password.

One slight complication I ran into is that it’s a little tricky to set a password. You can leave it as is and use an empty string in your Laravel config, but that’s not what I did.

I opened the following:

Applications/MAMP/bin/phpMyAdmin/config.inc.php and edited config.inc.php with:



$cfg['Servers'][$i]['password']      = 'mypassword'; 

Obviously use your password where it says mypassword. There’s probably an easier way to do this, so Google that for yourself or leave a comment if you want to share. It’s good to know how to set it through config.inc.php if you ever happen to lock yourself out.

Step 3. Set DB parameters in .ENV in your Laravel app.

Once you are on the Laravel side of things, setup is a snap. Open your .ENV file and set the following:



DB_HOST=localhost
DB_DATABASE=yourDBname
DB_USERNAME=root
DB_PASSWORD=mypassword

Obviously fill in yourDBname and mypassword with your values.

By default, Laravel 5.1 is configured for mysql as the default DB. If you need to change that, you can go your Laravel config folder and open database.php. You can see it’s a settings array and the default key is:



'default' => env('DB_CONNECTION', 'mysql'),

Step 4. Run the Migration

Laravel 5.1 comes with a couple of migrations to setup the users table and the password_resets table. It will also create a migrations table to keep track of all the migrations.

You can see the migrations in database/migrations folder. You will see two files:

2014_10_12_000000_create_users_table.php
2014_10_12_100000_create_password_resests_table.php

These are pre-configured migrations, so you don’t need to change anything. If you are new to migrations , they are a set of instructions to the DB from a php file to do things like create tables and columns. You can also use them to create indexes and foreign keys. There’s also a rollback method, in case you need do undo something.

The laravel docs on migration are a great resource.

Once you run the migrations from the command line, it will create the tables you need to add users and manage password recovery.

To run the migration, go to your command line and run:



 php artisan migrate

Once you are done, check via PhpMyAdmin to make sure the tables were created. Now that you have your DB created and communicating with Laravel, you will be ready to move on to creating your user registration and login.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks.

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

Installation and Setup of Laravel 5.1

Access all tutorials in sprocket icon.

June 13, 2015 from author Bill Keck.

Let’s do a fresh install of Laravel 5.1. I’m going to assume you have a development environment setup. If not, check out my previous post on
development environments before continuing.

Please note that you need to use a minimum PHP build of 5.5.9. You can set this by opening MAMP, selecting preferences, then PHP.

In my fresh install of MAMP, I’m using PHP 5.6.7, so you should choose this as well if you are using MAMP. If you do make a change, remember to restart the servers, so the change will take effect.

Also note: While you can certainly install Laravel 5.1 on a windows machine using MAMP or some other development environment, the instructions I’m giving here are for Mac OSX, using the development tools I listed in my development environments
post, which includes MAMP.

Also, for convenience, you can reference the Laravel install docs directly
here, should you need to refer to them.

Ok, let’s jump in:

Step 1. Create Local Host Entry

We will modify our hosts file.

From the command line, type:



sudo vim /private/etc/hosts

Remember when using vim, we use i for insert, so we can begin typing. Then create an entry for:



127.0.0.1       www.mydomain.com   mydomain.com

Obviously mydomain represents your project name. You can also use the extension .dev instead of .com if you choose, a lot of developers like to do it that way.

Then hit escape on the keyboard, then :wq and enter to write and quit. That local host entry should now be saved.

Step 2. Listen for Vhosts in httpd.conf

If you placed your MAMP build in your applications folder, go to applications/MAMP/conf/apache/httpd.conf and open the file using your IDE or other suitable text editor. Make sure the following line is uncommented:



# Virtual hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

Now we’re listening for our vhosts entries.

Step 3. Configure Vhost For Our Application

Go to Applications/MAMP/conf/apache/extra/httpd-vhosts.conf and open the file using your IDE or other suitable text editor and add the following:



    <VirtualHost *:80>
   ServerAdmin webmaster@dummy-host2.example.com
   DocumentRoot "/Users/billk/var/www/mydomain/public"
   ServerName mydomain.com
   ErrorLog "logs/dummy-host2.example.com-error_log"
   CustomLog "logs/dummy-host2.example.com-access_log" common
    </VirtualHost>

The important thing to note here is the DocumentRoot. In my case, I have my project folder on /Users/billk/var/www. You should set yours accordingly, /path/to/mydomain/public.

Also note the ServerName is set to mydomain.com, which obviously you will replace with your projectname.com.

Ultimately, it’s the public folder within our application that is accessible via the web. We’re leaving the example entries for the logs as we will not be using them in our tutorial.

Step 4. Start or restart MAMP. If you have not previously created shortcut on the dock, you should do so now. MAMP should be in your applications folder and you can drag it to the dock for future use.

Open the application and click the start servers button. If MAMP was previously running, you must restart it in order for the changes in the host entry and the vhosts to take effect.

Step 5. Use composer inside the billk/var/www directory to install a new build of laravel

Obviously if your path is different, you would use your path, you are not going to have a billk directory, for example.

To navigate to the correct directory from the command line, first type:



cd ~

That will get you to the base directory. From there type:



cd var/www/

Gotcha: Do not put a backslash in front of the first folder, if you start with /var, it will bring you to the wrong location.

Ok, now that we’re in the right folder, we can pull in Laravel via composer, assuming you have installed composer. If you have not installed composer, do so now. You can pull it down from getcomposer.org.

Let’s assume you have composer installed globally and can use it in this directory. Type the following:



composer create-project laravel/laravel mydomain --prefer-distribution

It will likely take a couple of minutes to download. This will also create the project folder and place laravel within it.

Step 6. Create project in PHP Storm or your IDE.

These instructions are for PHPStorm. If you do not have it, you can download a free trial PHPStorm.

Now, select create new project from existing files. Then select the last option on the first screen, which is Source files are in a local directory no web server is configured. Click Next.

In the directory tree, navigate to your project folder, highlight it by clicking on it, then click the Project Root near the top left of the dialog. Then click finish.

And that’s pretty much it for basic install. If you navigate your browser to mydomain.com, again using your project name, it should pull up the Laravel welcome page.

In my next Laravel tutorial, we will configure the database and continue to setup a basic application in Laravel 5.1. I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

Development Environment for Laravel 5.1

Access all tutorials in sprocket icon.

June 12, 2015 from author Bill Keck.

One thing often overlooked by beginning developers is setting up a proper development environment. Now exactly what constitutes a proper development environment is subject to wide interpretation, so I’m not looking to start arguments or flame wars.

I’m actually more of a follower than a leader when it comes to environments, and the team at work has been very helpful pointing me in the right direction.

So now I’m just trying to be helpful to those who want to learn Laravel 5.1 by showing them helpful tools for the job. I’m going to stick with the idea that simplest is best for now. I will write a separate blog at a later date for a more advanced environment, one that includes vagrant, live updates, PhpUnit tests firing off on whenever a file changes, and other advanced topics.

But for now, I just want to help people get started and address some of the more basic concerns. And although this may seem incredibly obvious to experienced programmers, the first question to be asked is should you use a linux, OSX, or windows environment?

I know nothing about straight linux machines, so can’t help you there. As for Windows, while it’s possible to develop on a pc/windows, to do so is to severely handicap yourself. Anyone who follows Laracasts for example, knows that Jeffrey way uses a macbook pro. So if for no other reason, I would recommend using a macbook pro just to have consistency when you are following along his lessons.

From personal experience, I recently switched to macbook pro, with OSX Yosemite 10.10.3 from Windows. It’s a pretty amazing improvement just from a speed standpoint. I feel like I can work twice as fast as before. But even more so, installing and maintaining programmers is easier and cleaner than it is with windows. So you gain a lot of time efficiency from not having to trip over environment and path variables like we so often do on windows.

I’m sort of an old school developer and the idea of using a laptop for development was counter-intuitive at first. I thought I would be constrained by the small screen. My vision problems are far-sighted, which sometimes leads me to short-sighted thinking.

Anyway, lucky for me the team at work showed me the way. We all use Henge Docks, one for work, and one for home. So I pop my laptop into the dock and it is instantly wired up to two large monitors, a wireless keyboard, and a wireless mouse.

When I’m done at work, I take it home, pop it into a mirrored dock setup there, and I have the same exact environment in both places. This doesn’t seem like such a big deal in theory, but in practice, it is. I get 100% consistency by working off a single machine. Since the battery keeps it running in transition, everything is always open for me, just how I left it. I don’t even have to open my IDE, it’s just waiting for me to do some work and have some fun coding.

I know cost is a factor, and not everyone can just decide to switch environments, but if you can, I would highly recommend it.

So now that we got that question out of the way, what do you need to put on your machine? I’ll give you a short list of what I’m currently using:

Each item above is linked, so you can get right to the downloads. So let’s talk a little about them.

MAMP is an all-in-one development environment, which gives you Apache, PHP, MySql, and PhpMyAdmin all in one download. It’s easy to install and manage. It’s easy for beginners to work with.

Iterm 2 is an enhanced Apple terminal for the command line.

Home Brew is a package installer for OSX. It makes installing things like Node a snap. You’ll note that I didn’t include Node on this list, I will be including it in the advanced environment tutorial that I will write at a later date.

I’m also leaving out version control for the moment, will get back to you on that one. I could have waited to get all this organized before publishing, but I’m putting this out now, so people know the environment I’m using for the laravel tips tutorials. This is the exact environment I’m using for these tutorials.

PhpStorm is my IDE of choice. It’s a paid IDE, where you could use something free like NetBeans, but I found PHPStorm to be exceptional, as I wrote about in this PhpStorm post. Sublime is another big contender for this role, but I don’t use it personally, so I don’t have experience to share with you on that.

If you do choose PhpStorm, then I highly recommend watching the free videos on Laracasts for PHPStorm. You can learn how to customize your own theme, which besides making it prettier, can help you understand the code better. And of course modifying the keymap, so you have your own custom shortcut keys is essential as is the live templates, which allow you store snippets of code template for re-use. I highly recommend this series of videos. I would write tutorials on this, but the videos really have it all and they are free, so you can’t beat that.

Sequel Pro is on the list, but for beginner tutorials, it is not really necessary. It is however in my current development environment.

Finally we have composer, and this is absolutely vital to modern PHP development. You will need it to install Laravel. I will write about Laravel installation as a separate tutorial.

Building the write development environment is a key ingredient of success as a programmer. It doesn’t happen overnight, so have patience. Become fluent in as many environment tools as you can, then choose the ones that suit you best.

Probably the most common beginner mistake is to rush into development without having a firm grasp of their development environment. Most mistakes I talk about, I have made personally. That’s ok. It gives me perspective and room to grow.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

How Use PHPUnit Test in Laravel 5.1

Access all tutorials in sprocket icon.

June 12, 2015 from author Bill Keck.

Sometimes for beginners, the idea of PHPUnit testing code can be scary. You find yourself having to install the test framework, learn a whole new series of commands and methods, and half the time, you have no idea why it doesn’t work.

Fortunately, with Laravel 5.1, testing is incredibly easy, it is already integrated into the framework, ready to go, out of the box. To confirm this, you can run a simple command from the command line:



vendor/bin/phpunit --version

Tip for anyone who gets an error message about composer dependencies from the above. Try running:



vendor/phpunit/phpunit/phpunit --version 

In any event, once you have the correct path, it will return the following, and you know you are good to go:



PHPUnit 4.7.2 by Sebastian Bergmann and contributors.

Use the path that works for the rest of the tutorial.

Ok, great, so how do we run an actual test? Well, let's start by looking at the example test that comes with the Laravel install. Under your project folder, you will see a tests folder. Inside you will see ExampleTest.php:



<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class ExampleTest extends TestCase
{
    /**
     * A basic functional test example.
     *
     * @return void
     */
    public function testBasicExample()
    {
        $this->visit('/')
             ->see('Laravel 5');
    }
}

To run this test, just call it from the command line like so:



vendor/bin/phpunit

That will run all tests in the folder. If have a fresh install of Laravel, the test should find "Laravel 5' on the welcome view, which is where the '/' route points to. You will get a two line response. The first line tells you how many milliseconds it took to run the test and how much memory it consumed.

The second line will be highlighted in green, and look something like this:



OK(1 test, 1 assertion)

Now let's make it fail, so we can see what happens when it fails. Change 'Laravel 5' to 'Laravel 6' inside the test and run it again with:



vendor/bin/phpunit

You can see it gives a lot more output. There's too much for me to include here, so I'll give you the relevant bits. It starts with:



Time: 719 ms, Memory: 15.50Mb

There was 1 failure:

1) ExampleTest::testBasicExample
Failed asserting that '

Then it prints the html from the page. Then you get the following line:



' matches PCRE pattern "/Laravel 6/i".

That's the end of the statement of the failed assertion. So it's telling you precisely how it failed. How cool is that?

And then of course you get the red highlighted summary block:



FAILURES!
Tests: 1, Assertions: 1, Failures: 1.

With the red highlighting, there's no way to miss the fact that it didn't pass. Now you would think that every time you run a test, you would get red or green, but there's actually a third option.

If you have a mistake in the test code itself, the test doesn't run at all and it will simply return a command prompt on a new line. You can test this by removing the semicolon from inside the test method and running the test again.

One of the more time consuming tasks that I hear programmers talk about is testing forms. Laravel has made this incredibly easy. Let's create a test for registration. This assumes you have registration setup for your app. If you don't, set that up first, then come back to this tutorial.

So let's use artisan to make our test stub:



php artisan make:test RegistrationTest

Now, inside the tests folder, let's modify RegistrationTest.php with the following:



<?php

use Illuminate\Foundation\Testing\WithoutMiddleware;
use Illuminate\Foundation\Testing\DatabaseMigrations;
use Illuminate\Foundation\Testing\DatabaseTransactions;

class RegistrationTest extends TestCase
{

    use DatabaseTransactions;

    public function testNewUserRegistration()
    {
        $this->visit('auth/register')
            ->type('bob', 'name')
            ->type('hello1@in.com', 'email')
            ->type('hello1', 'password')
            ->type('hello1', 'password_confirmation')
            ->press('Register')
            ->seePageIs('/');
    }

}

Look at how intuitive the syntax is! Do I even need to explain what it does? Obviously the first parameter in each chained method is the value and the second is the name of the field.

For a full list of methods, check testing docs, they are well written and clear.

Note that if your path to registration is different than mine, you will have to adjust your test accordingly. Also, if you have different input fields in your form, adjust accordingly.

You'll also note that we are using a trait in our test class named DatabaseTransactions. What this does is rollback the insert to the database, so you don't have to gum it up with test data. Using the DatabaseMigrations trait will rollback the migration, which will drop the table. The WithoutMiddleware trait allows it to skip middleware for testing purposes.

You can read up on PHPUnit on the Official PHPUnit Site. Just remember that inside Laravel, we are extending TestCase for our test classes, not PHPUnit_Framework_TestCase.

Ok, so that's going to wrap up our primer on PHPUnit testing in Laravel 5.1.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

How to Use @inject in Blade in Laravel 5.1

Access all tutorials in sprocket icon.

June 12, 2015 from author Bill Keck.

In a previous tutorial, we looked at creating a laravel service provider for Laravel. A service provider is a beautiful aspect of the Laravel architecture, but in some cases, when you want to re-use a class in your views, you don’t need it.

Instead, you can use the @inject method in blade. It could work like this:



@section('content')

@inject('boom', 'App\Helpers\Contracts\RocketShipContract')

    {{ $boom->blastOff() }}

@endsection

Ok, so @section and @endsection are typical blade syntax to define where in the master page the ‘content’ will be placed. Then we can see we have the @inject method. The first parameter is the name of the local variable to hold the object, in this case I called it boom. You can call yours any name that falls within variable naming rules.

The next parameter is the class or contract you are instantiating. In this case, I’m calling a contract, because I have a service provider binding the contract to a concrete class. You can refer to that service provider tutorial for the exact reference.

Then in the dual curly brackets, which is again blade syntax to echo php, you see we are calling the blastOff method from the object instance variable $boom. The blastOff method simply returns a string of text. If you are curious why I chose boom, blastOff, and RocketShipContract, these were examples I was using in my service provider tutorial, which is a related subject. Check that out when you have a chance.

There’s an interesting example of @inject in a Laracast’s video where they use stats as an example, which is perhaps a closer to a real-world example.

Anyway, @inject offers you an easy alternative to service providers, allowing you to bring in reusable code that is not tied to a controller. As I’ve explained above, you can also use @inject in tandem with a service provider, when you want to call a contract instead of a concrete class.

Also note that you can place @inject outside of the @section where the object is being used. So if you want to perhaps place it at the top of the file, above the @extends line, you could do so. That might be more intuitive.


@inject('boom', 'App\Helpers\Contracts\RocketShipContract')

@extends('layouts.master')

@section('content')

    {{ $boom->blastOff() }}

@endsection

This looks really clean to me. That kind of flexibility is yet another reason to love the Laravel Framework.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.

How to Create a Service Provider in Laravel 5.1

Access all tutorials in sprocket icon.

June 11, 2015 from author Bill Keck.

A beginner-friendly tutorial on building a service provider in Laravel 5.1.

I mentioned in my last blog that I love the Laravel 5.1 architecture, especially when it comes to service providers, which are the building blocks of your application. Configuration of an application can often be tricky task, depending on the framework you are using, but lucky for us, this is a fairly simple task in Laravel.

So let’s start by creating a route that we’ll use for demonstration purposes. Go to app/Http/routes.php and add the following route:



Route::resource('demo', 'DemoController');

Since we’re using Route::resource, we get index, show, create, edit, update, store, and destroy routes defined for us.

Now in perfect symmetry, we can use our artisan command line tool to create a matching controller for us. Type the following:



php artisan make:controller DemoController

Let’s open that file and change the index method to the following:



public function index()
{

    return view('demo.index');
}

Now let’s make a folder for the view in app/Resources/views named Demo, and in that folder create a view named index.blade.php like so:



@extends('layouts.master')

@section('content')
<h1>Demo Page</h1>
@endsection

In this case we are pulling in our master page, which I have in the layouts folder, master.blade.php. If you have a master page with another name, use that instead. If you have no master page, simply remove that extends line altogether, along with the @section statements.

Assuming you have set up your development environment to resolve your domain, when you hit the route yourapplication.com/demo, you should see the words Demo Page.

Ok, so now let’s create a service provider. This service provider isn’t going to do anything particularly useful. It’s just going to show you how to set one up.

Let’s start by creating a Helpers folder in our app directory. Then inside the Helpers folder, create a Contracts folder. Inside the Contracts folder, create RocketShipContract.php with the following contents:



<?php

namespace App\Helpers\Contracts;

Interface RocketShipContract
{

    public function blastOff();


}

As you probably are aware, an interface is a contract that enforces architecture. In order for a class to implement the interface, it must contain a public function named blastOff.

So why bother making a contract? Well, one of the amazing features in Laravel is that you can type hint the contract, and the service provider will return an instance of whatever concrete class you have bound to it. This creates an incredibly flexible and loosely coupled structure because you will be able to easily swap out implementations with a single line of code. We will see how this works in a little while.

First, let’s create the concrete class. In the app/Helpers folder, create RocketShip.php with the following:



<?php

namespace app\Helpers;

use App\Helpers\Contracts\RocketShipContract;

class RocketShip implements RocketShipContract
{

    public function blastOff()
    {

        return 'Houston, we have ignition';

    }

}

You can see our concrete class doesn’t do much, but we are mainly interested in how all this stitches together. You can decide for yourself what services you want to provide to your application.

Ok, now we need to create the service provider, which will bind the contract and the concrete class. Go to your command line and type the following:



php artisan make:provider RocketShipServiceProvider

Hit enter and it will create the class for you.

The new file is located in app/Providers. Go ahead and change it to the following:



<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helpers\RocketLauncher;

class RocketShipServiceProvider extends ServiceProvider
{
    protected $defer = true;

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('App\Helpers\Contracts\RocketShipContract', function(){

            return new RocketShip();

        });
    }

    /**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['App\Helpers\Contracts\RocketShipContract'];
    }

}

So let’s look at the pieces:



<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Helpers\RocketShip;

class RocketShipServiceProvider extends ServiceProvider
{

All fairly straightforward. We have our namespace, use statements and class declaration. When you create service providers, you will have to import the concrete class, in this case RocketShip, as I did with the use statement.

Next we have:



    protected $defer = true;

Setting the $defer property to true means this class will only be loaded when necessary, so the application runs more efficiently.

Next we have the boot function, which is just an empty stub, since we are not configuring anything.

Following that, we have the register method:



/**
 * Register the application services.
 *
 * @return void
 */
public function register()
{
    $this->app->bind('App\Helpers\Contracts\RocketShipContract', function(){

        return new RocketShip();

    });
}

You can see we are using the bind method to bind the contract to the concrete class. This is the one place within the service provider where the concrete method is defined. So if you wanted to change which the class the binding will call, it’s quick and easy. We will see this in action later.

Finally, we have the provides method:



/**
     * Get the services provided by the provider.
     *
     * @return array
     */
    public function provides()
    {
        return ['App\Helpers\Contracts\RocketShipContract'];
    }

}

You need the above method if you are setting the $defer property to true.

All in all, this is a really simple class, which is part of the beauty of all this.

Ok, next we need to tell our application to look for this class, and we do that by adding it to the providers array in config/app.php.



        /*
         * Application Service Providers...
         */

        App\Providers\AppServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        App\Providers\RocketShipServiceProvider::class,

I included some of the other providers for reference, you can see our provider on the last line. Once you save this, you should be good to go.

So let’s go to our DemoController index action and modify it to the following:



public function index(RocketShipContract $rocketship)
{
        $boom = $rocketship->blastOff();

        return view('demo.index', compact('boom'));
}

So in this case, we are type hinting RocketShipContract and giving it an instance variable $rocketship. Laravel knows through the service provider that you actually want the RocketShip class because we bound it to the contract in the service provider. How cool is that?

Then we are simply calling the blastOff method and assigning it to a variable, which we will pass onto the view. Let’s modify the view:



@extends('layouts.master')


@section('content')

    {{ $boom }}

@endsection

You can see I’m using blade to echo the variable. So in your browser, you should see:



Houston, we have ignition.

So now to demonstrate ease at which you can swap out implementations, let’s create a second concrete class in our Helpers folder. Let’s call it RocketLauncher.php and place the following within it:



<?php

namespace app\Helpers;

use App\Helpers\Contracts\RocketShipContract;

class RocketLauncher implements RocketShipContract
{

    public function blastOff()
    {

        return 'Houston, we have launched!';

    }

}

You can see this is a lot like our RocketShip class, but our blastOff method is slightly different. So now to implement this, we simply change one line in our service provider in the register method:



public function register()
    {
        $this->app->bind('App\Helpers\Contracts\RocketShipContract', function(){

            return new RocketLauncher();

        });
    }


And also the use statement:



use App\Helpers\RocketLauncher;

And with those simple changes, we now have a different implementation bound to the contract and of course a new result in the browser.

Even though we did a super trivial example for this tutorial, you can see the benefits of this architecture. By coding to a contract instead of a concrete class, we gave ourselves flexibility and an easier way to maintain the code.

A couple of gotchas to look out for. You can’t rename the service provider without deleting and creating a new one from artisan because something behind the scenes causes the class not to be seen. It’s probably related to autoload. You can try running composer dump-autoload from the command line if you run into this type of situation. If that doesn’t work, delete the file and start over.

The other thing is don’t add the service provider to the config/app.php file until the last step. Having a class that doesn’t exist in there will mess up artisan.

The laravel framework has excellent documentation and you can read more about laravel service providers there.

I hope you have enjoyed this tutorial and found it useful. Click on the sprocket icon at the top of the page to see all tutorials. Please comment, share, and like if you can, thanks!

I don’t have a donate button, but If you would like to support my work and learn more about Laravel, you can do so by buying one of my books, Laraboot: laravel 5* For Beginners, I really appreciate it.