Search code examples
phplaraveleloquenteloquent-relationship

How can i get data by using "with" laravel relationship function by a condtion?


this is my table => table image

//This is my controller
public function listUserStripeActionableRequests(Request $request) {
        return $model = UserRequest::whereNull('deleted_at')
            ->with('oldPackage')
            ->get();
}


userRequest.php

public function oldPackage() {
    return $this->hasOne(Package::class, 'id', 'old_package_id');
}

I need to get data according to package_type in the table if package_type == 1 then i need to get data from Package::class, if package_type == 2 then from AddOnsPackage::class then model function like :- $this->hasOne(AddOnsPackage::class, 'id', 'old_package_id');

How can i use single query to get data accordingly?


Solution

  • You can try

    class UserRequest extends Model
    {
    
    
        public function package()
        {
            return $this->hasOne(Package::class, 'id', 'old_package_id');
        }
    
        public function addon()
        {
            return $this->hasOne(AddonPackage::class, 'type', 'add_on_type');
        }
    
        public static function sorted()
        {
            return static::whereNull('deleted_at')
                ->get()
                ->map(function ($record) {
                    if ($record->package_type === 1) {
                        $record->load('package');
                    } elseif ($record->package_type === 2) {
                        $record->load('addon');
                    }
    
                    return $record;
                });
        }
    }
    

    Then in the controller you can do

    public function listUserStripeActionableRequests(Request $request)
    {
        return $model = UserRequest::sorted();
    }