Loading Relationships Outside of Eloquent Models in Laravel



Somedays ago i was trying to relate two models outside of the model class because I am developing a package. I found out that the resolveRelationUsing() method is appropriate for this kind of situation and it does works good.

Suppose what we do when we create a relationship in laravel? For instance, if we want to define a “one-to-one” relationship between Order and Customer model where the Order belongs to the User, you can define it like so.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    /**
     * Get the customer that owns the order.
     */
    public function user()
    {
        return $this->belongsTo('App\Customer');
    }
}

 

This is one way to define relationships. But there’s another way in Eloquent using which you can define relationships on-the-fly outside of the models. Using resolveRelationUsing built in method.

 

Laravel provides this handy method called resolveRelationUsing which can be used to define relations between Eloquent models outside of model like so.

 

Define same relationship like before, see the below code example

use App\Order;
use App\Customer;

Order::resolveRelationUsing('customer', function ($orderModel) {
    return $orderModel->belongsTo(Customer::class, 'customer_id');
});

 

Recommended : Way to Load Custom JSON Files Into Laravel's Config

 

Hope it can help you.

 

Facebook Github
A web enthusiastic, self-motivated Full-Stack Web Developer from Dhaka, Bangladesh with experience in developing applications using Laravel Vue and React Js Application.