FrankClark
3 months ago

Laravel Eloquent Conditional BelongsTo relationship

Posted 3 months ago by FrankClark

Hello There,

I'm having to shoe-horn in an extra layer into my laravel project and trying to find an elegant solution to an issue. I have organisations, customers, and users. An organisation has many customers, a customer has many users. I have a middleware that redirects a user to select which customer they want to proceed with. This is then set as a cookie so that any subsequent requests return the data / entities for the customer.

It might make it easier to think of it as an ecommerce website with multiple stores. The user selects a store, and then as they proceed will only see products that belong to that store. In this analogy the store would be my 'customer'.

The difficulty lies in creating the user->customer() relationship. Dependent on the customer that's been set, i want to have a belongsTo relationship.

So, here are my current relationships that work :

#App\Organisation

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

    public function users(): HasManyThrough
    {
        return $this->hasManyThrough(CustomerUser::class, User::class);
    }

#App\Customer
  
    public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }

    public function organisation(): BelongsTo
    {
        return $this->belongsTo(Organisation::class);
    }
#App\User

    public function customers(): BelongsToMany
    {
        return $this->belongsToMany(Customer::class);
    }

I'm trying to do something like the following

#App\User

    public function customer(): BelongsTo
    {
        return $this->belongsTo(Customer::class)->where('uuid', $_COOKIE['selected_customer'])
    }

But this doesn't seem to want to play ball, various errors such as proc_open(): fork failed - Cannot allocate memory or if i do a firstWhere I get :

Return value of App\User::customer() must be an instance of Illuminate\Database\Eloquent\Relations\BelongsTo, null returned

It's possible this is just an issue with the customer_user pivot but i'm not sure. Any thoughts or different approaches would be greatly appreciated

Please sign in or create an account to participate in this conversation.