0

Trying to integrate "if condition" inside model relation. But It doesnt work.

    $customer_index = Customer::where('firm_id', $firm_id)
    ->with(['company', 'tires', 'vehicles'])
    ->withCount(['tires', 'vehicles'])
    ->orderBy('id', 'desc');

my Customer.php model

public function vehicles()
{
    if(isset($this->company->is_fleet)){
        return $this->hasMany('App\Models\CustomerVehicle', 'fleet_id', 'company_id');
    }
    return $this->hasMany('App\Models\CustomerVehicle');
}
2
  • 1
    you cant do that with eager loading as the relation method is called on a new instance (that has no attributes) Commented Nov 27, 2020 at 15:34
  • 1
    Does this answer your question? How to setup conditional relationship on Eloquent Commented Nov 27, 2020 at 15:50

1 Answer 1

1

Can't do that sort of conditional with eager loading.

To maintain all benefits of eloquent you should separate the relations

public function company_vehicles()
{
    return $this->hasMany(CustomerVehicle::class, 'fleet_id', 'company_id');
}

public function customer_vehicles()
{
    return $this->hasMany(CustomerVehicle::class);
}

//A scope to tuck away the eager loads
public function scopeVehicles($query)
{
   return $query->with(['company_vehicles', 'customer_vehicles']);
}

You asked in the comment to club the relations in one key vehicles. This is how you can try


User::vehicles()->get()->map(function($user){

    if(!empty($user->customer_vehicles)){
      
      $user->vehicles = $user->customer_vehicles;
      unset($user->customer_vehicles);
      unset($user->company_vehicles);
      
    } else if(!empty($user->company_vehicles)) {
      
      $user->vehicles = $user->company_vehicles;
      unset($user->customer_vehicles);
      unset($user->company_vehicles);
      
    }
  
  return $user;
});
Sign up to request clarification or add additional context in comments.

8 Comments

Thank you. but It gives: Call to undefined method Illuminate\Database\Eloquent\Builder::getRelated() error.
For which line does it give the error can you find in the stacktrace. Are you importing the use statement for the CustomerVehicle
Call to undefined method Illuminate\Database\Eloquent\Builder::getRelated(); vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php:50
What I mean is look in the stacktrace to find which line of your written code the error occurs not the framework components in the stack
ok it returns 2 list. customer_vehicles and company_vehicles. isn't there anyway to return them on same key? example: vehicles: [{ bla bla bla}]. now, it gives like customer_vehicles: [{bla bla}], company_vehicles: [{ bla bla}]
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.