michaelnguyen547

michaelnguyen547

Member Since 1 Year Ago

Experience Points 23,490
Experience
Level
Lessons Completed 198
Lessons
Completed
Best Reply Awards 1
Best Answer
Awards
  • Start Your Engines Achievement

    Start Your Engines

    Earned once you have completed your first Laracasts lesson.

  • First Thousand Achievement

    First Thousand

    Earned once you have earned your first 1000 experience points.

  • One Year Member Achievement

    One Year Member

    Earned when you have been with Laracasts for 1 year.

  • Two Year Member Achievement

    Two Year Member

    Earned when you have been with Laracasts for 2 years.

  • Three Year Member Achievement

    Three Year Member

    Earned when you have been with Laracasts for 3 years.

  • Four Year Member Achievement

    Four Year Member

    Earned when you have been with Laracasts for 4 years.

  • Five Year Member Achievement

    Five Year Member

    Earned when you have been with Laracasts for 5 years.

  • School In Session Achievement

    School In Session

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

  • Welcome To The Community Achievement

    Welcome To The Community

    Earned after your first post on the Laracasts forum.

  • Full Time Learner Achievement

    Full Time Learner

    Earned once 100 Laracasts lessons have been completed.

  • Pay It Forward Achievement

    Pay It Forward

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

  • Subscriber Achievement

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • Lifer Achievement

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • Laracasts Evangelist Achievement

    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 Achievement

    Chatty Cathy

    Earned once you have achieved 500 forum replies.

  • Laracasts Veteran Achievement

    Laracasts Veteran

    Earned once your experience points passes 100,000.

  • Ten Thousand Strong Achievement

    Ten Thousand Strong

    Earned once your experience points hits 10,000.

  • Laracasts Master Achievement

    Laracasts Master

    Earned once 1000 Laracasts lessons have been completed.

  • Laracasts Tutor Achievement

    Laracasts Tutor

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

  • Laracasts Sensei Achievement

    Laracasts Sensei

    Earned once your experience points passes 1 million.

  • Top 50 Achievement

    Top 50

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

13 Dec
3 days ago

michaelnguyen547 left a reply on Replace Passport Oauth Private And Public

FYI, I tested and all signed in users get 401 Unauthenticate

12 Dec
4 days ago

michaelnguyen547 started a new conversation Replace Passport Oauth Private And Public

If, for whatever reason, I replace Laravel Passport private and public key (e.g. storage/oauth-private.key and storage/oauth-public.key) with a new pair.

Will this replacement kick out all signed in Passport users?

michaelnguyen547 started a new conversation Telescope Monitor Tags

I have no clues how monitor tags work in Telescope. Any advice?

11 Dec
5 days ago

michaelnguyen547 left a reply on Speed Up Make:migration

@cronix only make:migration runs slow. The command instantly create a migration file, but waiting at "Created Migration: 2018_12_11........" for about 50 seconds

michaelnguyen547 left a reply on Laravel Website With 1500000 Users At The Same Time

check out FortRabbit - they use AWS

michaelnguyen547 started a new conversation Speed Up Make:migration

when I make a new DB migration, it takes 50 seconds to finish. I suspect because Laravel needs to update autoload_classmap and autoload_static.

Is it normal? Can I speed up the process?

michaelnguyen547 left a reply on Exists() Method Not Working As Expected

paste your route here

your model binding is not working

09 Dec
1 week ago

michaelnguyen547 started a new conversation Laravel Upload To S3 With Transfer Acceleration

any idea how this can be done?

08 Dec
1 week ago

michaelnguyen547 started a new conversation How To Create Cloudfront SignedUrl?

I am working with CloudFront to serve content from S3.

WIth S3 only

Storage::disk('s3')->url($image_path); // return a normal s3 url - correct

Storage::disk('s3')->temporaryUrl($image_path, now()->addMinutes(30)) // return S3 signed url - correct

With CloudFront (Restrict Bucket Access is on, Restrict Viewer Access is on Use Signed URLs or Signed Cookies)

Storage::disk('s3')->url($image_path); // return a normal CloudFront url - correct

Storage::disk('s3')->temporaryUrl($image_path, now()->addMinutes(30)) // return S3 signed url - incorrect . I expect CloudFront signed url

any idea how to get a signed URL CloudFront? (example from AWS PHP library https://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.CloudFront.UrlSigner.html)

06 Dec
1 week ago

michaelnguyen547 started a new conversation Scout Enable/disable Queue On Demand

I can set 'queue' => true for scout indexing operation. It would works in 95%. In some scenarios, I want to run scout indexing now (not queue up, even though i have queue set to true in scout config) as part of a transaction. Can I do that?

28 Nov
2 weeks ago

michaelnguyen547 left a reply on Strange Issues With FormRequest

I used redis as session driver + Horizon. For now, I switch to database session driver and see if the problem will occur. Will update later.

my crazy thought is that Horizon and Redis Session Driver do not play nice with each other

michaelnguyen547 left a reply on Strange Issues With FormRequest

something is happening with the project I am working on and I have no clue. When I keep submitting the form with validation errors, I will eventually get back a clean form with no old input and no validation errors.

Working on a clean laravel 5.7 does not have this weird validation issue.

michaelnguyen547 started a new conversation Strange Issues With FormRequest

sometimes, the FormRequest is skipped and the form is rendered again without old inputs.

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use App\Enums\MessagePassengerSendTo;

class PassengerMessageForm extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'subject' => 'required|min:10|max:256',
            'content' => 'required|min:10',
            'platform' => 'required',
            'passengerStatus' => 'required_if:sendTo,' . MessagePassengerSendTo::AllPassenger, // require if send to is all driver
            'recipients' => 'required_if:sendTo,' . MessagePassengerSendTo::CustomizedPassenger,
            'confirm' => 'required_if:sendTo,' . MessagePassengerSendTo::AllPassenger
        ];
    }

}

Here is the controller action

    public function process(PassengerMessageForm $request)
    {
        dd($request->all());
        $message = new Message();
        $message->subject = $request->subject;
        $message->content = $request->content;
        $message->save();

Sometimes, the form is rendered with validation errors. Other times, a new form (without old inputs and validation errors) is rendered. I dont understand why. Even I have the ``dd($request->all())`, it does not reach

26 Nov
2 weeks ago

michaelnguyen547 left a reply on Do I Need Run `queue:work` When I'm Using Horizon?

Don't mix queue:work and horizon together. At the moment, queue supports more driver. Horizon only works with redis. They do the exact same thing though queue gives you more choices such as drivers, throttle with redis etc ...

michaelnguyen547 left a reply on Code Review

@d9705996 thank you very much. I like your solutions.

michaelnguyen547 left a reply on What Are Options For Model Save?

@realrandyallen thanks. It came up when I googled. I thought that someone knows more about the options. The core API and code does not say much.

michaelnguyen547 started a new conversation Code Review

I have several models that upload to S3 , in all of them, I have 3 main functions

    public function retrieveFileUrl()
    {
        return ($this->file) ? Storage::disk('s3')->temporaryUrl($this->file, now()->addMinutes(5)) : '';
    }


    public function uploadToS3($newFile, $path)
    {
        $this->deleteFromS3();

        $this->file = Storage::disk('s3')->putFile($path, $newFile);

        $this->save();
    }

    private function deleteFromS3()
    {
        if ($this->file) {
            Storage::disk('s3')->delete($this->file);
        }
    }

I figure that I can create a class S3Uploader to handler all uploading to S3. I need

  • $model // to tell which table I am working on, can be user, document
  • $attribute // which column I am working on, $user->photo, $document->file
class S3Uploader
{
    public static function upload($model, $attribute, $request, $path)
    {
        rnew self($vehicle, $attribute, $request, $path)->uploadToS3();
    }

    public function __construct(Model $model, $attribute, $request, $path)
    {
        $this->model = $model;
        $this->attribute = $attribute;
        $this->path = $path;
        $this->request = $request;
    }

    public uploadToS3() {

        if ($this->request->hasFile($this->attribute)) {
            $this->deleteFromS3();
            $this->model->{$this->attribute} = Storage::disk('s3')->putFile($this->path, $this->request->file($this->attribute));
            $this->model->save();
        }
    }

    public retrieveFromS3() {
        return ($this->model->$attribute) ? Storage::disk('s3')->temporaryUrl($this->model->$attribute, now()->addMinutes(5)) : asset('placeholder.jpg');
    }

    private deleteFromS3($attribute) {
        if ($this->model->{$this->attribute}) {
            Storage::disk('s3')->delete($this->model->{$this->attribute});
        }
    }
}

I think it does what I need, however, this $this->model->{$this->attribute} bothers me. Any suggestions for S3Uploader overall?

michaelnguyen547 left a reply on What Are Options For Model Save?

@REALRANDYALLEN - @realrandyallen I can't find anything about save options

michaelnguyen547 started a new conversation What Are Options For Model Save?

the documentation does not say much and I can not find a good explanation in source code.

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Model.html#method_save

22 Nov
3 weeks ago

michaelnguyen547 left a reply on Image Cropper Before Uploading

@snapey I like the Slim library. Can you share the laravel code that saves image(s) from Slim ?

michaelnguyen547 left a reply on How To Automatically Download A File Of Storage???

@EDDIEPUIG - it is weird that you are trying to upload and download file at the same time.

michaelnguyen547 left a reply on How To Automatically Download A File Of Storage???

https://laravel.com/docs/5.7/filesystem#retrieving-files

return Storage::download('file.jpg');

return Storage::download('file.jpg', $name, $headers);
21 Nov
3 weeks ago

michaelnguyen547 left a reply on What Does $guard In Admin Or User Do?

@fraserk Thanks.

It appears < L5.3 use protected $guard = 'admin'. Since > L5.3 , Laravel use

protected function guard()
{
    return Auth::guard('guard-name');
}

michaelnguyen547 left a reply on Different Way To Redirect

@tykus thanks for the write up

michaelnguyen547 started a new conversation What Does $guard In Admin Or User Do?

I am reading some multi auth tutorial and most of them add protected $guard = 'admin' to Admin class. I can not find anything in Laravel documentation about this protected $guard.

namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Admins extends Authenticatable
{
    
    protected $guard = 'admin';
    ......
}

anybody know about thing about this $guard ?

michaelnguyen547 started a new conversation Different Way To Redirect

I am looking at Illuminate/Routing/Redirector - the main actor that handlers redirect()

Need some gurus to help me understand the use case and when I should use guest, intended, away, action

    /**
     * Create a new redirect response, while putting the current URL in the session.
     *
     * @param  string  $path
     * @param  int     $status
     * @param  array   $headers
     * @param  bool    $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function guest($path, $status = 302, $headers = [], $secure = null)
    {
        $request = $this->generator->getRequest();

        $intended = $request->method() == 'GET' && $request->route() && ! $request->expectsJson()
                        ? $this->generator->full()
                        : $this->generator->previous();

        if ($intended) {
            $this->session->put('url.intended', $intended);
        }

        return $this->to($path, $status, $headers, $secure);
    }

    /**
     * Create a new redirect response to the previously intended location.
     *
     * @param  string  $default
     * @param  int     $status
     * @param  array   $headers
     * @param  bool    $secure
     * @return \Illuminate\Http\RedirectResponse
     */
    public function intended($default = '/', $status = 302, $headers = [], $secure = null)
    {
        $path = $this->session->pull('url.intended', $default);

        return $this->to($path, $status, $headers, $secure);
    }

    /**
     * Create a new redirect response to an external URL (no validation).
     *
     * @param  string  $path
     * @param  int     $status
     * @param  array   $headers
     * @return \Illuminate\Http\RedirectResponse
     */
    public function away($path, $status = 302, $headers = [])
    {
        return $this->createRedirect($path, $status, $headers);
    }

    /**
     * Create a new redirect response to a controller action.
     *
     * @param  string|array  $action
     * @param  mixed   $parameters
     * @param  int     $status
     * @param  array   $headers
     * @return \Illuminate\Http\RedirectResponse
     */
    public function action($action, $parameters = [], $status = 302, $headers = [])
    {
        return $this->to($this->generator->action($action, $parameters), $status, $headers);
    }

20 Nov
3 weeks ago

michaelnguyen547 left a reply on Can Not Get Horizon Dashboard Authorization Work

@d9705996 Thanks for pointing that out. I test with a fresh L5.7 app and it works. I am using multi-auth (https://github.com/Hesto/multi-auth) in my app and it definitely interfere with Horizon gate.

The $request->user() return null and I don't know why

vendor/laravel/horizon/src/HorizonApplicationServiceProvider.php
    /**
     * Configure the Horizon authorization services.
     *
     * @return void
     */
    protected function authorization()
    {
        $this->gate();

        Horizon::auth(function ($request) {
            return app()->environment('local') ||
                   Gate::check('viewHorizon', [$request->user()]);
        });
    }

michaelnguyen547 started a new conversation Can Not Get Horizon Dashboard Authorization Work

Horizon has new Dashboard Authorization using Gate. I set env to production, and set return true inside gate. I get 403 when accessing Horizon, which I dont understand, the gate should allow me to get in.

/**
 * Register the Horizon gate.
 *
 * This gate determines who can access Horizon in non-local environments.
 *
 * @return void
 */
protected function gate()
{
    Gate::define('viewHorizon', function ($user) {
    return true; // still get 403
    });
}

what do I miss?

19 Nov
3 weeks ago

michaelnguyen547 started a new conversation Commit Public/vendor/telescope To Git?

should I commit telescope public asset to git?

18 Nov
4 weeks ago

michaelnguyen547 left a reply on Change Carbon Timestamp Format

@gabotronix save datetime as 2018-11-16 01:58:53 in your database. When you display on a page, format it to 01:58:53 day-Month-YEAR

    /**
     * Handle the event.
     *
     * @param  Login  $event
     * @return void
     */
    public function handle(Login $event)
    {
        .....
        $user->last_login_at = Carbon::now();
         .....
    }

/**
* Display on page
*/

{{ $user->last_login_at->format('H:i:s d-m-Y ') }}

michaelnguyen547 started a new conversation Code Review With If, Switch, Foreach

I have this code, it works but it is messy. Any advices to improve it?

        foreach ($request->platform as $platform) {
            switch ($platform) {
                case \App\Enums\Platform::SMS:

                    // customized drivers
                    if ($request->recipients) {
                        $recipients = \App\Provider::find(explode(',', $request->recipients));
                        foreach ($recipients as $recipient) {
                            ProcessSMS::dispatch($recipient, $message);
                        }
                    } else {
                        foreach ($request->driverStatus as $driverStatus) {
                            \App\Provider::where('type', $driverStatus)->chunk(100, function ($recipients) {
                                foreach ($recipients as $recipient) {
                                    ProcessSMS::dispatch($recipient, $message);
                                }
                            });
                        }
                    }

                    break;

                case \App\Enums\Platform::PUSH:

                    if ($request->recipients) {
                        $recipients = \App\Provider::find(explode(',', $request->recipients));
                        foreach ($recipients as $recipient) {
                            ProcessPushNotification::dispatch($recipient, $message);
                        }
                    } else {
                        foreach ($request->driverStatus as $driverStatus) {
                            \App\Provider::where('type', $driverStatus)->chunk(100, function ($recipients) {
                                foreach ($recipients as $recipient) {
                                    ProcessSMS::dispatch($recipient, $message);
                                }
                            });
                        }
                    }
                    break;
            }
        }

michaelnguyen547 left a reply on Where To Record A Log To Database When An Notification Is Successfuly Sent?

if it is successfully sent, I create a new record with datetime, subject, content, recipient name, status (Sent)

The problem is with (Notifications)[https://laravel.com/docs/5.7/notifications#sms-notifications], where do I do that?

I don't want to do it in toNexmo() because the message is not sent yet.

@skoobi does the Notification Event fire after I do $user->notify(new InvoicePaid($invoice)); or after the actual send Mail or send SMS action inside InvoicePaid

17 Nov
4 weeks ago

michaelnguyen547 started a new conversation Where To Record A Log To Database When An Notification Is Successfuly Sent?

when a notification is successfully sent, i want to log to database. any idea where to do it?

michaelnguyen547 started a new conversation Rate Limiting For Notifications?

It is possible for Queued jobs to (rate limiting)[https://laravel.com/docs/5.7/queues#rate-limiting]

How can I do that with (Laravel Notifications)[https://laravel.com/docs/5.7/notifications#sms-prerequisites]

16 Nov
1 month ago

michaelnguyen547 started a new conversation Redis Failed Job ??

in queue.php, there is failed option to tell Laravel the location to save failed jobs.

    'failed' => [
        'database' => env('DB_CONNECTION', 'mysql'),
        'table' => 'failed_jobs',
    ],

I am using redis as queue driver, what do I put in the failed so that Laravel will save failed jobs to redis.

15 Nov
1 month ago

michaelnguyen547 left a reply on Where Does Parameters From Queue Job Handle Come From?

@cronix i think you read my question wrong, it is about the AudioProcessor variable in handle() function.

@tykus i think you got it correct that this has to do with type hinted dependencies. I’ve read Laravel officials doc and some on stackoverflow but I still can not understand how it work. Do you know any good explanation of service container and service provider with clear examples ?

michaelnguyen547 started a new conversation Where Does Parameters From Queue Job Handle Come From?

I am reading the Queue Job and cannot understand where AudioProcess $processor inside handle method coming from?

class ProcessPodcast implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $podcast;

    /**
     * Create a new job instance.
     *
     * @param  Podcast  $podcast
     * @return void
     */
    public function __construct(Podcast $podcast)
    {
        $this->podcast = $podcast;
    }

    /**
     * Execute the job.
     *
     * @param  AudioProcessor  $processor
     * @return void
     */
    public function handle(AudioProcessor $processor) 
    {
        // Process uploaded podcast...
    }
}
14 Nov
1 month ago

michaelnguyen547 left a reply on Error "composer Update"

your git repo does not have the full project.

anyway, check their Installation guide. Contact them if you have questions

13 Nov
1 month ago

michaelnguyen547 left a reply on Error "composer Update"

can you upload your project on GitHub?

michaelnguyen547 left a reply on Error "composer Update"

try composer dump-autoload first, then composer update again

07 Nov
1 month ago

michaelnguyen547 started a new conversation Laravel And Vue Lesson

Are there any Laracast lessons that use both Laravel and Vue in a project? I m looking for detail lessons on how to use Vue within Laravel.

06 Nov
1 month ago

michaelnguyen547 started a new conversation Where Does Laravel Save Cache?

the cache driver is set to redis. But I don't see laravel save anything, but Telescope still shows some cache is being hit. Where is the cache?

Screenshot [https://imgur.com/a/DoO6ad3]

02 Nov
1 month ago

michaelnguyen547 started a new conversation Bootstrap And Vue

I am thinking to use Keen theme (https://themes.getbootstrap.com/product/keen-the-ultimate-bootstrap-admin-theme/). it is purely jquery.

I am new to Vue so does not know much. If I decide to use Vue components in some pages and want to use Keen Theme, is it an easy thing to do?

01 Nov
1 month ago

michaelnguyen547 left a reply on How To Send Request To An External Api

all right, just double check that I am not crazy. Thank you for feedback

michaelnguyen547 started a new conversation How To Send Request To An External Api

At the lowest level, I can use curl to an external API server.

For some reasons, I can not do the same with Illuminate\Http\Request.

Here is my example


use Illuminate\Http\Request;

        $request = Request::create(
            'https://google.ca/search=laravel',
            'GET'
        );

$response = app()->handle($request);

The request is sent to myserver/search=laravel , not to google.ca/search=laravel.

I don't know why? Does Request not work for external API?

29 Oct
1 month ago

michaelnguyen547 started a new conversation Check Signed In User Can Edit A Place

I have this check to make sure the signed in user can edit a post


if ($post->author_id !== Auth::id()) {
            return response()->json([
                'message' => 'The given data was invalid',
                'errors' => [
                    'passenger' => 'Attempt to update unauthorized resource'
                ]
            ], 422);
        }

I have the check in multiple places in multiple controllers. What is the best way to do this without copy/paste everywhere when I need to check?

23 Oct
1 month ago

michaelnguyen547 started a new conversation Where Does Redis Save My Queued Jobs And Failed Jobs?

First time using Redis so I am finding my way around. Using Redsmind for GUI, I can not find where Redis saved queued jobs and failed jobs. I thought it will be in database "10" as defined in database.php but Resdmind shows nothing.

I use Horizon which can process the job fine. I set up a delay of 5 mins so it should show in Redis.


// queue.php
    'connections' => [

        'redis' => [
            'driver' => 'redis',
            'connection' => 'queue',
            'queue' => 'default',
            'retry_after' => 90,
            'block_for' => 5
        ],
    ],

// database.php
    'redis' => [
        'client' => 'predis',

        // 'cluster' => false,
        'cache' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 0,
        ],

        'default' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 10,
        ],

        'queue' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 2,
        ],

        'sessions' => [
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'password' => env('REDIS_PASSWORD', null),
            'port' => env('REDIS_PORT', 6379),
            'database' => 1,
        ],
    ],

// horizon.php
    'environments' => [
        'production' => [
            'supervisor-1' => [
                'connection' => 'redis',
                'queue' => ['default'],
                'balance' => 'simple',
                'processes' => 10,
                'tries' => 3,
            ],
        ],

        'local' => [
            'supervisor-1' => [
                'connection' => 'redis',
                'queue' => ['default'],
                'balance' => 'simple',
                'processes' => 3,
                'tries' => 3,
            ],
        ],
    ],
19 Oct
1 month ago

michaelnguyen547 left a reply on Homestead Vagrant Box And Homestead Itself

ok. i think i got it now

basically, vagrant box includes all the software

Ubuntu 18.04
Git
PHP 7.3
PHP 7.2
PHP 7.1
PHP 7.0
PHP 5.6
Nginx
Apache (Optional)
MySQL
MariaDB (Optional)
Sqlite3
PostgreSQL
Composer
Node (With Yarn, Bower, Grunt, and Gulp)
Redis
Memcached
Beanstalkd
Mailhog
Neo4j (Optional)
MongoDB (Optional)
Elasticsearch (Optional)
ngrok
wp-cli
Zend Z-Ray
Go
Minio

then laravel/homestead configure these softwares, set up sites config (nginx/apache),