0 Best Reply Awards

  • Member Since 1 Year Ago
  • 411 Lessons Completed
  • 10 Favorites

13th March, 2018

miwal left a reply on Overriding A Method Implemented In A (used) Trait • 6 days ago

@ottoszika excellent answer, thank you.

miwal started a new conversation Overriding A Method Implemented In A (used) Trait • 6 days ago

The trait Illuminate\Foundation\Auth\RegistersUsers contains the following method (I copy it exactly):

     * The user has been registered.
     * @param  \Illuminate\Http\Request  $request
     * @param  mixed  $user
     * @return mixed
    protected function registered(Request $request, $user)

The trait is used in RegisterController, in Http/Controllers/Auth

As above the trait contains the above method with an empty method body. Obviously we don't want to change this trait in the framework code in vendor/.

In a video, what Jeff did was implement the method in RegisterController.

I just wanted to get something clear: a trait is a way of doing multiple inheritance, it's obviously not an interface.

In php, if a class uses a trait, and it implements a method that is also implemented in the (multiple inheritance...) trait, do we know for a fact that the method body in the class itself will take precedence over the same method in the trait?

Is that the behaviour being relied upon here?

Jeff doing the above is at 1:20 here: https://laracasts.com/series/lets-build-a-forum-with-laravel/episodes/73

miwal left a reply on Unsubscribe Token - Ok To Have One Permanently Valid Per User? • 6 days ago

@shez1983 Aha - yes: anyone could unsubscribe anyone else.

I was wondering why @martinbean used quotation marks around "simplest"!

The other criteria here is the benefit of a uniform approach across a codebase.

Since token (now realise this could usefully be called "secure token" here) is used for password reset, secure token for unsubscribe could be a way to go, if only for consistency and to prevent the minor quibble of anyone being able to unsubscribe anyone else; rather, use of that insecure pattern.

What I might do though is to have the token be null when a user isn't subscribed. When they subscribe (which may or may not happen during registration), I'll create the token, and when they unsubscribe, set it to null.

This way manual inspection of the database is will be a slightly neater experience.

The small benefit of not using a detail table, so long as the token is not too long, is visibility on the users table. Could even use the logic unsubscribe_token is not null to determine subscribed or not... though still need to be sold on the readability of that... hmm... Though if I wanted a timestamp subscribed_at that would scupper that of course.

So if I'm willing to forego the timestamp...

Thanks for sharing the thoughts here.

miwal started a new conversation Unsubscribe Token - Ok To Have One Permanently Valid Per User? • 6 days ago

I'm looking at implementing my own unsubscribe link for emails by creating and using an unsubscribe token. Obviously this will be a unique token identifying a particular user.

I note that the built in password_resets table is a detail table off of users, containing a created_at column, which allows the enforcement in code of a particular validity duration. The default for this as set in config/auth being 60 minutes.

To implement unsubscribe, I'm thinking of creating an unsubscribe_token directly on the users table, and creating this at the time of creation of the user record.

This would be one, permanent unsubscribe token per user that is permanently valid and never needs to be refreshed, identifying an unsubscribe request for a particular user.

Are there any conceivable drawbacks to using a token that is permanently valid for this purpose?

I want it as simple as possible but not simpler.

3rd March, 2018

miwal left a reply on The Route::is() Method - How To Find Out ? ... • 2 weeks ago

@skliche great tips there :) merci.

miwal left a reply on The Route::is() Method - How To Find Out ? ... • 2 weeks ago

@sklicke Yes, that works. Thanks. My question, though, was on how to go about finding the information in cases like this... i.e., should I really be using methods when I don't know their origin -- so, how to find where the method comes from.

miwal left a reply on The Route::is() Method - How To Find Out ? ... • 2 weeks ago

So now I have

        ['minicourses.show', 'topics.show', 'lessons.show', 'questions.show']))
    // includes here ...

which is a slight improvement. thanks.

miwal started a new conversation The Route::is() Method - How To Find Out ? ... • 2 weeks ago

I'm selectively including a bunch of modals in a blade layout file, and the pattern I'm following is to use @if(Route::is('routename.here')) in which I wrap @include('modal.here').

Now I find I need to apply this to four different routes, so I have:

@if(Route::is('minicourses.show') || Route::is('topics.show') ||
            Route::is('lessons.show') || Route::is('questions.show'))
  // include modals and a few scripts here

which is getting a bit unweildy.

I'm wondering whether there is a Route::in([]), so I could do something like: Route::in(['minicourses.show', topics.show', 'lessons.show', 'questions.show' ])

My actual question is, how would I go about finding out whether such a method exists, apart from just trying in the dark to see if something works?

I found this: https://laravel.com/api/5.5/Illuminate/Routing/Route.html

but that doesn't even list the Route::is method I'm already using, so I'm not clear on how to go about finding out this kind of information.

18th February, 2018

miwal left a reply on Best If Repositories Always Return ->toArray() ? • 1 month ago

it all depends on what exactly you are trying to achieve right now

Build a repository that provides both model instances and stdclass objects/arrays. See how it changes the rest of the code

My action now precisely :)

miwal left a reply on Best If Repositories Always Return ->toArray() ? • 1 month ago

Thanks @skliche. I tried sketching some client code and see what you mean.

A problem, though, if I do use any of those eloquent calls on a returned model, is it appears the principal benefit on which repositories are being sold, viz. swappability (e.g. to add a caching layer, which is what I had in mind to do with it at this point), will be lost (!?)

(since any call on a returned model will bypass the repository).

A problem... :) Is this a problem with all use of the repository pattern in laravel?

At this point I'd like to see some example repository contracts to compare my needs against, do some drafting and see how it could stack up in reality for my case.

Wonder if it would be useful at this point to try reading the laravel source. Not sure where to start with that though :) I tried a few times and didn't get much leverage on it. Wonder what some of the most accessible parts to start reading first could be? Cheers.

miwal started a new conversation Best If Repositories Always Return ->toArray() ? • 1 month ago

Am I right in saying that to implement a repository effectively, I must not return any active records (models).

Reason is, a (perverse) client could do this:

// $lessons is the name of the injected repository

$lesson = $lessons->get($slug);

$any_other_mad_query = $lesson::find('some other lesson');
// this last call circumvents the repository, so if the data layer had been derouted, say, to a mock, or some other implementation of the repository than the database which the model connects to, this would break.

The above code circumvents the repository and breaks separation of concerns. It's what you risk if your repository returns a functioning active record.

To prevent this, repositories should always call ->toArray().

toArray() will unnest even the eloquent collection of models (active records). Here's a summary of the options (I checked):

  • Lesson::first() gives a single model, not a collection.
  • Lesson::all() gives an eloquent collection (extends base collection) containing models.
  • Lesson::first()->toArray() gives a flat array.
  • Lesson::all()->toArray() gives an array of arrays
  •    (both collection and models inside it are unpacked to arrays)

Taylor calls ->toArray() when returning from a repository at the start of his book.

I just wanted to get my head around the concept before attempting to implement it, the options available, what to avoid and why.

Comments / clarifications / discussion greatly appreciated.

17th February, 2018

miwal left a reply on Is There Anything Wrong With Calling Two Gates In Succession, Using ->authorize()? • 1 month ago

I was using that one-liner previously, but at the moment I prefer the double if block instead. I know it's longer... but in this case I prefer it... at the moment!

miwal left a reply on Is There Anything Wrong With Calling Two Gates In Succession, Using ->authorize()? • 1 month ago

I've settled on this form for maximum avoidance of misreading and clarity:

        Gate::define('deploy-course', function($user) {

            if ($user->isCoordinator())
                if (config('tm.coordinators_can_deploy'))
                    return true;
            return false;

Then Gate::allows('deploy-course') in controllers and @can('deploy-course') in views both read crystal clear. Good job.

To summarize, name a gate after the domain action that is being authorized, not the checks necessary to do it.

An important benefit in my opinion comes from never(?) writing authorization logic in controllers as a result, which means you know the bit that matters that you have to test when doing a code audit.

So to answer the title of the original question. YES, there is something wrong with that, because you should use a single domain-action named gate to encapsulate all of your logic, and not build them up in a granular way, because if you do that you loose the chance to abstract and make your client code read at a higher level. i.e. you fail in your conceptual decoupling.

Tada! Comments welcome.

miwal left a reply on Is There Anything Wrong With Calling Two Gates In Succession, Using ->authorize()? • 1 month ago

@Nash I just went away from my computer then realised you are spot on with that.

If I think of the name as the action I'm trying to authorize, it is: deploy-course

Looked at this way, the Gate:: syntax is no longer such a dissonance:



@can('deploy-course') now works for my view, too, rather than being the unreadable guff @can('coordinators-can-deploy') ?!, which it would have been before this change.

I could stick the config variable check in that gate, and either just use a method on user ->isCoordinator() for the other piece of the authz logic, or, which now makes much more sense, put it in the new, declaratively named, gate, in which, it seems, there is now no reason to be afraid of not being an atomic command... oh, sunlight...

The key for me is not being afraid to name the gate declaratively, as the actual domain action you want to authorize, not the pieces of internal logic you're going to use to build that check. Makes sense?

miwal started a new conversation Is There Anything Wrong With Calling Two Gates In Succession, Using ->authorize()? • 1 month ago

I'm trying to simplify my authorization code.

I created two simple gates then another which was a combination of the previous two. (Compared to the below, it was is-coordinators-and-coordinators-can-deploy -- yuck).

My thought was to eliminate the compound one, and just call each of the atomic ones separately which then has the same effect.

In the controller actions that use them, it now looks like this:


I'm comfortable with putting the authorization logic in the gate, even though it is short, simply because it means less chance of error than were I to write out the needed boolean check off of a config variable every time a controller uses it.

My question is about laravel recommended usage.

I read in the docs that we are supposed to use Gate::allows() to call gates, rather than authorize.

$this->authorize is simply easier to read. There is a 'wtf' millisecond response when i see Gate::allows('is-coordinator'). It doesn't parse in my head well. Maybe my naming is the problem. I haven't solved that.

Is there anything wrong with writing two gates and calling them one after the other with ->authorize()?

14th February, 2018

miwal started a new conversation Case Sensitivity Difference (in Directory Names) Between Local (mac) And Production (ubuntu) Environments? • 1 month ago

Just had an interesting issue having just replaced a live codebase with a newly rebuilt version of my app on 5.5, upgrading from 5.3. (that upgrade's not the issue, though).

I have a directory in Console/ called MailgunCampaigns/ with a single skeleton command at present; where I'm going to add run-once commands which trigger mailgun campaigns probably via the package Bogardo/Mailgun, which gives full api access, including tags so results can be independently tracked & analysed on the mailgun dashboard.

The issue is much simpler, though.

When I do php artisan on my dev machine, I could see all my commands including those that exist just as skeletons at present.

Then I did heroku run bash and php artisan to take a look, on my new deployment.

A command was missing!

After short befuzzlement I noticed a typo. My directory in commands was 'MailgunCampaigns/'. In the console kernel to register autoload of all commands in that directory, I'd spelt it 'MailGunCampaigns' (with capital 'G').

Long story short --- my mac is not case sensitive of the difference and registers the command anyway. --- heroku is case sensitive, and with the identical codebase, the command is not registered.

I've checked this and fixing the case fixes the heroku (ubuntu 16) deployment too.

Wondered if this is a well known thing to experienced hands and if there's anything related that one can be usefully aware of or comments to be made about this.

miwal left a reply on How .version() Really Works In Laravel Mix ? • 1 month ago

Ah - I get it. The extreme simplicity of this was eluding me.

I view source of my front end, and, with .version() on, I see:

<link href="/css/front.css?id=4d2008fbca42a70de316" rel="stylesheet">

So in any old browser viewing that page, because that query string will have changed, that's going to cause it to not use what's in the cache (unless perhaps it already has that exact hashed version in its cache - not sure exactly how browser caches work..).

So this seems pretty cool. Not sure why previously (elixir, in 5.3) all that filename versioning was going on... But, thanks for the answer, and I'll just leave it to the experts and get on with my app at this point :)

miwal started a new conversation How .version() Really Works In Laravel Mix ? • 1 month ago

Just upgraded to 5.5 from 5.3.

Adding .version() in my webpack.mix.js makes mix-manifiest.json in public/ change from

    "/js/back.js": "/js/back.js",
    "/css/front.css": "/css/front.css",
    "/css/back.css": "/css/back.css"


    "/js/back.js": "/js/back.js?id=3d5fa110caada816e8d3",
    "/css/front.css": "/css/front.css?id=4d2008fbca42a70de316",
    "/css/back.css": "/css/back.css?id=7e816c2769c8d7d585dc"

but the file names themselves in public/ are not changed. (Just the query string is added to the call to load them, as above)

This seems to be some clever hashing type thingy which obviates the need to alter the actual filename. This is brilliant, as it reduces junk. But how does that work?

Do browsers now hashcode the file they have in cache and if it doesn't match, re-load it? front.css?id=4d2008fbca42a70de316

Does that mean if a browser didn't know to do this, it would use the stale version?

Just looking for some documentation on this feature. The 5.5. docs seem out of sync, not mentioning this behaviour I am now getting on 5.5

12th February, 2018

miwal left a reply on Empty Square Brackets After Every Log:: Line On Upgrade To 5.5 - Can They Be Removed? • 1 month ago

Hmm... I'll certainly try that @cronix. Thank you.

Also, I was just mucking around and discovered that if I add an empty array as 2nd parameter in the call to Log, then the empty brackets are no longer printed.

i.e. the empty brackets can be removed by changing:

Log::info('------------ ' . Auth::user()->name . ' ------------');


Log::info('------------ ' . Auth::user()->name . ' ------------', []);

which then prints as:

app/web.1:  production.INFO: ------------ Logged users name appears here ------------ 

without the empty [].

miwal left a reply on Empty Square Brackets After Every Log:: Line On Upgrade To 5.5 - Can They Be Removed? • 1 month ago

Interesting, thanks @Cronix. I've often wondered how to make logs more useful... That's a concrete idea I can try. I tend to heavily log things like payments, with tons of status lines like in the example above with lots of dashes to make them distinctive in the logstream, then other than that just print user names on access to certain key pages, so I have some dim idea of who is on the site on a particular day when just scanning through papertrail. Any other cool ideas for logging?

miwal started a new conversation Empty Square Brackets After Every Log:: Line On Upgrade To 5.5 - Can They Be Removed? • 1 month ago

Just upgraded my application from 5.3 to 5.5.

I write quite a few Log::info() status lines to my heroku logstream / papertrail.

Two pairs of empty square brackets now appear at the end of every log line, which are always empty, so have no purpose at all.

Is this now normal? What's the point? Can they be switched off?

I note this issue has existed for others, e.g.: here

It looks like this:

app/web.1:  production.INFO: ------------ Logged users name appears here ------------ [] [] 

(pointless empty brackets at end of line)

Why not on 5.3? Why now? Have I done something wrong?

9th February, 2018

miwal left a reply on Why ->exists Property Errors Out On Upgrade From 5.3 To 5.5 ? • 1 month ago

@talinon Thanks. It helps to know that the norm now is not to rely on presence of an 'empty' eloquent model returned off of a null parameter sent to be route model bound, and so the ability to call ->exists on it. That behaviour does seem strange, and I'm not entirely sure if I invented the ->exists call that used that myself by accident, or if it came from Jeff's community contributions, which was the inspiration for the code above:


In any case, the lesson I take away is it makes more sense not to return an eloquent model that is 'empty' off of a null default, but to return an actual null. L5.5 now does the latter, so case solved, perhaps. Thanks.

I'm not yet a skilled navigator of the laravel source, but if anyone can find this exact change in the source for interest and point it out, kudos for that, would be interesting to see it!

miwal left a reply on Why ->exists Property Errors Out On Upgrade From 5.3 To 5.5 ? • 1 month ago

The route is:

Route::get('photolibrary', '[email protected]')

That's the one I'm hitting. But these also exist:

Route::get('photolibrary/channel/{channel}', '[email protected]')


Route::get('photolibrary/user/{user}', '[email protected]')

The controller signature, which takes all three of these routes, is: public function photoLibrary(Photochannel $channel = null, User $user = null)

The call in the controller to the PhotosQuery is: 'photos' => (new PhotosQuery)->get($channel, $user),

The first part of PhotosQuery is:

    public function get($channel, $user) {
        if ($channel->exists) {
            return Photo::with('user', 'channel')
                    ->where('photochannel_id', $channel->id)
                    ->orderBy('created_at', 'desc')
        if ($user->exists) {

On laravel 5.3. The above code works. On 5.5, calling ->exists off of a non object errors out as you would expect. Hence I don't know why ->exists works on 5.3, since that should be a null object it's getting there. This is from community contributions laracasts and that's where i'll have to go if i have time to look into this further to find the answer. (But I've just replaced ->exists with isset() and it works on 5.5. Curious to find out why, though.

8th February, 2018

miwal left a reply on Why ->exists Property Errors Out On Upgrade From 5.3 To 5.5 ? • 1 month ago

if $channel->exists with channel set to null (it is set that way by a default value to an argument of the function the above code is inside of), is fine in 5.3, returning false. In 5.5, it gives the error.

miwal started a new conversation Why ->exists Property Errors Out On Upgrade From 5.3 To 5.5 ? • 1 month ago

I have a Query object, taken more or less directly from one of Jeff Way's tutorials, which contains:

if ($channel->exists))

Upgrading from 5.3 to 5.5, I get a 'trying to reference property of non-object' error.

I change it to this:


and the error goes away.

This question is really just because I love squashing bugs! I couldn't find mention of this in the upgrade guides.

Can anyone help pinpoint why ->exists errors out as described above in 5.5?

miwal started a new conversation What's The Intention Behind App\Policies\ModelPolicy? (which Doesn't Exist By Default) • 1 month ago

In AuthServiceProvider, one policy is present by default: App\Policies\ModelPolicy.

That file does not exist in a plain install.

Is this meant to imply that this class should be created? What would the value of having an (abstract?) ModelPolicy be?

The docs seem strangely silent on this unless I've missed something.

Or maybe it's just meant to be an example that is never intended to mean anything.. which seems a bit strange since it's not explained... ?

6th February, 2018

miwal left a reply on In Refactoring To A Repository, Is Route Model Binding Then Best Avoided? • 1 month ago

Clarification: what I meant by "passing the entire Model class up from the repository" above could be better rephrased as:

where a repository had return App\MyModelClass; as one of its methods.

i.e., an 'empty' model that hasn't got any records in it; so can serve as a query builder when the controller receives it.

i think i need to get clearer exactly what a Model class is, before and after it's used as a query builder... seem to be a bit confused here.

miwal left a reply on In Refactoring To A Repository, Is Route Model Binding Then Best Avoided? • 1 month ago

I meant the case where the repository would pass the model back to the controller. I think the intuition behind that is so that you get all the options you previously had, instead of having to write a new method on the interface for every query needed. But I came round to the idea being explicit like that could be worth it. (It means adding to the interface when you need a new query).

So, it seems to me that passing up the model from the repository means you don't benefit from the repository pattern. (So I don't understand when you mention above about the repository returning the model... - why is there any value in that compared to, just using it directly in the controller, if its needed there?

I think I'm planning to pass just $id or $slug to my repositories. But if I have create and update methods, I'll need to pass more - I guess I could pass the whole request down there as you mention.

In that case there's the question of where to do validation - should we keep validation in the controller?

miwal left a reply on In Refactoring To A Repository, Is Route Model Binding Then Best Avoided? • 1 month ago

@bobbybouwmann I have a follow up question.

Would I be right in saying that it is probably a bad idea to pass up an entire Model class from a repository?

I saw one example on the web doing that, but, while I have no wish to become an architecture astronaut, it seems to me that passing up a Model from a repository means failing to enforce separation of concerns; that being one major reason for using repositories in the first place.

Model in laravel means a direct access to the (database) data layer, via the methods it provides, like ::all() and ::find(). With repositories, it could be a good idea to only(?) use Models inside of the repository itself, so they won't (ever?) be used in our Controllers any more. ?

5th February, 2018

miwal started a new conversation In Refactoring To A Repository, Is Route Model Binding Then Best Avoided? • 1 month ago

I'm asking this question as a way to check my (conceptual) understanding.


  1. the first several pages of Otwell's book
  2. https://stackoverflow.com/questions/17367159/laravel-repositories
  3. http://martinbean.co.uk/blog/2017/11/27/binding-configured-services-to-laravels-container/ (not strictly about repositories, but very interesting none the less)

My question:

Repository means you get your data, via DB or even eloquent model classes, all inside of a separated implementation of some interface you define.

Then, your Controllers are going to get an instance of that, and get all of their data off of the methods in the interface.

Hence, what if I'm looking at refactoring to this pattern and I currently use route model binding in a few places?

Answer: its best avoided.

Is this correct? Any comments? Thank you.

miwal left a reply on Should I Change 'name' In Composer.json, From 'laravel/laravel' To The Name Of My Own Project...? • 1 month ago

Thanks @martinbean.

Good tip about license. It's nice to be neat!

miwal started a new conversation Should I Change 'name' In Composer.json, From 'laravel/laravel' To The Name Of My Own Project...? • 1 month ago

A tiny detail, perhaps, but I'm trying to improve my grasp of composer and packages.

Since a new laravel application is a copy of laravel/laravel, forming the application skeleton, that skeleton is called laravel/laravel.

But, since this is now the code I am going to modify, should I rename this, effectively making it into a new composer package? (and benefitting from the license which allows this to be done).

In this case, my newly named composer package dependencies include laravel/framework, etc.

I also note for clarity that laravel/laravel is not a dependency and never has been, it's just a repo, i.e. the application skeleton which we clone in starting a new app.

24th January, 2018

miwal left a reply on What Exactly Does The Laravel Version Number Refer To? • 1 month ago

Thanks. To clarify, then:

The laravel framework is:


of which I see there have so far been 304 releases:


But the repo you actually install to create an app (usually via laravel new) is not that, but this:


That has so far had only 80 releases (in contrast to 304 for the framework):


Hence, in reality, there are are two version numbers.

There is a version number for the framework, and a version number for "laravel/laravel" (which is what they have called the application skeleton that you install to create a new project).

composer update will update the version of the first, the framework.

There does not seem to be any facilitated way to update the application skeleton. This is not that surprising, as you are going to have modified that code. In the upgrade guide, though, it does mention a few cases where you might be sensible to bring in some of the changes made there recently, manually, when you upgrade.

Hopefully that summarises it accurately. Please point out any mistakes here and I'll update my answer.

miwal started a new conversation What Exactly Does The Laravel Version Number Refer To? • 1 month ago

I know that laravel new or composer create-project, or for that matter git clone https://github.com/laravel/laravel all generally do the same thing.

What these do is clone a skeleton of the application code that you will start with, and add to, when you write your application.

However, laravel is a "framework" and there are also a lot of other composer packages involved. These are part of your application only by virtue of their being listed in the composer.json file which is in your app directory.

Thus, what exactly does a "laravel version number" refer to?

It would seem this could mean the skeleton application code which you start with in your repo; and/or its dependencies which lie in /vendor and are specified by composer.json.

So, which? Thank you.

22nd November, 2017

miwal left a reply on Laravel Session Data - Encrypted? (any Value To Attacker If They Had It?) • 3 months ago

Yeah, I get that. That wasn't my question.

miwal started a new conversation Laravel Session Data - Encrypted? (any Value To Attacker If They Had It?) • 3 months ago

I just connected to my redis on heroku which is my session driver on a live app. It said 'the connection is not secure'. This is is the only option for non-paid redis plans.

I connected in any case, so, in theory, someone could have got all of the session keys. They look like they are encrypted. Are they? If someone had that data, would they be able to do anything with it?

I found a reference to option to encrypt session data but that was back in the 5.0 docs. If it is now encrypted, does that mean it is useless to an attacker? Would be nice to know.

(BTW the safe way to interact with redis if you're not on a paid plan on heroku seems to be doing it via artisan tinker and the Redis:: facade, which has a magic method to pass through all native redis commands, which is nice - will be using that from here on instead)

20th November, 2017

miwal started a new conversation URL Includes Unwanted /index.php/ ? • 3 months ago


I have a newly deployed laravel site (with apache on heroku).

I notice in the logs that some users access it via: /index.php/

Whereas for most it is: / (i.e., what I would call normal, & expect)

Why could this be? I think I'd like to switch it off if possible.

Google bot accessed it using the /index.php/ insertion, too.... (I think both with and without)

Thanks for any help. Curious... I'm just using default laravel settings as far as I know (5.3).

31st August, 2017

miwal left a reply on Validation With Route-model Binding • 6 months ago

Hi Daniel, Looking back at it now, I'm not absolutely sure I formulated the problem correctly - I believe I forgot about the issue for better or worse. If it was a PDO exception then getting one of those is a good thing really. If it wasn't that, I'm not sure. In any case this that was laravel 5.3 I was using there and the framework might have evolved a little now (or maybe not in this area - don't know).

6th June, 2017

miwal left a reply on Choosing Between Laravel And Vue To Achieve Same End? • 9 months ago

Thanks Stefan. You offer some valuable food for thought there. One point I realise from reading your reply is that removing 'everything front end related' from a laravel project would require that while web routes are removed, an api remains (obviously).

In a standard laravel project web routes are fed probably by models, but one would need to basically build out an api abstracted from them to be able to 'remove everything front end related' (i.e. so as not to end up with no functioning service at all!).

Taking a standard laravel app and building out an api to mirror the data needs of the app in preparation for replacing the front end is a refactor I haven't actually had any practice with I now realise, but you help me to see the direction that could take.

Not sure Jeffrey has done that particular refactor anywhere on Laracasts unless I'm mistaken, and I guess he may be understandably hesitant to chop laravel down to such a degree which would be fair enough given his main focus.

Cheers & thanks for the advice.

miwal started a new conversation Choosing Between Laravel And Vue To Achieve Same End? • 9 months ago


Having flirted with vue, which is obviously useful, and even got to the point of building a few simple SPAs with vue router and vuex, via some excellent courses on Udemy, I've realised that most of my app could, in fact, be built with hardly any javascript at all, which is how I kind of set out to do it in the first place in any case, following all that I've learnt here on laracasts.

In fact, I think I've decided to build it so it at least works in a basic form with javascript turned off. I could argue that I've wasted a lot of time starting with php then exploring how to do similar things with javascript.

What kind of personal guidelines do people use to help them to reduce the bamboozlement over multiple ways to achieve the same thing?

Obviously some things can only be achieved in javascript; but with that aside javascript can also take over large parts of what laravel does for us - so how do you choose when to stop?

I think I'm just going to be very old fashioned - if I can do it in php, then I will. That has the simple merit of being a discipline that I seem to be able to get a handle on. Then javascript is added but only under the assumption the site will still work without it, albeit be a bit less pretty (realise some have called this 'progressive enhancement').

How do others deal with the profusion of choices available when using laravel with vue - so many ways to achieve the same thing. Is it best simply to take one of two extremes - use php anywhere you can with sprinkling of js on top; or, simply to do the reverse, and go to the full SPA?

Is a 'middle road', rather than one of the two extremes above, just going to create a bit of a mess? Any thoughts?

Cheers Mike

11th April, 2017

miwal left a reply on In Adopting Vue, Does This Mean We May Not Have A Need For Stylus Any More? • 11 months ago

I've come back to this to add a more exact answer with the benefit of time.

  • If you use .vue components, you can use <styles lang="stylus> inside of the .vue file. That means that styles you would have put in resources/assets/stylus are going to be likely to reside in resources/assets/js/components/ComponentName.vue, within the tag, instead.

You'll tend to group css with components when you move towards vue.

7th April, 2017

miwal left a reply on Hiding Irrelevant Build Files • 11 months ago

Hi @Screenbeetle

if (elixir.config.production) {
    mix.version(['css/app.css', 'js/app.js'], 'public/build')  
        // 'public/build' above is also the default output dir in any case
if (! elixir.config.production) {
    mix.version(['css/app.css', 'js/app.js'], 'public/build-dev') 
       // add 'public/build-dev' to your .gitignore

You must then include this in your blade layout file:

@if(config('app.env') === 'local')
    <link href="{{ elixir('css/app.css', 'build-dev') }}" rel="stylesheet">
    <link href="{{ elixir('css/app.css') }}" rel="stylesheet">

plus the equivalent for your app.js

Finally, in your project directory, in .git/hooks/pre-commit

#!/usr/bin/env sh
echo 'Running pre-commit hook'
gulp --production
git add ./public/build/css ./public/build/js ./public/build/rev-manifest.json

This works fine for me with git CLI – stops all the garbage appearing in Github desktop while I'm working, plus does the production build automatically before every commit.

Unfortunately I haven't yet got Github Desktop to fully run this hook, it does run the hook itself, but not gulp, for some reason, so I have to manually run gulp --production before committing if I want to commit with Github Desktop, which is not a huge problem except that might forget to do it. http://stackoverflow.com/questions/43279311/git-hook-not-completing-on-github-desktop-for-mac

6th April, 2017

miwal left a reply on Hiding Irrelevant Build Files • 11 months ago

Hi @Screenbeetle

I'm on 5.3. Yes that works - I can add a second argument to .version() and it puts the hashed filenames plus the rev-manifest which elixir uses in that target directory.

This gives us step 1 to solve this. Great.

If my goal is sound, as step 2 we'll then need to branch based on whether it's a dev or production build, like this:

  • If build = dev, .version() to a dir that we .gitignore

  • If build = production, .version() to a dir that we don't.

There seems to be an elixir.config.production variable somewhere, which I haven't quite got my head around:


I tried to hack this but couldn't get it to work - my grasp of the js syntax of the gulp file is poor...

miwal left a reply on Hiding Irrelevant Build Files • 11 months ago

@Screenbeetle Isn't public/build needed by elixir() to resolve the versioned file when you include it in your views? So that's going to be needed in production and so I need it in the repo (I'm deploying via git).

What I'd like to do is .gitignore all dev (un-minified) builds only, so those build artifacts are not always in my face, then silently do the production build via a pre-commit hook (i think... but in all honesty I'm a bit confused...).

miwal left a reply on Hiding Irrelevant Build Files • 11 months ago

Elixir .version() is outputting to the same place, public/build, and does not make the file names recognisably different, whether I run gulp watch or gulp --production, so it seems I cannot target dev vs production builds independently with this tool.

miwal started a new conversation Hiding Irrelevant Build Files • 11 months ago

I like to use github desktop to review code changes I've made and its very annoying having all of those js and css build files clutter that up as they are autogenerated and of no relevance to me.

How can I put them out of sight?

While also having minification done ideally as a pre-commit hook?

I can't gitignore all of public/build/css because that's where both the non-minified and minified files live, so a blanket ignore doesn't seem possible - I'm also using elixir's cache-busting.


  • gitignore loads of stuff to keep it out of my treasured and useful github desktop view.

  • make a git pre-commit hook to run a production build script then add back the files I need (which have previously been gitignored).

  • It seems if I do this I then have to add a post-commit hook to then ignore again the files I've added back in the step above.

What a mess.

18th March, 2017

miwal started a new conversation Validation With Route-model Binding • 1 year ago

I'm using route model binding, binding two separate models which default to null if absent (modelled on Jeff's Photochannels in one of the laracasts, with these params passed to a PhotosQuery class), and I'm now, as a security audit, trying to break a few of my routes.

If I enter a trailing ' after the user_id in the route, I get a Query Exception: SQLSTATE[22P02]: Invalid text representation.

Given this, my response is to try to add some validation.

But this error is triggered by the route model binding itself, and any validation in the controller is done too late so has no effect.

So, what to do? The docs state that if a model isn't found, a 404 will be generated: https://laravel.com/docs/5.3/routing#route-model-binding

But this isn't happening - I'm getting the error above.

Is there simply an expectation that a form request is used when you want to validate before a route model bind?

I only need one or two rules, so I wouldn't otherwise do that.

26th February, 2017

miwal left a reply on Deeper Understanding Of Events? • 1 year ago

See Eventing behind the scenes from 'intermediate laravel':


miwal left a reply on Permissions System Schema Design Alternatives • 1 year ago

To answer my own question: roles with permissions and users with permissions can be achieved without polymorphism.

You can use three (non-pivot) tables: users, roles, and permissions, joined by two pivot tables: roles_users, and permissions_roles.

This gives you, of course, the first part of what we want: roles defined in terms of permissions.

To get permissions directly on one user (the second part of what we want), you can define a role with the same name as the user, the intention being it is a role unique to the user, and applying that only to your one user gives you permissions per user, without needing polymorphism.

I got the idea from here: http://laravelsd.com/share/2nM4tV

Edit Your Profile

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