davestewart

Front end developer at Freelance

Hire Me

Experience

50,095

56 Best Reply Awards

  • Member Since 3 Years Ago
  • 156 Lessons Completed
  • 3 Favorites

11th December, 2017

davestewart left a reply on Update, Create And Delete HasMany() Relations In One Go • 7 months ago

Thanks for confirming @Snapey.

Hopefully this post will be useful to someone else anyway.

davestewart left a reply on Update, Create And Delete HasMany() Relations In One Go • 7 months ago

I guess it's a manual job then:

function getCrud($oldData, $newData)
{
    // ids
    $oldIds = array_pluck($oldData, 'id');
    $newIds = array_filter(array_pluck($newData, 'id'), 'is_numeric');

    // groups
    $delete = collect($oldData)
        ->filter(function ($model) use ($newIds) {
            return !in_array($model->id, $newIds);
        })
        ->toArray();
    $update = collect($newData)
        ->filter(function ($model) use ($oldIds) {
            return property_exists($model, 'id') && in_array($model->id, $oldIds);
        })
        ->toArray();
    $create = collect($newData)
        ->filter(function ($model) {
            return !property_exists($model, 'id');
        })
        ->toArray();

    // return
    return compact('delete', 'update', 'create');
}

// data
$oldData = json_decode('[{"id":1,"name":"one"},{"id":2,"name":"two"}]');
$newData = json_decode('[{"id":2,"name":"TWO"},{"name":"three"}]');

// debug
$results = getCrud(collect($oldData), collect($newData));
print_r($results);
Array
(
    [delete] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 1
                    [name] => one
                )

        )

    [update] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 2
                    [name] => TWO
                )

        )

    [create] => Array
        (
            [1] => stdClass Object
                (
                    [name] => three
                )

        )

)

davestewart started a new conversation Update, Create And Delete HasMany() Relations In One Go • 7 months ago

Is it possible to pass an array Eloquent and have it update, create or delete relations in one shot?

My usage: a SPA and a user has many addresses:

  • let's say he has addresses 1 and 2, and these are downloaded to the app.
  • in the app, the user deletes 1, amends 2, and adds a 3rd.
  • we now have addresses 2 and 3

When I upload to the server, I want to do a diff on existing addresses, and take action accordingly:

  • delete address 1
  • update address 2
  • create address 3

Is there a built-in way to do this?

The other approach I suppose would be to do this one at a time, but in my case, I want the user to be able to update various forms in sequence, then only at the end submit data.

So ideally I'd have something like:

$user->updateRelations($arr)

But happy to do it all manually.

Cheers, Dave

21st August, 2017

davestewart left a reply on Calling A Controller From Within Laravel • 11 months ago

Your used method bypasses all of the middlewares as it goes directly to the controller and not thru the route engine which would normally apply the middlewares. Also, you won't be able to have model binding too as it is done via router too.

Hey @ModestasV - yes, the use case is atypical! Hense, asking the question :)

As no one has said "Oh, you can use this method" I'm thinking Guzzle would probably be the safest way to do this.

davestewart left a reply on Calling A Controller From Within Laravel • 11 months ago

As to your described case - a controller should NEVER call another controller in any case

Well this is what Guzzle does.

davestewart left a reply on Calling A Controller From Within Laravel • 11 months ago

To allay your fears, the wider problem I'm looking to re-work is calling controllers in Sketchpad, which are the primary units for organising code.

Right now, a request comes in, I determine the controller from the last controller scan, then use some custom code to assign objects and values.

It works just fine, but I think skips middleware, and I haven't really tested for form requests or models. Additionally, I've had a recent request to see if it could be used for APIs (yes I know Postman is a better candidate).

So I just wanted to see what / if there were the options.

davestewart left a reply on Calling A Controller From Within Laravel • 11 months ago

It's calling an internal API, so would need to be authed and validated at the very least!

davestewart started a new conversation Calling A Controller From Within Laravel • 11 months ago

Is there a way to make request, using the full routing setup of your app, via Laravel, or have you got to use something like cURL or Guzzle?

I know you can do app()->call() but does that include things like FormRequests and Route Model Binding? And I presume it almost certainly leaves out middleware?

And before anyone suggests a Service, nope, this isn't the problem I'm trying to solve :)

Thanks.

15th August, 2017

davestewart left a reply on Architecture And/or Schema For Managing And Storing Single Values From Select Lists • 11 months ago

We store all select values (I assume you mean HTML select element options) in a config file, which is loaded into our SPA on start.

The user selections are stored to local storage, and loaded into Vuex when the app boots.

Not totally sure what you're trying to do, but it seems like storing JSON values would be the way to go here?

1st August, 2017

28th July, 2017

davestewart left a reply on Validation: Can't Get `required_if` Working • 11 months ago

Thanks! Certainly an option.

But I assume the point of the required_if rule is to mange this without extra code.

So that's what I'd like to do in the first instance.

davestewart started a new conversation Validation: Can't Get `required_if` Working • 11 months ago

I have a validation requirement to check a user's credit rating.

They can either pass:

  • an estimated credit rating, i.e. good
  • an actual rating provider, i.e. Experian and a credit score, i.e. 500

The front end will pass all three values, but only the rating or the provider and score will be passed:


{
    rating: "", 
    provider: "", 
    score: 0
}

My validation looks like this:

'credit.rating' => 'nullable|string',
'credit.provider' => 'nullable|string',
'credit.score' => 'nullable|required_if:credit.provider,==,|numeric|min:200',

I've tried various combinations of the the required_if format, but no matter what I do, I get:

The ‘credit.score’ field must be at least ‘200’

The docs are at best vague and at worst, useless for this - I had to find out what I got here from google.

How do I validate score only if provider is filled?

Cheers, Dave

24th July, 2017

davestewart left a reply on Sending Requests Into Services Or Models • 11 months ago

@topvillas agree with you about a DTO and in a way a custom FormRequest solves that.

@MikeHopley Ha ha, great analogy! And agreed.

I'm actually new to FormRequests as well, but I've come to rather like them. At first, I was like "why create a whole extra class, just to add validation code that you would have just added in the controller?"

However, it's quite nice to see all the form validation logic in one place, especially as we're building this for an API and using the top level exception hander to convert any validation error to JSON in one single place.

So the idea of treating the custom FormRequest as as a DTO with a few power methods on it appeals for this reason.

So, yes, we'll suck it and see!

Then report back :)

davestewart left a reply on Sending Requests Into Services Or Models • 11 months ago

Hey fellas,

Great input and perspective, thanks!

And Mike, I'm sure you're not!

I agree with you both that sacrificing dogmatism for clarity c/should be the way to go in situations that call for it.

Perhaps a compromise should be to beef up the custom FormRequest class with additional getters, that way a lot of the logic could be in one place?

// CustomRequest
$customer = $request->getCustomer();
$foo = $request->getFoo();

// even
list($foo, $bar, $baz) = $request->getData();

We could even use traits for requests with common parameters...

Thoughts?

davestewart started a new conversation Sending Requests Into Services Or Models • 11 months ago

Hey all,

It's been a while since I've posted :)

I'm working with an outsourcing company and it's been a battle to bring their architecture and coding standards up to something approaching useable.

Now I have them using proper service classes and have deleted the hundreds of try/catches that were littering the code, we're getting there, but they seem intent on passing Request objects into the rest of the system (even to models), rather than extracting the components of the Request in the Controller, then passing them to parameterised methods:

function doSomething ($request) { ... }
function doSomething (Customer $customer, Foo $foo, Bar $bar) { ... }

To me, it's a major code smell, doesn't surface the intent of the system properly, and would make testing more difficult.

I get that there are times when the Request class is a useful wrapper, but in Models and Services it just feels lazy and something that will cause problems later.

We are using FormRequests which adds an extra layer of resilience, but does anyone have any thoughts on this?

Thanks, Dave

6th June, 2017

davestewart left a reply on Sketchpad: Upcoming Laravel Package • 1 year ago

Thanks @KNietzsche! Appreciated :)

I've a new thread I'm using for announcements on Sketchpad now; you can find it here:

23rd May, 2017

davestewart left a reply on Announcement: Laravel Sketchpad 1.2 Is Out • 1 year ago

I've added a new video showing day-to-day development with Sketchpad, developing various snippets into reusable tools:

https://youtu.be/bKSAONBKuEA

17th May, 2017

davestewart left a reply on Announcement: Laravel Sketchpad 1.2 Is Out • 1 year ago

Yeah - I really don't get why folks don't get it! This is the main issue at the moment.... what am I doing wrong?

I find that most sites I do I write as much code that doesn't get used as the code that makes it into the final site. This could be:

  • just finding out how a function or API works (hence the name)
  • experimental stuff, or building features that need somewhere to live before they make it into a page or service
  • tooling, which needs to live outside the main site

The tooling bit is really interesting, as it fills a space between Commands, Jobs and Tests; you rapidly develop code in your IDE, view updates live in the browser with the live reload plugin, use the PHP helpers to generate and inspect decent, legible output, and interact with your tool via the UI and on-screen parameters.

I'm sure there will be folks who just won't develop this way, but I'd be interested in other developer's thoughts to help me hone my communication.

The next two videos are going to be:

  • Development - live coding an everyday tool
  • "Application" setup - Using sketchpad as your entire application

:D

davestewart left a reply on Announcement: Laravel Sketchpad 1.2 Is Out • 1 year ago

Yes... there's been a lot of iteration of the last year!

So many mistakes made, so many times I've changed my mind, so many times I thought this way would be the way to go, then it turned out to be that way.

I have a couple of lists, and will probably go over the commits at some point to do something like that.

davestewart started a new conversation Announcement: Laravel Sketchpad 1.2 Is Out • 1 year ago

My bolt-on development environment for Laravel is officially released today.

image

There is a demo online here:

And a couple of videos:

New features include:

  • Completely reworked live documentation (see demo)
  • New customisation and admin options
  • New top-level Search and Favourites pages
  • New @field tag supports new HTML5 input types, <select> and <dataset> controls
  • New helpers and various coding / tooling improvements
  • Various front end, interactivity, and formatting tweaks / fixes
  • Basic admin permissions to prevent showing of Setup and Settings pages
  • Test vs Run mode

26th April, 2017

davestewart started a new conversation How Is The Performance For Sharing Valet Sites? • 1 year ago

We have a server setup at the moment where we a single host machine using AMPPS which serves various kiosk machines over a local network.

We serve a decent amount images (which animate) from the host machine, to up to 3 kiosks and have no performance issues.

We are thinking about moving the whole setup to Laravel Valet, and using its share feature.

Not having tested this yet, how is the performance? Is it straight across the local network, or (looking at the URL) does it go into the cloud or anything?

Thanks,

Dave

21st April, 2017

davestewart left a reply on Set Session Weirdness In AppServiceProvider • 1 year ago

OK, testing in 5.4 and this seems to be OK. I figure a bug in 5.2 then.

davestewart started a new conversation Failed Posts Discard Current Edits. • 1 year ago

If I submit a post, but:

  • forget to click the "I am not a robot" button
  • click submit before it's finished thinking
  • it decides to reset

...then the post reloads, but without my last edits.

I've cleared cookies, and logged in and out, but no joy.

It's particularly frustrating!

davestewart started a new conversation Set Session Weirdness In AppServiceProvider • 1 year ago

I'm trying to do something fairly basic; set a session variable in the AppServiceProvider. The value will be used by a 3rd-party package (that I'm writing) that loads later to override some of its settings.

This works, in the boot process, but if I dump the session in a controller later, the session value NEVER changes after its initial set!

// AppServiceProvider
public function boot()
{
    dump(\Session::get('test'));
    \Session::put('test', microtime()); // won't update on subsequent requests
    dump(\Session::get('test'));
}

// Package
public function init ()
{
    $value = \Session::get('test'); // gets the correct value
}

// Controller
public function dumpSession ()
{
    print_r(\Session::all()); // new value never shows!
}

It's very strange. I can't trust my session.

Am I missing something?

18th April, 2017

davestewart left a reply on [announcement] Laravel Sketchpad • 1 year ago

Just to let everyone know, Sketchpad is now fully released, with a few new features added as well.

I updated the GIF in the initial thread post, so take a look at that to get the idea.

More info on the wiki of course!

Cheers :)

12th April, 2017

davestewart left a reply on Ways Of Loading Relevant User Info Without Hitting DB Every Time • 1 year ago

JavaScript local storage is another.

10th April, 2017

davestewart started a new conversation Homestead Instance Per Group Of Projects • 1 year ago

I have a client with multiple (related) websites, and some common resources.

It would be nice to be able to configure just these sites in a single .yaml file.

Is it possible to either a) set up a Homestead instance to serve these sites as a group:

+- client           <- install homestead here
    +- site.foo
    +- site.bar
    +- site.baz
    +- common
    +- shared

Or b) set up a single .yaml file to run from the terminal, something like:

homestead up --config client.yaml

Thanks, Dave

6th April, 2017

davestewart left a reply on [announcement] Laravel Sketchpad • 1 year ago

OK, RC4 is available now, with those pesky install bugs fixed.

5th April, 2017

davestewart left a reply on [announcement] Laravel Sketchpad • 1 year ago

Hey Will,

Thanks for testing, and the feedback.

That's weird, not something I've come across in testing, but I suspect is permissions on your storage directory... or maybe default permissions on the folder I create in the storage directory.

The settings file is copied from the here:

Once copied, I write some values to it, so a manual copy probably isn't the best (that prompt was from a much earlier attempt at the installer).

Can you give me any more info about your storage folder? Location, permissions, etc.

Once that is sorted, everything else should take care of itself.

It doesn't seem to matter how much you test, there is always more to go wrong! I should have publisized this more widely in beta :(

davestewart left a reply on [announcement] Laravel Sketchpad • 1 year ago

I've just released 1.0.0-RC3, which I'm hoping is the final release candidate before full 1.0.0:

If anyone has a 10 minutes spare to install and have a quick go, that would be really useful.

Hopefully you'll get it and find it useful as well, if not, please do fire questions my way so I can make things more obvious!

3rd April, 2017

davestewart left a reply on Can A Package's ServiceProvider Access Configuration Values It Just Published? • 1 year ago

Not totally sure on your use case, but did you look at mergeConfigFrom() ?

30th March, 2017

davestewart left a reply on [announcement] Laravel Sketchpad 1.0.0-RC • 1 year ago

Oh my goodness - doesn't stuff scroll off quick! I may have to make a few "strategic" bumps :P

I'll be doing a proper video over the weekend, and will announce a full release next week, so that should make it easier for folks to grok and comment on it :)

And, thanks :)

davestewart started a new conversation [announcement] Laravel Sketchpad 1.0.0-RC • 1 year ago

Hey all,

About a year ago, I posted about a package I was working on called Sketchpad, which I'm pleased to say – after a 6 month hiatus, and a huge amount of work – is now complete!

I've used it in it's Beta state on a couple of commercial jobs in the last year, and it's been invaluable for running code "outside of" the main website's concerns.

What it is

Sketchpad is an interactive front-end for your Laravel back-end; a place to write, test, experiment and execute code, or just a place to group useful tools and functions you want easy access to.

image

What it does

It lists controllers and methods from folders of your choice, and allows you to run them without setting up routing, views, etc.

You can navigate to, and run any controller method, even modify parameter values, all from a friendly UI.

It comes with a bunch of useful tools and PHP functions to make it easy to rattle out quick coding tests.

There's also a video of the pre-beta version if you want to see it in action.

Uses

  • Test out new coding ideas
  • Develop tools and utilities for everyday work
  • Debug applications in the same environment they're running in
  • Practice with new libraries or APIs with your existing code
  • Give new hires a place to get up to speed with the codebase
  • Double check how that rarely-used function actually works
  • Give all that "secret" or commented-out code somewhere to live
  • Live-document existing features and tools
  • Generate and manage reports

Install

Installation instructions for the RC release are here:

More info

For more info, ask questions here, or check the GitHub wiki:

20th February, 2017

davestewart left a reply on Dd() - Not Well Formed Numeric Value Encountered • 1 year ago

@dailysleaze - thanks!

composer update did the trick :)

27th January, 2017

davestewart left a reply on Great Article On JOINs • 1 year ago

Ah, good resource!

davestewart started a new conversation Great Article On JOINs • 1 year ago

Hey all,

I recently discovered the DZone website, which has a ton of useful resources for developers.

This morning, this arrived in my in box:

I often struggle getting JOINs right, so thought I would share as it looks really useful.

Cheers, Dave

1st January, 2017

davestewart left a reply on Testing An Obese Test • 1 year ago

@ohffs - big daddy! Showing your age (and nationality) there ????

14th December, 2016

davestewart left a reply on Full Stack Developer • 1 year ago

I just saw this on CommitStrip which may at least amuse you :)

commitstrip

davestewart left a reply on Getting The Array Of Values • 1 year ago

Is $id actually an array, or you do you need to match or explode it first?

davestewart left a reply on Custom Class For External API Calls, Where To Put It Inside Laravel 5.3? • 1 year ago

I want to code a class for calls to an external rest api

Sounds more like a service to me.

davestewart left a reply on What Are You Working On ? • 1 year ago

@IsaacBen I thought you were making an insightful / funny joke about designing a pen and paper project management system for a client.

That would be cool! :P

13th December, 2016

davestewart left a reply on Full Stack Developer • 1 year ago

There's only so much time in the day to learn things, so you can be good at both, but practically it will take you twice as long to reach the same standard, or you'll be lacking in specialisms for both in the same timeframe.

I'm primarily a front end dev, but have been working with PHP for around 15 years, but never considered myself "full stack", more a front end guy with reasonable back end skills.

However, my previous two jobs have both been full stack (using Laravel, which I'm now pretty comfy with) and I was the only developer, so I now loosely call myself a "front-end, full-stack developer" and caveat this for any jobs I go with that a "real" back end guy will know far more than me about database flavours, security, and all the other "back end" stuff than I, so if they need something really up there, either to hire someone else, or to have me work with a primarily back end guy.

The one thing I can't stand is supposedly "full stack" folks who don't caveat their areas of expertise. I worked on a Rails/JavaScript site last year where the front end was written mainly by a "full stack" Node guy (it's all JavaScript, right!?) and it was an absolute f-ing mess.

Front end is now so technical that it makes it very difficult to be across both disciplines and really compete.

One of the phrases I've heard recently is "full stack integrator" which I think makes a lot of sense, and if you google the same term, you'll see a lot of people talking about "the myth of the full stack developer".

Food for thought!

davestewart left a reply on I Need Some Advice, Which Macbook To Buy? • 1 year ago

I don't expect to change your mind as you said it's made up, but...

I bought the 13" and 15" models last year to compare them. My head said 15" my heart said 13"... and (for once) I went with my heart.

At home I use 2 x HD external flat screens on stands so I have 3 screens and am very productive. When I'm no the road, the laptop is so light, and so easy to whip out and put away, I know I made the right choice by getting the lighter, more portable version.

I use multiple desktops to make it easy to switch apps using trackpad gestures, and it's lovely. Even though the 15" has quad core and better graphics, I've been amazed at just how many apps and tabs I can have open, and work just fine.

13" seems to be the most popular amongst developers at conferences, meetups, etc, and now I can see why.

Just my 2p :)

davestewart left a reply on What Are You Working On ? • 1 year ago

Ahhh @ohffs - I should have tapped you for input for an article I've just written for net magazine. I'm sure you would agree with most of it though.

I'm about to get back to working on Sketchpad, which I've taken a break from for a couple of months due to work pressure.

It's a playground to test out code and build reusable tools, and installs as a module alongside your PHP projects:

sketchpad

I should get some time over Christmas to get it complete. I used to finish projects must faster than this, I promise!

24th November, 2016

davestewart started a new conversation I Just Want To Say Thank You For Choosing A Sensible Font Size • 1 year ago

There seems to be some trend in the last couple of years to choose increasingly-larger font sizes.

The (major brand) site I'm contracting on at the moment, the default font is 16px and goes up to about 24px, even for body copy and it's infuriating. The Jetbrains forum uses 16px or 18px as its base size, and it's just too much.

Seeing 12px on the index page is most pleasing.

Well done!

18th November, 2016

davestewart left a reply on Laracasts Refresh • 1 year ago

I'll add to the prevailing view that it looks brilliant! Not in any way overpowering, lovely use of space, great highlight colours, and really easy to read.

My only comments would be:

  • the left hand menu requires a lot of scrolling; maybe a toggle at the top?
  • would be good to see horizontal scrolling on code blocks as wrapping makes them hard to read

Well done!

17th November, 2016

16th November, 2016

davestewart started a new conversation StateMachine: New State Management Library For JavaScript (including Vue) • 1 year ago

Hey all,

So I've been working on a JavaScript State Machine implementation for the last 6 weeks or so, which I've now released.

It's in a different category from Vuex/Redux etc as it's based around named transitions from state to state, rather than storing global state, which makes it particularly suited to user interface design, components, funnels, games, etc.

It's also really easy to use; in fact I've specifically designed the configuration to be as easy as writing English:

transitions: [
    'next    : intro > form > finish',
    'back    : intro < form           < error',
    'error   :         form >           error',
    'restart : intro        < finish'
]

Demo and code is online here:

There are also 4 specific Vue demos, showing how it can be integrated easily with the framework:

In the meantime, here's a GIF of the main library demo that illustrates a lot of StateMachine's features:

state-machine-demo

Enjoy!

1st November, 2016

davestewart left a reply on Custom Exception Classes • 1 year ago

I settled for a more generic ParseRelationException with static methods to generate custom messages:


// No results for table `blah`. Did you spell, capitalize, and pluralize it correctly?
throw ParseRelationException::results($table);

// Lookup key `blah` failed matching a row in table `Features`
throw ParseRelationException::lookup($table, $lookupKey);

Feels like it gives provides enough contextual information to the user whilst still being flexible.

davestewart started a new conversation Custom Exception Classes • 1 year ago

I'm building a library which does quite a lot of database stuff (for the soon-to-be defunct/open-sourced Parse.com), reading, writing, updating relations etc, and I need to be fairly "on" the error handling.

Should I really be using custom Exception classes here, such as:

ParseRelationResolutionException
ParseRelationResultsException
ParseRelationResolutionException in ParseRelationResolver.php line 143:
Lookup key `blah` failed matching a row in table `Features`

?

I appreciate that's not much info to go on, but I'm trying to keep it brief :)

Edit Your Profile
Update

Want to change your profile photo? We pull from gravatar.com.