michaelnguyen547

michaelnguyen547

Member Since 2 Years Ago

Experience Points 29,150
Experience Level 6

850 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 246
Lessons
Completed
Best Reply Awards 1
Best Reply
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 Feb
1 week ago

michaelnguyen547 started a new conversation DevDependencies Vs Dependencies

I am using Laravel Mix v4. I am having a hard time to understand which packages should be in devDependencies vs dependencies (in package.json).

    "devDependencies": {
        "axios": "^0.17",
        "bootstrap-sass": "^3.3.7",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-mix": "^4.0",
        "lodash": "^4.17.4",
        "resolve-url-loader": "2.3.1",
        "sass": "^1.17.0",
        "sass-loader": "7.*",
        "vue": "^2.5.7",
        "vue-template-compiler": "^2.6.6"
    },
    "dependencies": {
        "laravel-echo": "^1.5.2",
        "popper.js": "^1.14.7",
        "pusher-js": "^4.3.1",
        "vue-resource": "^1.5.1",
        "webpack-s3-plugin": "^1.0.3"
    }

when I run npm run dev or npm run production, how does Laravel mix know should it get devDependencies or should it only get dependencies.

FYI, I would need the following package only

axios (to make ajax call)
laravel-mix (so it would work when i run npm run dev/prod)
lodash ( it is in resources/assets/js/bootstrap.js , dont know what it does to my project)
vue
laravel-echo (to use with pusher)
popper ( it is in resources/assets/js/bootstrap.js , dont know what it does to my project)
pusher-js (used with laravel-echo)
webpack-s3-plugin (publish to s3)

I dont know what the rest are for? Some were added automatically when I first ran npm run dev.

11 Feb
1 week ago

michaelnguyen547 started a new conversation Clean Up Query Parameters When Using Yajrabox DataTables

I am using Yajra DataTables and it bothers me that query parameters includes junks that I dont want

here is an example @ https://datatables.yajrabox.com/fluent/custom-filter

and this is the query sent to server

https://datatables.yajrabox.com/fluent/custom-filter-data?draw=3&columns%5B0%5D%5Bdata%5D=id&columns%5B0%5D%5Bname%5D=id&columns%5B0%5D%5Bsearchable%5D=true&columns%5B0%5D%5Borderable%5D=true&columns%5B0%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B0%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B1%5D%5Bdata%5D=name&columns%5B1%5D%5Bname%5D=name&columns%5B1%5D%5Bsearchable%5D=true&columns%5B1%5D%5Borderable%5D=true&columns%5B1%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B1%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B2%5D%5Bdata%5D=email&columns%5B2%5D%5Bname%5D=email&columns%5B2%5D%5Bsearchable%5D=true&columns%5B2%5D%5Borderable%5D=true&columns%5B2%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B2%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B3%5D%5Bdata%5D=created_at&columns%5B3%5D%5Bname%5D=created_at&columns%5B3%5D%5Bsearchable%5D=true&columns%5B3%5D%5Borderable%5D=true&columns%5B3%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B3%5D%5Bsearch%5D%5Bregex%5D=false&columns%5B4%5D%5Bdata%5D=updated_at&columns%5B4%5D%5Bname%5D=updated_at&columns%5B4%5D%5Bsearchable%5D=true&columns%5B4%5D%5Borderable%5D=true&columns%5B4%5D%5Bsearch%5D%5Bvalue%5D=&columns%5B4%5D%5Bsearch%5D%5Bregex%5D=false&order%5B0%5D%5Bcolumn%5D=0&order%5B0%5D%5Bdir%5D=asc&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&name=&email=ad&_=1549932861825

Ideally, it should only include the name, start, length and email

https://datatables.yajrabox.com/fluent/custom-filter-data?draw=3&start=0&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&name=&email=ad&_=1549932861825

is there a way to do that?

michaelnguyen547 left a reply on <div Id"app"> Does Not Render With Vue

do I have to npm install? I used vuejs from a cdn.

michaelnguyen547 started a new conversation <div Id"app"> Does Not Render With Vue

i am starting to use Vue and hit a breakpoint already.

my html look like this

<head>
        <script src="https://cdn.jsdelivr.net/npm/vue"></script>

<script src="/js/vuelidate-0.7.4/vuelidate.min.js"></script>
<script src="/js/vuelidate-0.7.4/validators.min.js"></script>
</head>
<body>
// other html tags
<div id="app">
<form ...>

</form>
</div>

<script>
new Vue({
    el: '#app'
})
</script>
</body>

The part from <div id="app"> ... </div> does not render when I set `el: '#app`, I dont know why? remove the `el` will have the <div id="app"> section show again.
09 Feb
1 week ago

michaelnguyen547 left a reply on Predis Many Issues

I'm using FortRabbit to host my app. I am asking them if they support phpredis

michaelnguyen547 started a new conversation Predis Many Issues

I am using Redis Labs for redis instance. It is a multi-az setup using AWS.

I often get Redis issues that can not be explained (caught by Sentry.io).

Predis\Connection\ConnectionException Error while writing bytes to the server.

Predis\Connection\ConnectionException Connection timed out

Redis Labs was very adamant that this has nothing to do with their servers. They can not find any evidents the server was down when the errors occured.

WIth the help of Google, I've seen many Predis connection/writing bytes to the server issue. This is my config for redis

    'host' => env('REDIS_HOST_QUEUE', '127.0.0.1'),
    'password' => env('REDIS_PASSWORD_QUEUE', null),
    'port' => env('REDIS_PORT_QUEUE', 6379),
    'database' => 2,
    'persistent' => true,
    'read_write_timeout' => 60

I feel that 99% this has to do with predis library than the server itself. Any suggestions to fix these predis problems?

07 Feb
1 week ago

michaelnguyen547 started a new conversation Retry Dispatching Job

I am running issues with Redis Server randomly can not connect when I dispatch a job. Is there a way to attempt to dispatching job 3 times for example.

php // This job is sent to the default queue... Job::dispatch(); // when redis server is not responsive, no job will be queued. I would like to re-try dispatch at least 3 times

24 Jan
3 weeks ago

michaelnguyen547 started a new conversation Soft Delete Model And Drop Down

I have a State and City with soft delete. When updating user, I want to show State (active) plus the soft deleted state the user has, otherwise the dropdown value is blank. What is the best way to do this?

18 Jan
1 month ago

michaelnguyen547 started a new conversation Handle Deadlock With Manual Transaction

I am aware that Laravel support deadlock with db transaction automatically

DB::transaction(function () {
    DB::table('users')->update(['votes' => 1]);

    DB::table('posts')->delete();
}, 5);

I am curious that in case of manual transaction using DB::beginTransaction() , DB::commit() and DB::rollback(). How can I handle deadlock ?

16 Jan
1 month ago

michaelnguyen547 started a new conversation Overwrite Queue And Delay In A Job

instead of doing SendMail::dispatch($email)->onQueue('high')->delay(now()->addMinute()),

Can I put the queue and delay inside a job so I can just do SendMail::dispatch($email)

15 Jan
1 month ago

michaelnguyen547 started a new conversation Polymorphic Relation

https://laravel.com/docs/5.7/eloquent-relationships#polymorphic-relationships


$comment = App\Comment::find(1);

$commentable = $comment->commentable;

commentable can be App\Video or 'App\Post'. Is it possible to get exact type such as $comment->video or $comment->post

michaelnguyen547 started a new conversation DB Transaction Rollback Runs There Is Exception

finally always run no matter there are exceptions or not.

I am looking for a way to run DB::rollback only if there are exceptions

DB::transaction();

try {
// do some works with db
DB::commit();
} catch (PaymentException $e) {
DB::rollback();
} catch (RareException $e) {
DB::rollback()
} catch (Throwable $e) {
DB::rollback();
}
10 Jan
1 month ago

michaelnguyen547 started a new conversation Validation Between 1 And 5

I feel stupid that can not figure out how to validate if a field is between 1 and 5.

If it is 0, it fails, if it is greater than 5, it fails.

can not figure out, tried min, max, between, none of them works

michaelnguyen547 left a reply on Autoload_classmap.php And Autoload_static.php In Vendor/composer

@d9705996 does composer automatically do dump-autoload when you run composer add/update/install

09 Jan
1 month ago

michaelnguyen547 started a new conversation Overwrite Passport Keys Creation Location?

by default, php artisan passport:keys will generate keys at /storage directory. Is there a way to ask php artisan passport:keys to generate keys in different directory?

07 Jan
1 month ago

michaelnguyen547 started a new conversation Update Some Attributes And Do Not Fire Saving Events

I have a model observers for saving event on estimated_fee. I only want the saving event when i am saving estimated_fee. If I update other attributes, I dont want the saving event fired. $model->save() always fire the saving event.

Is there other way?

04 Jan
1 month ago

michaelnguyen547 started a new conversation Autoload_classmap.php And Autoload_static.php In Vendor/composer

how does Laravel use these 2 files?

I move some classes around and Laravel still works even though old path of moved classes are still in autoload_classmap and autoload_static.

Do i suppose to run composer dump-autoload when I move classes around in Laravel project?

20 Dec
2 months ago

michaelnguyen547 started a new conversation Feedback On Naming Class

I have 2 classes: DistanceMatrix and VehicleTypeDistanceMatrix

DistanceMatrix takes an orign and destination, its job is to find on travel time and distance

VehicleTypeDistanceMatrix takes an origin and a vehicle type, its job is to find the average wait time.

I m not happy with the naming. It does not convey the meaning well.

19 Dec
2 months ago

michaelnguyen547 left a reply on What Can People Do With My Oauth-private.key And Oauth-public.key

@bobbybouwmann thanks for the reply. The question is OAuth public / private keys generated by Laravel Passport.

18 Dec
2 months ago

michaelnguyen547 started a new conversation What Can People Do With My Oauth-private.key And Oauth-public.key

if they have my oauth private/public key, what can people do to my website/api/server?

13 Dec
2 months 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
2 months 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
2 months 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
2 months ago

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

any idea how this can be done?

08 Dec
2 months 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
2 months 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 months 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 months 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
2 months 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
2 months 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 months 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()]);
        });
    }