J0wZ

J0wZ

Member Since 1 Year Ago

Experience Points
46,580
Total
Experience

3,420 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
424
Lessons
Completed
Best Reply Awards
1
Best Reply
Awards
  • start your 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-in-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 Created with Sketch.

    Subscriber

    Earned if you are a paying Laracasts subscriber.

  • lifer Created with Sketch.

    Lifer

    Earned if you have a lifetime subscription to Laracasts.

  • evangelist 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.

Level 10
46,580 XP
Sep
01
2 weeks ago
Activity icon

Replied to $this Is Null In Models When Using A Model

My problem was the next one. A user is considered member of a company only if it has a role into the company.

So I made this attribute / query. Here is an image who can help.

https://i.imgur.com/E0Sdsq5.png

Activity icon

Replied to $this Is Null In Models When Using A Model

I am getting an error.

In fact companies is not a relation but a accessor.

    public function getCompaniesAttribute()
    {
        return Company::select(['companies.*'])
            ->join('roles', 'companies.id', '=', 'roles.company_id')
            ->join('model_role', 'roles.company_id', '=', 'model_role.model_id')
            ->distinct()
            ->get();
    }
Activity icon

Replied to $this Is Null In Models When Using A Model

Yes it is. And it is null.

Activity icon

Started a new Conversation $this Is Null In Models When Using A Model

Hello,

Here is my question, I am doing a where on a relation and the $this->current_company_id only have a value if I am acting as the authenticated user.

If I an fetching a random user from DB $this is actually null.

    public function roles(): MorphToMany
    {
        return $this->morphToMany(
            config('permission.models.role'),
            'model',
            config('permission.table_names.model_has_roles'),
            config('permission.column_names.model_morph_key'),
            'role_id'
        )->where('company_id', $this->current_company_id);
    }

Do you have any way to have the $this acting as the current model.

$user = User::find(1);

$user->companies->first()->roles

// PHP Notice:  Trying to get property 'current_company_id' of non-object in /Users/anthonyrubio/Sites/artidevis/artidevis-server/app/Traits/HasCompany.php on line 13
Activity icon

Replied to Cannot Assign Role To User

    public function roles(): MorphToMany
    {
        return $this->morphToMany(
            config('permission.models.role'),
            'model',
            config('permission.table_names.model_has_roles'),
            config('permission.column_names.model_morph_key'),
            'role_id'
        )->where('roles.company_id', auth()->user()->current_company_id);
    }
Activity icon

Replied to Cannot Assign Role To User

This comes from the relation roles from the Laravel Spatie permission I wanted to customize to only return the roles of the current company of the user. The current_user_id here is equal to null.

Activity icon

Started a new Conversation Cannot Assign Role To User

Hi there,

I am trying to do this :

        $user = auth()->user()->holding->users()->create([
            'firstname' => $request->firstname,
            'lastname' => $request->lastname,
            'email' => $request->email,
            'invitation_token' => Str::random(32)
        ]);

        collect($request->roles)->each(function ($role) use ($user) {
            $role = Role::withoutGlobalScopes()->where('id', '=', $role)->get()->first();
            $user->assignRole($role);
        });

But I have to admin that nothing happen when I do $user->assignRole($role);. My role relation on the user is still empty. Any idea ?

Aug
27
3 weeks ago
Activity icon

Replied to Remove Global Scope On A Model Instance

@martinbean what solution do you suggest ?

Activity icon

Replied to Remove Global Scope On A Model Instance

This could be a solution but I don't like the idea because it's a lot more code than currently. But you idea works actually @tykus (as mine). Thanks for helping !

Activity icon

Started a new Conversation Remove Global Scope On A Model Instance

Hi there,

I am building a simple multi tenant app so I added a trait which has global scope to some of my models :

trait HasCompany {
    protected static function bootHasCompany()
    {
        static::addGlobalScope('company', function (Builder $builder) {
            $builder->where(function ($builder) {
                return $builder
                    ->where('company_id', auth()->user()->current_company_id)
                    ->orWhereNull('company_id');
            });
        });
    }
}

Then I am creating a Company in a the controller :

    public function store(CompanyRequest $request)
    {
        /** @var Company $company */
        $company = auth()->user()->holding->companies()->create($request->companyPayload());

        $company->location()->create($request->locationPayload());
        $company->emailAddress()->create($request->emailPayload());
        $company->phoneNumbers()->createMany($request->phoneNumbersPayload());

        return new CompanyResource($company);
    }

The things is : due to the trait applied on Location / EmailAddress and PhoneNumber models when I dump $company I am not able to see the relations.

I tried to do switch the current_company_id to the company who was just created, in fact, it work but I have to eager load the relations using ->with(['location', 'emailAddress', 'phoneNumber]). Maybe you have a cleaner way ?


    public function store(CompanyRequest $request)
    {
        /** @var Company $company */
        $company = auth()->user()->holding->companies()->create($request->companyPayload());

        $company->location()->create($request->locationPayload());
        $company->emailAddress()->create($request->emailPayload());
        $company->phoneNumbers()->createMany($request->phoneNumbersPayload());

        auth()->user()->current_company_id = $company->id;

	$company->with(['location', 'emailAddress', 'phoneNumber'])

        return new CompanyResource($company);
    }
Aug
25
3 weeks ago
Activity icon

Replied to Create A "fake" Relationship

Thank you @click i was thinking we cannot do a relationship without "direct" foreign key.

Activity icon

Started a new Conversation Create A "fake" Relationship

Hi there,

This is what I am doing using a scope in my User model :

    public function scopeCompanies($query)
    {
        return Company::where('holding_id', $this->holding_id);
    }

I am wondering if I could do something more "fluent", which is not forcing me to do $user->companies()->get() but more $user->companies only.

Could do it with an accessor i guess but is there a cleaner way ?

Aug
24
3 weeks ago
Activity icon

Started a new Conversation Different Data Depending On Unit Test

Hi,

I am experiencing a weird thing.

I created a factory class to generate my users depending on some data :

class UserFactory
{
    protected string $permission;

    public function withPermission($permission)
    {
        $this->permission = $permission;

        return $this;
    }

    public function create(int $holdingId = 1, int $companyId = 1)
    {
        if ($this->permission) {
            $role = factory(Role::class)->create(['company_id' => $companyId]);
            $role->syncPermissions(Permission::where('name', 'like', $this->permission . '%')->get());


	// The problem seems to be here
            $user = factory(User::class)->create([
                'holding_id' => $holdingId,
                'current_company_id' => $companyId
            ])->assignRole($role);
        }

        return factory(User::class)->create([
            'holding_id' => $holdingId,
            'current_company_id' => $companyId
        ]);
    }
}

After that I am using this factory to generate a user this is what I am doing in my VatTest.php

$user = app(UserFactory::class)->withPermission('library-parameters')->create();

// Here if I do 
$user->getRoles // I have an empty array of rioles

// But if I do
User::find($user->id)->getRoles // I am getting the role back

Any idea ? I tried some refresh() on the model and had the same result.

All of the role / permission process is made using the spatie permission package.

Activity icon

Replied to Feature Test With Seed Data

I found this : https://laracasts.com/discuss/channels/testing/seeding-the-database-for-all-tests-55?page=1#reply=520419

Which seems a good option. If you have any suggestion, I take it !

Activity icon

Started a new Conversation Feature Test With Seed Data

Hi there,

I am looking for the best way to run feature test with data already in the database.

Should I use $this->seed(); and RefreshDatabase in my test ? Do youy have any other solution ? I would like to avoid dunning seed before each test. Thanks.

Aug
16
1 month ago
Activity icon

Started a new Conversation API Store Method With Relations And Forme Validation

Hello,

I am bulding an API. Here is the schema. A company can have one address, one email and many phone numbers.

About what I am think to do :

  • Validate the nested data in the CompanyRequest. For example (for nested data) :
'address.street' => 'required|string'
  • Change my controller method from (currently only creating the company with name and corporate name only) :
    public function store(CompanyRequest $request)
    {
        return new CompanyResource(auth()->user()->owns()->create($request->validated()));
    }

=> To something like that :

public function store(CompanyRequest $request)
    {
  	$validData = $request->validated();
        $company = auth()->user()->owns()->create($validData->only(['name', 'corporate']));

	// Then here check if the request has data about address and create the relation using
	$company->address()->create($validData->only()) // Only the data form address 

	// Then the same process for email and phone numbers

    }

Well this is gonna work but I don't find it suuuuuuuper clean. Do you have a cleaner way to achieve that ?

Aug
15
1 month ago
Activity icon

Replied to Update A One To One Relationship ?

Done ! Thanks for the help btw !

Activity icon

Started a new Conversation Model Route Binding Force Variable Name

Hi,

As all my code is in english I have an API Resource route :

Route::apiResource('fournisseur', 'SupplierController');

The name of the route define the name of the variable which is binded into my methods. So I have to do :

    public function show(Supplier $fournisseur)
    {
        return new SupplierResource($fournisseur);
    }

Is there a way to avoid this ? Thanks !

(In fact I would like to call my $supplier and not $fournisseur)

Aug
12
1 month ago
Activity icon

Replied to Update A One To One Relationship ?

I think my problem comes from logic. The thing is : Owners of holdings are users. In my users table I have a holding_id column. And in the holding table I have a owner_id.

// Holding Model
    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function users(): HasMany
    {
        return $this->hasMany(User::class);
    }

// User Model
    public function holding(): HasOne
    {
        return $this->hasOne(Holding::class);
    }

    public function owns(): HasOne
    {
        return $this->hasOne(Holding::class, 'owner_id', 'id');
    }
Activity icon

Replied to Update A One To One Relationship ?

This is actually what I dead. Got an error that eloquent wants an array. So I tried $holding->toArray(). Again an error.

Activity icon

Replied to Update A One To One Relationship ?

Sorry I made a mistake. My owner (which is a user too) has a holding_id property. This is the field I want to update.

So i tried :

$owner->holding->save($holding);

Nothing ...

Activity icon

Started a new Conversation Update A One To One Relationship ?

Hi there. I have a one to many relationship. On holding have one owner (so i first create the owner) and one holding have one owner.

First, am I right in my logic ? Second, how could I update the relationship without doing :

$holding->owner_id = $owner->id;
$holding->id

Here is my code :


$owner = User::create([
            'firstname' => 'John',
            'lastname' => 'Doe',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
        ]);

        $holding = $owner->holding()->create([
            'reference' => Str::uuid()
        ]);

	// This part 
        $holding->owner_id = $owner->id;
	$holding->id

Thanks for the help !

Aug
10
1 month ago
Activity icon

Replied to Automatically Pass Foreign Key When Create From Relationship

I could do it this way but I am sure Laravel is good enough to have a "shorter" solution.

User::create([
            'firstname' => 'John',
            'lastname' => 'Doe',
            'email' => '[email protected]',
            'password' => bcrypt('password'),
            'holding_id' => Holding::create([
                'reference' => Str::uuid(),
            ])->id
]);
Activity icon

Started a new Conversation Automatically Pass Foreign Key When Create From Relationship

Hi,

I have a One-to-Many relationship. A holding can have many users. But a user can only belongs to one holding. This is what I am doing :

        $user = User::create([
            'firstname' => 'John',
            'lastname' => 'Doe',
            'email' => '[email protected]',
            'password' => bcrypt('password')
        ]);

        $user->holding()->create([
            'reference' => Str::uuid()
        ]);

The problem is : the holding_id on the $user instance is not updated (and is NULL). Is it normal ? Thanks.

Activity icon

Replied to When To Use An Event Or Job ?

@martinbean I think didn't express myself perfectly.

I would like to understand the differences between dispatching a Job and dispatching an event which has listeners.

Aug
09
1 month ago
Activity icon

Replied to When To Use An Event Or Job ?

@martinbean so let's say I want to send an e-mail on all users who have subscribed to a post whenever a new message is posted. Should I use a Job or an Event ? Both can achieve this no ?

Activity icon

Started a new Conversation When To Use An Event Or Job ?

Hi there,

I am watching the course "queue it up" of Jeffrey. And I would like ton understand when should we use an event or a job ? Also, whats motivate our choice. Do you have some real life examples ? Thanks !

Aug
07
1 month ago
Activity icon

Replied to Sanctum Error "token Mismatch" When Trying To Login Using Insomnia

Any idea ? Stuck on it since yesterday 😭

Aug
06
1 month ago
Activity icon

Replied to Sanctum Error "token Mismatch" When Trying To Login Using Insomnia

Even when I am trying to copy the content of the cookie I am getting back into the headers of Insomnia under the property X-XSRF-TOKEN I am getting a The payload is invalid this time.

Activity icon

Started a new Conversation Sanctum Error "token Mismatch" When Trying To Login Using Insomnia

Hi,

I did all the installation of Laravel Sanctum.

config/cors.php


    'paths' => [
        'api/*',
        'login',
        'logout',
        'sanctum/csrf-cookie',
    ],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

.env

SESSION_DOMAIN=localhost

SANCTUM_STATEFUL_DOMAINS=localhost

I am first hiting /sanctum/csrf-cookie and then after /login. I get back an error CSRF token mismatch.

Any idea ? Thanks !

Aug
04
1 month ago
Activity icon

Replied to Laravel Telescope Not Showing Records

It's 100% possible to access Telescope in production mode ...

Aug
03
1 month ago
Activity icon

Awarded Best Reply on Adding Sharable Link For Facebook Throws Error?

As a good practice you should have a file in config who uses env() and then use config()in your trait.'

Are you sure to have the good APP_ID ? Do you have many .env files depending of your app state ? (dev, prod, staging). If so, are you sur you put the FACEBOOK_APP_ID in the right .env file ?

Aug
02
1 month ago
Activity icon

Replied to Zsh-artisan Plugin Is Not Working

Hello,

First of all are you using oh-my-zsh ? And are you in a Laravel project ?

What do you mean by "i can't get it work" ?

Activity icon

Replied to Adding Sharable Link For Facebook Throws Error?

As a good practice you should have a file in config who uses env() and then use config()in your trait.'

Are you sure to have the good APP_ID ? Do you have many .env files depending of your app state ? (dev, prod, staging). If so, are you sur you put the FACEBOOK_APP_ID in the right .env file ?

Jul
31
1 month ago
Activity icon

Replied to How Would You Organize This Data (and Models) ?

This is what was in my mind actually to be honest. And I think it's a good way. Thanks for answering mate.

Activity icon

Replied to Laravel Telescope Not Showing Records

Hello,

Maybe you are in production mode on your application and telescope was installed with the --dev flag ?

Activity icon

Started a new Conversation How Would You Organize This Data (and Models) ?

Hello,

I am trying to make the best choice about a future project. I want to create an estimate, and invoice system on an existing application.

Let me try a short explanation. If it's not clear, tell me.

Here is my problem An estimate can be converted in one single invoice OR into many sub invoices (keeping track of the estimate they are coming from). An invoice can depend for ONE (and only one) estimate, but it can also be created without depending on any estimate.

Would love the way you will do that.

Thanks for the help.

Jun
21
2 months ago
Activity icon

Replied to Difference Between With() And Load()

Well this is pretty much what I understood reading the documentation. Thanks for answering !

Activity icon

Started a new Conversation Difference Between With() And Load()

Hi,

Here is a question I am asking myself. As the final result in terms of "data" is the same.

What's the difference ? And which should we use for what ?

Thanks.

May
22
3 months ago
May
21
3 months ago
Activity icon

Started a new Conversation Transition Trouble Using Laravel, VueJS & Tailwind

Hi,

I am trying to make a notification component and I can't understrand why the component is not having a transition on render.

Transition

<transition
        enter-active-class="transform ease-out duration-500 transition"
        leave-active-class="transition ease-in duration-500"
        enter-class="translate-y-2 opacity-0 sm:translate-y-0 sm:translate-x-2"
        enter-to-class="translate-y-0 opacity-100 sm:translate-x-0"
        leave-class="opacity-100"
        leave-to-class="opacity-0"
>

Blade

@if (session('status'))
      <notification
          title="Success"
          content="{{ session('status') }}"
      >
      </notification>
@endif

I made a short video if it can help : https://streamable.com/ou593o

Thanks guys !