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.