Member Since 5 Years Ago

Nottingham, Uk

Experience Points

2,150 experience to go until the next level!

In case you were wondering, you earn Laracasts experience when you:

  • Complete a lesson — 100pts
  • Create a forum thread — 50pts
  • Reply to a thread — 10pts
  • Leave a reply that is liked — 50pts
  • Receive a "Best Reply" award — 500pts
Lessons Completed
Best Reply Awards
Best Reply
  • start-engines Created with Sketch.

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • first-thousand Created with Sketch.

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • 1-year Created with Sketch.

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • 2-years Created with Sketch.

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • 3-years Created with Sketch.

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • 4-years Created with Sketch.

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • 5-years Created with Sketch.

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • school-session Created with Sketch.

    School In Session

    Earned when at least one Laracasts series has been fully completed.

  • welcome-newcomer Created with Sketch.

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • full-time-student Created with Sketch.

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • pay-it-forward Created with Sketch.

    Pay It Forward

    Earned once you receive your first "Best Reply" award on the Laracasts forum.

  • subscriber-token Created with Sketch.


    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.


    Earned if you have a lifetime subscription to Laracasts.

  • lara-evanghelist Created with Sketch.

    Laracasts Evangelist

    Earned if you share a link to Laracasts on social media. Please email [email protected] with your username and post URL to be awarded this badge.

  • chatty-cathy Created with Sketch.

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • lara-veteran Created with Sketch.

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • 10k-strong Created with Sketch.

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • lara-master Created with Sketch.

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • laracasts-tutor Created with Sketch.

    Laracasts Tutor

    Earned once your "Best Reply" award count is 100 or more.

  • laracasts-sensei Created with Sketch.

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • top-50 Created with Sketch.

    Top 50

    Earned once your experience points ranks in the top 50 of all Laracasts users.

Level 1
2,850 XP
21 Oct
4 years ago

BenSmith started a new conversation Testing Eloquent Models With PHPSpec


I'm having difficulties trying to test my models using PHPSpec. Here is an example method that I am trying to test:

 * Check if the request has any offers.
 * @return bool
public function hasOffers()
    return $this->offered->count() >= 1;

And my test:

function it_can_determine_whether_it_has_offers()

All of the methods I have on my models are around this level of complexity and should be very straight forward to test, I just can't get PHPSpec set up correctly.

When I run this I get

Fatal error: Call to a member function connection() on null in vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 2948

Any ideas?

15 Oct
4 years ago

BenSmith started a new conversation Quickly Find The Version Number Of A Composer Package

I often need to find the most recent version of a package. Rather than open up packagist, add the following to your .bashrc file (or similar):

alias ver='function _versions() { composer show $1 | grep versions }; _versions'

We can now run ver package name to get a list of versions:

$ ver illuminate/html
versions : * dev-master, 5.0.x-dev, 4.2.x-dev, v4.2.9, v4.2.8, v4.2.7, v4.2.6, v4.2.5, v4.2.4, v4.2.3, v4.2.2, v4.2.1, v4.2.0-BETA1, 4.1.x-dev, v4.1.30, v4.1.29, v4.1.28, v4.1.27, v4.1.26, v4.1.25, v4.1.24, v4.1.23, v4.1.22, v4.1.21, v4.1.20, v4.1.19, v4.1.18, v4.1.17, v4.1.16, v4.1.15, v4.1.14, v4.1.13, v4.1.12, v4.1.11, v4.1.10, v4.1.9, v4.1.8, v4.1.7, v4.1.6, v4.1.5, v4.1.4, v4.1.3, v4.1.2, v4.1.1, v4.1.0, 4.0.x-dev, v4.0.10, v4.0.9, v4.0.8, v4.0.7, v4.0.6, v4.0.5, v4.0.4, v4.0.3, v4.0.2, v4.0.1, v4.0.0, v4.0.0-BETA4

BenSmith started a new conversation Share Your PHPStorm Live Templates

One of the biggest improvements to my workflow over the last few months has been to create a live template for anything I find myself doing more than twice a day.

This new sub forum seems like a good place to share these templates and I would love to see any you have created and are particularly fond of.

Rather than just exporting all your templates into a file, I think it is probably better to just include them in a post with the following format:

Abbreviation Description


Here are some of mine:


Seeing Jeffrey using variations of these to quickly create forms was what first made me realise how much time could be saved using templates. These are integrated to work well with the Twitter Bootstrap framework.

fo Form open tag

{!! Form::open() !!}

fc Form close tag

{!! Form::close() !!}

textfield Text form field

<!--- $VALUE$ Field --->
<div class="form-group">
    {!! Form::label('$NAME$', '$VALUE$:') !!}
    {!! Form::text('$NAME$', null, ['class' => 'form-control']) !!}

emailfield Email form field

<!--- $VALUE$ Field --->
<div class="form-group">
    {!! Form::label('$NAME$', '$VALUE$:') !!}
    {!! Form::email('$NAME$', null, ['class' => 'form-control']) !!}

passwordfield Password form field

<!--- $VALUE$ Field --->
<div class="form-group">
    {!! Form::label('$NAME$', '$VALUE$:') !!}
    {!! Form::password('$NAME$', ['class' => 'form-control']) !!}

textareafield Text area form field

<!--- $VALUE$ Field --->
<div class="form-group">
    {!! Form::label('$NAME$', '$VALUE$:') !!}
    {!! Form::textarea('$NAME$', null, ['class' => 'form-control']) !!}

hiddenfield Hidden form field

{!! Form::hidden('$NAME$', $VALUE$) !!}

submitfield Submit form field

<!--- $VALUE$ Field --->
<div class="form-group">
    {!! Form::submit('$NAME$', ['class' => 'btn btn-primary']) !!}

req Require field (add in the attribute array of any form field type to make field required.

'required' => 'required'


I've been playing with 5.0 for a few weeks now and so I've added a few route annotation templates. I'm sure more will be added over the coming months.

anno Add docblock ready for annotations below

* @return Response

@G Get route annotation

@Get("$ROUTE$", as="$NAME$")

@P Post route annotation

@Post("$ROUTE$", as="$NAME$")

@M Get route annotation


Blade Live Templates

I’ve been using these less since native blade support was added to PHPStorm but they are still useful.

@ex Blade extend


@fe Blade foreach

@foreach($GROUP$ as $INDIVIDUAL$)

@if Blade if


@ife Blade if/else



@inc Blade include


@sect Blade section


@yi Blade yield


bb {{ }} unescaped blade tags

{{ $CODE$ }}

bbb {!! !!} escaped blade tags

{!! $CODE$ !!}

view New view from layout




A few testing templates, I’m only just getting properly into test so I will be adding to these.

cci Codeception $I->


@test Test outline

/** @test */
public function it_$METHOD$()
    // Given
    // When
    // Then


I use these when I'm working on a throw away project and need to quickly import some basic styles and scripts.

bootcss Bootstrap css CDN link

<link rel="stylesheet" href="//"/>

bootjs Bootstrap js CDN link

<script src="//"></script>

jquery jQuery CDN link

<script src="//"></script>

lorem lorem ipsum generator

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

Composer packages

I have a few packages that I add to every laravel install I do. Rather than have to remember the correct package number I just create a template to insert it into my composer file automatically (note: these are for Laravel 5).

gener Way/Generators

"way/generators": "~3.0",

illhtml Illuminate/Html

"illuminate/html": "~5.0",

reqdev Add require-dev to composer.json file

"require-dev": {


A few more that don’t quite fit into any category

lt Link to

{!! link_to('$PATH$', '$TEXT$') !!}

ltr Link to route

{!! link_to_route('$ROUTE$', '$TEXT$') !!}

errors Error loop

@foreach($errors->all() as $error)
    <li>{{ $error }}</li>

I have loads more but it's quite tiresome writing them, I'll add more a bit later today!

14 Oct
4 years ago

BenSmith left a reply on Laravel Just Jumped The Shark ... Annotations

Hell, if I was to repaint the sistine chapel ceiling, their faces would be up there :)

Someone with better photoshop skills than me, please make this a reality! I would love it as my desktop wallpaper, maybe give the guy on the left some pants though.

BenSmith left a reply on Cannot Find Module '.\vendor\laravel\elixir\Elixir'

A recent commit to elixir now has:

var elixir = require('laravel-elixir');

as the way to require elixir. That being said, I did a composer update and made the change above and now rather than the error you were getting, I'm getting:

throw err;
Error: Cannot find module 'laravel-elixir'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (pathtofile/Gulpfile.js:1:76)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)

11 Oct
4 years ago

BenSmith left a reply on Informal Poll: Routes File

@Cocoon, You can add filters (middleware) and prefixes to all methods in a controller:

 * @Controller(prefix="admin")
class RequestsController { }

BenSmith left a reply on Informal Poll: Routes File

If asked the question a couple of days ago, I would have strongly erred on the side of keeping the file. Now, having spent some time using with the new annotations I'm now leaning the other way.

As Jeffrey says, the inclusion of the file may be problematic to newcomers. It creates a point of friction at a very early stage of learning and for what should be a very straight forward subject.

Having read through the thread so far, I can see that this is definitely not the popular opinion. I would however be very interested in seeing how peoples answers would change if you asked the same question in a month or so, when people have had a chance to use them and Jeffrey had done a video or 2 outlining the changes and some of the benefits to using them.

BenSmith left a reply on Laravel Elixir

This is very cool, I got it working with my sass files within minutes however I'm having difficulties with my javascript files. I have my scripts in "resources/assets/scripts" with 2 subdirectories, one for vendor js (jquery, bootstrap, etc.) and another subdirectory for my own js.

In my previous gulp setup I had an array of my vendor js files in the order in which they needed to be included (jquery first etc.), and had a dedicated task to uglify and concatenate them to a vendor.js file. I then watched the javascript subdirectory with my own components and on a change I would uglify, concat and then merge them with the vendor file into a new main.js file.

I'm hoping with elixir this multi stepped approached is not necessary. Really all I need is to be able to specify an order that some vendor files should be loaded and then everything else can be arranged however.

I've played around with including .scripts() in my gulpfile but I wasn't getting anywhere and when the options I provided didn't cause a type error, gulp would run but the scripts task was never mentioned. Any help would be appreciated.

04 Oct
4 years ago

BenSmith left a reply on Laravel Db Designer

Would it be possible to create a package that would output a file (or upload a gist) representing the current database by parsing a combination of the migrations and eloquent models?

If you could then take this file and feed it into this tool, it would be a nice way of browsing the database structure at a high level. If a newcomer joins our team I think this would be a nice way of familiarising them with the database layout.

01 Oct
4 years ago

BenSmith left a reply on Happy First Birthday Laracasts!

Happy Birthday Laracasts! I've learn't more about web development this year than any other and it's no coincidence!

@bashy, the domain was originally registered and used by Maks Surgay but was transfered to Jeffrey in August 2013

29 Sep
4 years ago

BenSmith started a new conversation Specing A Command Handler

I posted earlier this week about the difficulties I'm having working out what / how to use phpspec with the command handler architecture. Rather than delay any longer I decided to get stuck and write some code.

My first job was to make an admin authentication system. It's almost the same as the standard login procedure but before logging a user in I check that they are an admin and if not then I reject their login attempt. Usually I would just do this in the controller but with the extra check I thought it would be better to use a command & handler.

My AdminLoginCommand object is very simple and contains just email and password fields. My controller method uses a request object to verify the presence of this info and I have implemented a toCommand method in a base request object that will return the class of the corresponding command object. My controller method is:

\\ Admin Sessions Controller
public function store(AdminLoginRequest $request)
 if( ! $this->execute($request->toCommand()))
    Flash::error('Invalid credentials');
    return redirect()->back()->withInput();

 Auth::attempt($request->only('email', 'password'));
 return redirect()->route('admin_dashboard');

My handler returns true or false depending on the success of the attempt. I do not actually log the user in within the handler but leave that to the controller.

My handler is also straight forward, it has two dependencies an instance of the Authenticator contract and a UserRepository. I first check to see if the credentials are valid, if they are not I return false. If they are I then get the user with the given email address and check that they are an admin.

\\ AdminLoginCommandHandler

public function __construct(Authenticator $authenticator, UsersRepository $repository)
 $this->authenticator = $authenticator;
 $this->repository = $repository;

public function handle($command)
 // Check if login credentials are valid
 if( ! $this->authenticator->validate((array) $command))
    return false;

 // If credentials are valid then check that the user is an admin
 $user = $this->repository->findByEmail($command->email);
 if( ! $user->hasRole('Admin')) {
    return false;

 return true;

I did not follow TDD, or at least not at the unit level, I did write a few acceptance level tests with Behat before writing anything at all and that was fairly straightforward.

And finally my spec:

class AdminLoginCommandHandlerSpec extends ObjectBehavior { function let(Authenticator $auth, UsersRepository $repository) { $this->beConstructedWith($auth, $repository); } function it_is_a_command_handler() { $this->shouldImplement('Laracasts\Commander\CommandHandler'); } function it_returns_false_if_the_credentials_given_are_invalid( Authenticator $auth, AdminLoginCommand $command) { $auth->validate(Argument::any())->willReturn(false); $this->handle($command)->shouldReturn(false); } function it_returns_false_if_the_credentials_are_valid_but_the_user_is_not_an_admin( Authenticator $auth, UsersRepository $repository, User $user, AdminLoginCommand $command) { $auth->validate(Argument::any())->willReturn(true); $repository->findByEmail(Argument::any())->willReturn($user); $user->hasRole('Admin')->willReturn(false); $this->handle($command)->shouldReturn(false); } function it_returns_true_if_the_credentials_are_valid_and_the_user_is_an_admin( Authenticator $auth, UsersRepository $repository, User $user, AdminLoginCommand $command) { $auth->validate(Argument::any())->willReturn(true); $repository->findByEmail(Argument::any())->willReturn($user); $user->hasRole('Admin')->willReturn(true); $this->handle($command)->shouldReturn(true); } }

I’m very wary of binding my spec too tightly to my implementation. I read @adamwathan post on this forum, in which he discusses the difference between query and command messages. Given that I am not changing the internal state of the application during this login request, I believe it is appropriate to just use stubs and not mocks and that by doing so this will also somewhat decouple my spec from my implementation.

I pass in both (prophesized) dependencies of my handler in the let method. It took me far longer than I would care to admit to work out that I had to pass these dependencies to the separate spec methods as well, if I wanted to set expectations for them (the PHPSpec documentation makes me realise how spoilt we are with Laravel’s brilliant docs).

The tests pass and I believe I have 100% coverage (not that it matters too much) however I’m really not sure if what I have done is even remotely correct. Any feedback would be greatly appreciated!

26 Sep
4 years ago

BenSmith started a new conversation A Couple Of Tips To Help Speed Up Your Database Seeders

Hi, I have just posted a new article on my blog with a few tips to speed up your database seeders. I managed to get my User table seed from 15 seconds down to just 1.6 seconds after making these changes.

If you have any other suggestions on improving the seed time I'd love to know, it's one of my pet hates having to wait for seeders/tests to run.

Also if you have any feedback on the article I'd love to hear it, I'm only just getting confident enough in my development career to feel like I have anything useful to say!

BenSmith left a reply on PHPStorm - Which Theme Do You Use?

I'm a big fan of light themes. For the last 6 months or so I've been using Dayle's Snappy Light theme:

20 Sep
5 years ago

BenSmith left a reply on Command Bus Stuff In Laravel 4.3

@nschiffelbein, thanks for the reply. I had completely forgotten that the commander package instantiated the command object for you.

The reason that I hardcoded the command path as a field within the request object was because I envisioned them being kept in different directories. I think it makes sense to store the request objects within the default App\Http\Requests namespace as in my mind they are not part of the core domain.

As far as I can remember, the commander package translates a command name to a handler by doing a string replace of command to handler. This will not work if the objects are stored in different namespaces.

For example if I have a request: App\Http\Requests\RegisterUserRequest and I try and translate it to a command it will return App\Http\Requests\RegisterUserCommand.

I'm not sure if there is a way to resolve this without hardcoding the command path into the request object. It's inelegant but it works. Let me know if you think of a way around it.

19 Sep
5 years ago

BenSmith left a reply on Command Bus Stuff In Laravel 4.3

I’ve just put together a quick implementation of how you could go about transforming a request to a command object. I’ve created a BaseRequest object that extends the FormRequest class and adds a toCommand function. All requests then extend this base request.

In the controller:

public function store(RegisterUserRequest $request, Authenticator $auth)
        $user = $this->execute($request->toCommand());

The base request class

<?php namespace Larabook\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class BaseRequest extends FormRequest {

    public function toCommand($options = [])
        $class = $this->command;

        if (!class_exists($class)) {
            $message = "Command object [$class] does not exist.";
            throw new Exception($message);

        $fields = array_merge($this->all(), $options);

        return $this->container->make($class, $fields);


The request class:

<?php namespace Larabook\Http\Requests;

class RegisterUserRequest extends BaseRequest {

    public $command = 'Larabook\Registration\RegisterUserCommand';



I don't like how we would now have to store the fully qualified command name on the controller but I can't see a way of resolving the command from the request without it being there.

It does allow for the easy addition of extra information to the command class that is not passed to us through the form. For example, imagine we have a form to post a status and we needed the status message and the logged in users id for the command. Rather than adding a hidden field in the form to contain the logged in users id we could add this to the command from our controller as follows:

public function store(PublishStatusRequest $request)
  $status = $this->execute($request->toCommand['user_id' => Auth::user()->id);
        Flash::message('Your status has been updated');
        return redirect()->back();

This would then populate our command with logged in users id. Let me know what you think. I'm sure there must be a more elegant way of doing this.

18 Sep
5 years ago

BenSmith started a new conversation What Should I Be Testing? Laravel 5 With A Command Architecture

Apologies for the length of this post, I wanted to try and get my current thoughts down concisely and ended up just doing a brain dump!

I’m just about to start a new project using the command bus architecture and I’m going to force myself to use TDD/BDD as much as possible. My problem is I don’t know what I should be testing and with what testing framework! Below are the types of testing I am thinking about from highest granularity down to the lowest, including my (possibly incorrect) definition of each and an example of usage:

Acceptance Testing

My plan at the moment is to use Behat 3 for my acceptance tests. These tests have no knowledge of the internals and interact with my code much like a user of the site would. I am most confident with these type of tests given I have just spent a few days learning Behat.

If I was testing the registration functionality of the site I would be testing that when a user fills out the registration form they then see a welcome message.

Functional Testing

I must confess I am still somewhat unclear on the difference between functional and acceptance testing (especially given that they mean different things to different people). In my mind, functional testing is similar to acceptance testing in that it interacts predominantly with the project through the user interface, however, it also has some access to the internals. For example, in a functional test we could check whether a record exists in the database.

Using the user registration example again, my functional test would check that when the user fills out the registration form: they are redirected to a certain page, a welcome message is shown but also we could check in the database if a user record was created.

I am unsure whether functional tests are truly necessary. I think that as long as I provide a number of scenarios for each acceptance test feature that this should cover most of the necessary checks. Please let me know if you think this is wrong.

Integration Testing

I think of integration tests as tests that cover a chunk of functionality that will involve multiple classes interacting with each other.

An example would be testing that a user repository persists a user. The test would involve creating a fake user, passing it to the repository, and then checking the database to see if a record was added.

I have in the past used Codeception for these type of tests however given that I plan on using Behat and PHPSpec (see below) I am somewhat apprehensive to add yet another testing framework. I think this type of test is important but is there any alternative method to do this with either of the previously mentioned tools?

Unit Testing

I am going to be using PHPSpec for my unit tests, I have used it a number of times on small learning projects and for the code katas on this site but never in a major project. I really like it but I am having troubles working out what I am should be testing within the command architecture. Here is a list of components that I am expecting to use within the command architecture/Laravel 5 and my current feelings on whether I should be testing them:

  • Command Objects - No need to test as they are are just data objects.
  • Request Objects - No need to test as they are part of the framework
  • Command Handlers - I usually set up my command handlers with a number of dependencies and then the handler is just used to pass the relevant information to these objects. Does this mean that I should just be mocking the dependencies and checking that the methods are called? This seems to me like it is tying me to my implementation too much.
  • Controllers - If I am just transforming a request object to a command object and passing it to the command bus, is there any need to test the controller given that it will be covered by the acceptance tests?

I think basically I need to see a fully tested project that uses the command architecture. I have done the Larabook series on here and while very helpful, unit testing wasn’t mentioned. If you’ve read this far, many thanks, any advice would be appreciated.

TL;DR: What types of testing should I do, what tools should I use to for each type and what should I be unit testing within Laravel 5 / the command architecture?

BenSmith left a reply on Sublime Laravel And Php Specific Packages.

The functionality you've asked for falls more within the domain of an IDE than for a text editor like Sublime Text. PhpStorm is the stand out PHP IDE and there is a great (series on Laracasts)[] on using it effectively.

Up until I joined Laracasts I was an avid ST user, now I only use it for making quick edits and leave the heavy lifting to PhpStorm, give it a try!

16 Sep
5 years ago

BenSmith left a reply on How To Quickly Find Most Recent Versions For A Package?

Just in case anyone wants a quick way to find the most recent versions of a package from the command line. Add the following to your bashrc file (or similar)

alias ver='function _versions() { composer show $1 | grep versions }; _versions'

This allows you to use:

ver phpspec/phpspec

to return a list of the versions like so:

versions : dev-master, 2.1.x-dev, 2.1.0-RC1, * 2.0.1, 2.0.0, 2.0.0-RC4, 2.0.0-RC3, 2.0.0-RC2, 2.0.0-RC1, 2.0.0-BETA4, 2.0.0-BETA3, 2.0.0-BETA2, 2.0.0-BETA1, 1.4.3, 1.4.2, 1.4.1, 1.4.0
15 Sep
5 years ago

BenSmith left a reply on How To Quickly Find Most Recent Versions For A Package?

Ughhh.... I looked through composers list of commands prior to posting because I was convinced that this functionality must already exist. I don't know how this didn't catch my eye, I think I need to go to bed.

Anyway, thanks very much!

BenSmith started a new conversation How To Quickly Find Most Recent Versions For A Package?

What is the quickest way that you know, to find the most recently released version of a package? I know that I could go to Packagist and search for the package and it would probably take less than 10 seconds but I do this so often that if there is a better way, I would like to know!

My ideal solution would be something built into composer such that when I do for example:

 composer require phpspec/phpspec

Then as well as asking me for the version constraints, it would also show the 3 most recently tagged releases, so for this example it would show:

Please provide a version constraint for the phpspec/phpspec requirement (Most Recent: “2.1.*@dev" | 2.1.0-RC1 | 2.0.1)

This would save me a few seconds every time I had to add a package. Is there a solution already out there that I don’t know about?

12 Sep
5 years ago

BenSmith left a reply on Command Bus Stuff In Laravel 4.3

@bbloom, I rewrote the Larabook project using 5.0 using requests in lieu of commands and replacing commander with @flyingfoxx commandcenter package, see here for more information.

11 Sep
5 years ago

BenSmith left a reply on The New Way To Submit Laravel Bug Reports

Awesome idea. A leaderboard to track who fixes the most Liferaft reports would be an interesting addition. There's nothing like a little gameification to incentivise people.

BenSmith started a new conversation Larabook 2.0 Rewritten For 4.3 And Using Requests Instead Of Command Objects

I was browsing the Laracasts forum last week and came across a post by @JeffreyWay in which he suggested using the new Laravel 4.3 form request classes as commands within the command bus architecture.

I decided that I would like to give this a try but needed a small project to test it out on. Having just finished the most recent episode of the Larabook series it was fresh in my mind and so I decided to build Larabook 2.0 using this approach.

Later in Jeffreys thread @flyingfoxx mentioned that he had updated his CommandCenter package to allow for request objects to be passed to the command bus. The command center package is strongly inspired by the commander package and using it is for the most part almost identical.

In addition to using requests in lieu of commands I rewrote the code to be more idiomatic to Laravel 4.3. This involved making use of requests, updating the app structure, using the new helper functions wherever possible, updating the blade tags etc. You can find the finished project here, it is up to date with the most recent Larabook lesson in the series (30).

Below are a few of the changes that I had to make and some of the issues I ran into whilst updating.

  • The sass directory is now in resources/sass.
  • There was no need to add the laracasts/validation package as we can just use the in-request validation method.
  • Global exception catching goes in app/providers/ErrorServiceProvider
  • We no longer need to explicitly catch validation errors as we are redirected back by default if the request validation fails
  • Rather than placing our view composers in the base controller (which no longer exists in 4.3) the more idiomatic approach would be to place it in a custom service provider. I initially decided to use this approach however I was having problems caused by the order in which the service providers are called. I ended up creating a base controller and adding the view controllers back, this also had the advantage of being able to add the commander trait to just the base controller.
  • Removed all requests from the http/requests directory and put them in folders that I would normally put the commands in.

Having used requests in this project, I cannot see the need to create additional command objects. The names of the requests are identical to those that I would use for my commands but also have built in validation, allowing me to sure that my commands hold the information I require.

One shortcoming is the inability to easily add extra information to the request object before we pass the request to the command bus. This means that we make more use of hidden fields to add this data into the request automatically. By doing so, it becomes possible for malicious users to manually change this data.

For example, when following a user we need the command/request to have the id of the logged in user and the id of the user to be followed. We would normally pass the logged in users id to the command in the controller however now that we are using requests we pass this into the form as a hidden field. We must now use the authorise method in the request to check to see whether the logged in users id matches that of the passed in user_id. If someone were to use this approach but without adding the check then a malicious user could follow someone on another users behalf.

I am a complete domain-driven design beginner so any comments you have would be much appreciated! 

10 Sep
5 years ago

BenSmith left a reply on New Blade Tag For Unescaped Data. Thoughts?

Thanks for the reply Taylor. Whilst changing the structure may not be a big update to the way the framework works internally, for us mere mortals it's a huge departure from what we've been used to, both in terms of file placement but also the bringing of service providers to prominence.

The providers for the legacy application and the setRawTags helper method will shorten the upgrade process, however when I am updating (and I may well be a small minority here), I want my code to be as idiomatic to the framework as possible. With all the changes this could easily take a few hours, moving files into their correct places, adding requests, updating blade tags etc.

The more I have thought about it, the more I agree with the removal of form and html from the core, my only worry is that new members of the community may completely miss out on what can be a huge timesaver. If Laracasts were to release a (free?) video about the form and html packages it would give us a place to point new users if they were writing out forms manually. All in all though, the new additions are incredible, thanks Taylor.

@rspahni - The service provider ordering bit me yesterday when I was trying to set up a provider for adding view composers. In the end I just created a base controller and stuck it in there like I used to.

BenSmith started a new conversation [4.3] How To Validate Route Parameters Within Request Objects

I'm currently porting over Larabook to 4.3 (I'll post it here once complete) and I've hit a speed bump. I'm in the process of adding the unfollow user functionality and my unfollow form sends a delete request to follows/{followed_id} where followed id is the id of the user to unfollow.

Now, within my request object I would like to like to add a validation rule of 'exists:users,id' (no point in making it required as it must be present for the form to submit). One way to do this would just be to add the followed_id variable as a hidden field in the unfollow form. Whilst easy enough to do, it seems a bit strange given that we have access to this value in the request object through $request->route()->parameter('followed_id'). Is this the suggested approach or is there another way that I am overlooking.

09 Sep
5 years ago

BenSmith left a reply on New Blade Tag For Unescaped Data. Thoughts?

100% agree with you, we're now seeing 5.0, the changes are too comprehensive for anything else. I think it would be wise for Taylor to confirm that this is the case so that people know what they're getting themselves into if they decide to make the jump early.

I'm still somewhat surprised about the form class being dropped. I can see the reasoning but to me forms are such a fundamental part of web development that having no built in way of making it as easy as possible to create them is a bit strange.

I've spent a bit of time recently trying out Ruby on Rails to see how Laravel compares and I was really impressed with how easy it was to make forms and populate them with the necessary information.

08 Sep
5 years ago

BenSmith started a new conversation New Blade Tag For Unescaped Data. Thoughts?

I've been messing around with 4.3 for the past couple of days and today I did a composer update right in the middle of Taylor fixing/changing a load of stuff. Was causing me some errors so I decided to look at the recent changes and noticed this Tweak how Blade echo escaping works for more safety.

This change is in conjunction with making both {{ }} and {{{ }}} escape values by default. This means that {{ link_to_route('login_path') }} will no longer output the html to the page and you will instead have to use {!! link_to_route('login_path') !!} .

I'm for the change as it reduces the risk of code injection but I do think it will break a lot of existing code. Will this make the next version more likely to be 5.0 than 4.3?. I'm also worried that it will mean yet more delays to get full blade support for PHPStorm :)

What are your thoughts?

02 Sep
5 years ago

BenSmith left a reply on Email Confirmation Database Decision

As you say, it would be possible to have just the one confirmation_code column and then once the user has confirmed their email address we set this value to null. Checking for a confirmed user then just become a check on whether the confirmation code is set.

The two approaches are much the same and it really just comes down to personal preference. The 2 column approach to me seems more explicit in that we can just look at the confirmed boolean to check for confirmation. I could definitely understand using the one column approach to minimize the number of columns in the table.

In regards to the inline vs new table discussion, I personally would use the inline approach unless I was implementing expiring confirmation links which may also be the reason that Taylor has for creating a separate table for password reminders as they also expire.

If the confirmation code was on the users table and we decided to use the updated_at timestamp to check the validity of the confirmation code, if we allow the user to update their account prior to confirming their account, then checking whether updated_at is within an hour of the confirmation time would allow a user to confirm there account way after the confirmation code was created.

If we instead use the created_at timestamp then we run into a different problem. If the confirmation link is valid for an hour and the user does not confirm within this time period we would probably want a way for the user to request a new confirmation link containing a new confirmation code. If the user does this and we are still checking the time that the user was created is within an hour of the confirmation time then it will fail.

If a separate confirmation table is used then we don't have to worry about a user updating their account information changing the updated_at timestamp of the timestamp and if the user requests a new confirmation code then we can just delete the current entry in the confirmation table and create a new one allowing us to use either the created_at or updated_at timestamp to check whether our confirmation code is valid.

Sorry if this doesn't make much sense, when I'm very tired I tend to ramble. I might tidy it up tomorrow and make it more coherent.

BenSmith left a reply on Email Confirmation Database Decision

I wrote an article on email confirmation a few weeks ago that you can find here. In the article I use 2 columns on the users table to keep track of the confirmation process.

In one I store whether the user has confirmed their email address and in the other I store the confirmation code that I need to receive from the user to confirm the account. The article goes in to much greater depth, give it a read!