Owner at https://sleeplessmind.com.mo



1 Best Reply Awards

  • Member Since 2 Years Ago
  • 396 Lessons Completed
  • 9 Favorites

22nd February, 2018

godbout left a reply on PHP Refactoring: Function Aliases? Need Opinions. • 3 weeks ago

Thanks! Although my functions are not methods, they're purely global functions available just for my tests.

21st February, 2018

godbout started a new conversation PHP Refactoring: Function Aliases? Need Opinions. • 3 weeks ago

Wondering if there's a way to avoid the duplication of a couple of helper functions I did for my tests:

function birth($action, $arguments)

function raw()
    return birth(__FUNCTION__, func_get_args());

function make()
    return birth(__FUNCTION__, func_get_args());

function create()
    return birth(__FUNCTION__, func_get_args());

birth is where everything happens obviously. I'm pretty sure I don't know PHP enough and there's a better way rather than copypasting each function. It doesn't really matter per se, but I'm curious. Any thoughts?

26th January, 2018

godbout left a reply on What Am I Missing. • 1 month ago

@madsynn you should bind the model in your Route Service Provider, not in the the route files. Have a look there: https://laravel.com/docs/5.5/routing#explicit-binding

Make sure you import your user class correctly in the Route Service Provider.

Then in your route files (web.php), you call your route with the {user} tag, for example:

Route::get('myroute/users/{user}', '[email protected]');

Then, MAGIC!!!

25th January, 2018

godbout left a reply on Custom Methods On Eloquent Relationships? • 1 month ago

Thanks for your time!

godbout left a reply on Custom Methods On Eloquent Relationships? • 1 month ago

Well, maybe. Let's see how this evolves. I'm just building something for my own company, and I like to build just for what I need. I extend later. But that might be a good idea, thanks.

24th January, 2018

godbout left a reply on Custom Methods On Eloquent Relationships? • 1 month ago

@Borisu let me tell you something: you might have a good point ?️ I made the InvoiceStatus model because I've got a corresponding table. I wanna keep track of all the status history per invoice. But maybe you're right, the model might not be needed? Not sure yet.

Thanks for the answer. Yeah that's what I did at the end. I was just wondering if there was some Laravel magic that I was missing. Thanks.

godbout started a new conversation Custom Methods On Eloquent Relationships? • 1 month ago

I'm trying to refactor my code.

I have 2 classes, one called Invoice, and another InvoiceStatus. Relationship is one to many.

What happens is when an invoice is sent, I add a new status for that invoice.

Currently the controller is:

    public function send(SendInvoiceRequest $request, Invoice $invoice)


The Invoice class:

    public function sent()
        'code' => 'SENT',
        'set_on' => Carbon::now()

I'm annoyed with setting the code in the Invoice class though, I think it is more appropriate in the InvoiceStatus class.

So I'm trying to do something like this:

    public function sent()

and handle the creation in the InvoiceStatus class instead (if possible, with invoice_id automatically filled).

How is that possible?

godbout left a reply on What Am I Missing. • 1 month ago

Well, $id doesn't exist in your method.

public function edit(User $user)
        $user = $this->userRepository->findWithoutFail($id);
        if (empty($user)) {
            Flash::error('User not found');
            return redirect(route('users.index'));
        return view('users.edit')->with('user', $user);

But you're passing the User, so Laravel should provide it for you. Not sure why there's a call to userRepository here.

If you bind your route with your model, then Laravel takes care of all the check for you, so if the method is entered, that means that you're already having a valid user.

Therefore, your method can become way simpler:

public function edit(User $user)
        return view('users.edit')->with('user', $user);

19th January, 2018

godbout left a reply on Testing Mail Content • 2 months ago

I've found a better way, although it is still not testing the email content. It it testing the variables passed to the view, which still helps me have a good test when nothing is passed. I can check that the variables contain the default data. It is slow, but it works. If anyone knows how to check from the email content directly, please let me know!

Here are my changes:

Mail::assertQueued(\App\Mail\Invoice::class, function ($mail) use ($attributes) {
            $filled = $mail->build();

            return $filled->subject === $attributes['subject'] &&
                $filled->viewData['greeting'] === $attributes['greeting'] &&
                $filled->viewData['message'] === $attributes['message'] &&
                $filled->viewData['farewell'] === $attributes['farewell'];

18th January, 2018

godbout started a new conversation Testing Mail Content • 2 months ago


I've got a mailable class with default attributes. If I pass attributes through the constructor, then the new attributes are used in the email generated.

I am currently able to test that those attributes passed are used using some tricks, but I think it'd be easier (and more useful for other cases) for me to compare those attributes differently against the email content, but I can't find a way to get it. Am I missing something?

Here's my code:



        $invoice = factory(Invoice::class)->create();

        $attributes = [
            'greeting' => 'Hi!',
            'subject' => 'Nice Subject',
            'message' => 'You owe us some dolars!',
            'farewell' => 'Be well soon!'

        $this->post("/invoices/{$invoice->id}/send", $attributes);

        Mail::assertQueued(\App\Mail\Invoice::class, function ($mail) use ($attributes) {
            return $mail->getAttributes() == $attributes;

So basically I want to replace the test of the closure of assertQueued with something that checks my attributes against the email content.


7th January, 2018

godbout left a reply on Npm, Same Package.json, But Different Dependencies Pulled • 2 months ago

Yep, done on both projects, still the same. So yeah I guessed it was a dependency issue, but it doesn't make sense to me. How come the same package, same version requires 2 different versions in 2 different projects?

6th January, 2018

godbout started a new conversation Npm, Same Package.json, But Different Dependencies Pulled • 2 months ago

I have 2 Laravel projects with the exact same package.json. GitHub reported a security issue with one package, so I ran an npm update on both projects. One get the latest version of that package, but the other doesn't.

I've tried cleaning npm cache, removing the package-lock.json, it didn't change anything. The package that is pulling the one with the security flaw has the same version.

Any idea what's happening here? I have a basic understanding of npm, not deep. Maybe it's something basic that I don't get.

Here's the package.json


    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --watch --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    "devDependencies": {
        "axios": "^0.16.2",
        "bootstrap-sass": "^3.3.7",
        "browser-sync": "^2.23.2",
        "browser-sync-webpack-plugin": "^1.2.0",
        "cross-env": "^5.1.3",
        "jquery": "^3.1.1",
        "laravel-mix": "^1.7.2",
        "lodash": "^4.17.4",
        "vue": "^2.5.13"

29th December, 2017

godbout started a new conversation Mailable, Rendering An AJAX • 2 months ago

Before sending an email, I open a modal where I can update the subject, text, etc... of the email. I'd like to load the preview of the email through AJAX, still while using the Mailable class. Mainly, like the preview in the browser, but in AJAX (without the head tags and all). I played with the markdown/html templates, remove the layouts etc, but that seems an overcomplicated path. The idea is to have only one place where the design of the email is done, but it's possible to view it in the browser, and to get it through AJAX. Laravel doesn't seem to allow that out of the box, right? Does my idea even make sense, I'm wondering?


26th December, 2017

godbout left a reply on Looking For Consolidating My Understanding On Database Locking And Same Field Editing • 2 months ago

Hey! Thanks for the quick and detailed answer.

Good tip for the raw queries, didn't think about that. Yeah I had a look before at the laravel docs about the pessimistic locking but didn't really get it. Going into the mysql docs, it seems that what I would need more is the sharedLock (the definitions are confusing, but updating only one row, it seems it's the way to go). I guess I can start a transaction, lock, get the model from the db, make my changes on the field, update in db, unlock.

I've tested heavily and it seems to work currently with the refresh just before modifying, and updating the field. But mainly, again the question is, I'm not crazy right? Between the refresh, the modification and the update, it COULD happen than a field is getting updated? Or is there something I'm missing, design-wise or through some magic that Laravel is taking care of?

godbout started a new conversation Looking For Consolidating My Understanding On Database Locking And Same Field Editing • 2 months ago

I've ran into a problem that I've solved but I'm still wondering if there's a chance that something weird happens.

Gonna try to be succinct: I made an API to share writings on social media. When a writing has been shared on a medium, I update a db field which stores which medium and when it has been shared in a json format. So basically I read and decode the json, add the current medium, encode and save.

The thing is, when I call APIs asynchronously, they seem to override each other. Each API doesn't catch up with the other ones, and when they decode/encode the json, media are missing in the field.

What I did to solve this issue is, right before reading the field, I refresh my eloquent model ($this->refresh();), make my changes, then save. It seems to work well.

Now I'm still wondering, is there a chance than between the refresh and the saving, some other API actually writes something in the field? I would have to be very unlucky, but in theory, it seems to be that it's possible. In that case, I would lose some data.

So I'm wondering, any way to solve this on the php/eloquent/laravel side? Use DB transaction and pessimistic locking? I'm asking coz I'm not sure I understand those two things correctly.

I know I could queue the API calls and process them synchronously, but that's not the question here. I'm trying to understand and improve my knowledge of this issue with locking, transactions, and having different async calls updating the same row/fields without losing data.

Thanks in advance!

3rd September, 2017

godbout left a reply on How To Get Html In Response Session Flash Or Redirect With Messages? • 6 months ago

The way I did:

In my controllers, sometimes I pass data, sometimes not:

$request->session()->flash('message_partial', 'messages.added');
$request->session()->flash('message_data', ['spelling' => $request->spelling]);

$request->session()->flash('message_partial', 'messages.added_demo');

In my main app layout, I make sure I cast the data to array, in case it's null:

            @if (session('message_partial'))
                @include(session('message_partial'), (array) session('message_data'))

I have a layout for the messages:

<div class="alert alert-flash fade in alert-@yield('type')" role="alert">

And I extend the layout in all of my messages partials:


@section('type', 'info')

    Words cannot be mastered in demo mode. Please <a href="{{ url('register') }}" class="alert-link">register</a> to start recording your own words!

Works quite well, at least if you just have a few messages, that are quite similar. Might need to find another solutions if number of flash messages grow or are too different.

godbout left a reply on How To Get Html In Response Session Flash Or Redirect With Messages? • 6 months ago

I'm quite new to Laravel, but I've been using kind of the same methods described here. Very useful, thanks!

I've also used a layout for the main parts of the message that I extend in all my messages partials.

14th August, 2017

godbout left a reply on PHP Fatal Error: Class 'TestCase' Not Found • 7 months ago

For me it was a little harder.

Had to get the new content of TestCase.php on github, then add manually CreatesApplication.php in the same folder, then update composer.json with the new settings for autoload-dev.

18th April, 2015

godbout started a new conversation JWT And Laravel Built In Auth • 2 years ago

I'm fairly new to Laravel and I'm planning to build a set of APIs with it (frontend done with angular). I've setup a JWT auth and I can generate and retrieve tokens, but I'm a bit confused with the built in auth of Laravel. I think I got that I'm going to drop the built in auth middleware and replace it with the JWT one, but what about the auth and password controllers? It seems to me that I can still use some functionalities like the password resets, the guest redirection, etc... Does it make sense, or do I have to drop everything? I think I'm getting confused about whether the middlewares and controllers are kinda linked or not.

godbout left a reply on Practical Uses For Lumen? • 2 years ago

@gregrobson Agreed. Still, I find weird that you can't use something like "Route::resources" and "artisan make:controller" when basically that's what you want for APIs. It's not gonna put much overhead on Lumen.

godbout left a reply on Practical Uses For Lumen? • 2 years ago

I'm not getting it. I believe I see the use, but it's for example more straightforward to create RESTful APIs in Laravel than in Lumen. Creating controllers too. Anything I'm missing?

11th April, 2015

godbout left a reply on Laravel 5 Validation Request, How To Handle Validation On Update? • 2 years ago

@zeeshan if you're using Route Model Binding you can drop the segments and use something like below instead:

$rules = [
            'code' => 'required|min:3|unique:programs,code,' . $this->route('programs')['id'],

then you can change your routes to whatever, add prefix and all, the correct data will always be retrieved.

Edit Your Profile

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