godbout

godbout

Member Since 4 Years Ago

Macau

Owner at https://sleeplessmind.com.mo

Experience Points 58,455
Experience Level 12

1,545 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 570
Lessons
Completed
Best Reply Awards 1
Best Reply
Awards
  • 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.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer-token Created with Sketch.

    Lifer

    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.

11 Aug
1 month ago

godbout left a reply on Npm Run Prod, Commits, And Forge

@bobbybouwmann thanks! There's a mention in the doc that yes, npm ci doesn't rewrite any package files. Seems the way to go.

Here's the doc for those interested: https://docs.npmjs.com/cli/ci.html

godbout left a reply on Npm Run Prod, Commits, And Forge

@nash good catch. v12 on my local dev, v10 on production. Still, I don't get the idea behind it. Just for install, I wouldn't expect neither package.json nor package-lock.json to change! Thanks.

04 Aug
1 month ago

godbout left a reply on Npm Run Prod, Commits, And Forge

@nash

Here's a part of the diff between the package-json.lock i commit and the one that gets generated by npm run prod:

                 "ansi-regex": {
                     "version": "2.1.1",
                     "bundled": true,
-                    "dev": true,
-                    "optional": true
+                    "dev": true
                 },
                 "aproba": {
                     "version": "1.2.0",
@@ -4111,14 +4110,12 @@
                 "balanced-match": {
                     "version": "1.0.0",
                     "bundled": true,
-                    "dev": true,
-                    "optional": true
+                    "dev": true
                 },

the error message i get is just a basic git merge conflict. the npm run prod works well.

my deploy script:

cd /home/forge/hq.sleeplessmind.info
git pull origin master

composer install --no-dev --no-interaction --optimize-autoloader

echo "" | sudo -S service php7.3-fpm reload

npm install
npm run production

what i'm thinking doing is once npm ran, i'll delete both package.json and package-json.lock so that at the next deploy, git can pull. it's dumb, but it should work.

godbout left a reply on Npm Run Prod, Commits, And Forge

@snapey, I omitted it in my description but npm install is run before npm run prod. the issue is that npm run prod updates package.json and package-lock.json, which then conflicts git tries to pull the update from the repo. see next comment on how those package files change.

03 Aug
1 month ago

godbout started a new conversation Npm Run Prod, Commits, And Forge

i don't get how the workflow is supposed to be. i develop on my local machine with npm run watch. my package.json and package-lock.json are committed. then i push to github, that sends the hook to forge. forge tries to install the repo but every time it can't because npm run prod generates a different package.json and package-lock.json and it can't merge. that means that every time before pushing my commits, i need to remember to run npm run prod to be sure i'll get the same files than on production. this is dumb. anyway to improve this? i thought that would work like composer, once you get your composer.json and composer.lock, they are not rewritten when installing on the server. but npm rewrites everything, breaking the repository pull.

27 Jan
7 months ago

godbout left a reply on Testing Listener With Queue::fake() ???

Had the same issue. The thing is the job pushed is not the listener. As you discovered, the job is an instance of "Illuminate\Events\CallQueuedListener". So we can do something like this:

Queue::assertPushed(CallQueuedListener::class, function ($job) {
    return $job->class == ListenerName::class;
});
11 Jan
8 months ago

godbout left a reply on Npm Run Dev Issue

Remove the content of node_modules first, then run npm install again, then run the dev command and enjoy.

30 Dec
8 months ago

godbout left a reply on How To Test Job Chaining In Laravel 5.5?

In my case, even if I trust that the chained job feature is working, I wanted to check whether I had forgotten to add a job in the chain or not. I didn't understand the code from AdrianB at first but after tinkering for a solution I ended up with the same. Thanks @adrianb!

godbout left a reply on Event/Listener Working Fine In Browser But Not Working In Test

Event::fake() will prevent ALL listeners from being executed, but you can pass it an argument and precise which events you wanna fake:

You can check the "Faking A Subset of Events" here: https://laravel.com/docs/master/mocking#event-fake

27 Dec
8 months ago

godbout left a reply on Call To A Member Function Count() On Null

You could use the optional helper (https://laravel.com/docs/5.7/helpers#method-optional), but the rest of the code seems a bit off. You might want to better your request validations first.

06 Apr
1 year ago

godbout left a reply on Using The Same Form Request For Two Different Models

This is how I handle everything in the same class currently, and it's kinda suck:

$clientId = 0;

if (isset($this->quotation)) {
    $clientId = $this->quotation->client->id;
} elseif (isset($this->invoice)) {
    $clientId = $this->invoice->client->id;
}

return [
    'contact_id' => [
        'required',
        Rule::exists('contacts', 'id')->where(function ($query) use ($clientId) {
            $query->where('id', request('contact_id'))
                ->where('client_id', $clientId);
        })
    ]
];

godbout left a reply on Using The Same Form Request For Two Different Models

Hi. Thanks. Yeah, so that sounds like my test of which class is being actually sent to the form request.

'required_if'? How would you make that work? The contact_id is always required, because that's whom the email is gonna be sent to. The problem is not going to be there, the problem is going to be whether $this->quotation->client or $this->invoice->client exists, which is why I wanted to extract this to a $this->document->client. The Document abstract class has the relationship to Client setup, but I don't know how to get a document instance rather than a child model in the form request.

godbout started a new conversation Using The Same Form Request For Two Different Models

I'm having two models, Invoice and Quotation. I have a validation form to check that an Invoice or a Quotation can be sent to a client. The validation form is the same for both. Currently, I had to duplicate the form request, the rules being slightly different because of the models:

For Invoice:


return [
            'contact_id' => [
                'required',
                Rule::exists('contacts', 'id')->where(function ($query) {
                    $query->where('id', request('contact_id'))
                        ->where('client_id', $this->invoice->client->id);
                })
            ]
        ];

For Quotation:


return [
            'contact_id' => [
                'required',
                Rule::exists('contacts', 'id')->where(function ($query) {
                    $query->where('id', request('contact_id'))
                        ->where('client_id', $this->quotation->client->id);
                })
            ]
        ];

So the only thing that changes is the model. I'm trying to use the same form request for both models in a clean way, but I'm not sure how to handle it. I'm trying to get a

$this->document->client->id
work but I can't get the Route binding to work, which makes sense I think, because my Invoice and Quotation models extend a Document model that is abstract.

So, anyways, I'm trying to learn how to design and work with Laravel correctly. I know I could just test whether

$this->quotation
or
$this->invoice
are set or not, but I'm looking for a cleaner solution, and a little bit of design pattern training :)

Thanks!

22 Feb
1 year ago

godbout left a reply on PHP Refactoring: Function Aliases? Need Opinions.

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

21 Feb
1 year ago

godbout started a new conversation PHP Refactoring: Function Aliases? Need Opinions.

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?

26 Jan
1 year ago

godbout left a reply on What Am I Missing.

@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!!!

25 Jan
1 year ago

godbout left a reply on Custom Methods On Eloquent Relationships?

Thanks for your time!

godbout left a reply on Custom Methods On Eloquent Relationships?

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.

24 Jan
1 year ago

godbout left a reply on Custom Methods On Eloquent Relationships?

@Borisu let me tell you something: you might have a good point :D 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?

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)
    {
    ...

        $invoice->sent();
       
    ...
    }

The Invoice class:

    public function sent()
    {
        $this->statuses()->create([
        '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()
    {
        $this->statuses()->sent();
    }

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

Anyway to do that? Or is there a better way to make this cleaner?

godbout left a reply on What Am I Missing.

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);
    }

19 Jan
1 year ago

godbout left a reply on Testing Mail Content

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'];
        });
18 Jan
1 year ago

godbout started a new conversation Testing Mail Content

Hello!

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:

        $this->be(factory(User::class)->create());

        Mail::fake();

        $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.

Thanks!

07 Jan
1 year ago

godbout left a reply on Npm, Same Package.json, But Different Dependencies Pulled

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?

06 Jan
1 year ago

godbout started a new conversation Npm, Same Package.json, But Different Dependencies Pulled

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

Thanks!

{
    "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"
    }
}
29 Dec
1 year ago

godbout started a new conversation Mailable, Rendering And AJAX

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?

Thanks.

26 Dec
1 year ago

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

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 by another API call? 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

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!

03 Sep
2 years ago

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

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'))
@endif

I have a layout for the messages:

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

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

@extends('layouts.messages')

@section('type', 'info')

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

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.

14 Aug
2 years ago

godbout left a reply on PHP Fatal Error: Class 'TestCase' Not Found

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.

18 Apr
4 years ago

godbout started a new conversation JWT And Laravel Built In Auth

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?

@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 shouldn't put much overhead on Lumen to get those things running. At the end it's less slick to get the structure of your APIs running under Lumen, which makes me wonder BUT OMG WHY???

godbout left a reply on Practical Uses For Lumen?

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?

11 Apr
4 years ago

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

@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.