Laravel - Relationships - Dynamic Relationships

You may use the resolveRelationUsing method to define relations between Eloquent models at runtime. While not typically recommended for normal application development, this may occasionally be useful when developing Laravel packages.

The resolveRelationUsing method accepts the desired relationship name as its first argument. The second argument passed to the method should be a closure that accepts the model instance and returns a valid Eloquent relationship definition. Typically, you should configure dynamic relationships within the boot method of a service provider:

    use App\Models\Order;
    use App\Models\Customer;
    Order::resolveRelationUsing('customer', function ($orderModel) {
        return $orderModel->belongsTo(Customer::class, 'customer_id');
When defining dynamic relationships, always provide explicit key name arguments to the Eloquent relationship methods.