skip to Main Content

So, I have a "noms" relation in provider model, i want, if role is manager, to return all models from noms.

I have this:

     {
         return $this->hasMany(Nom::class);
     }

want something like:

     {
         if($this->role === "manager"){
             return Nom::all
         }
         return $this->hasMany(Nom::class);
     }

2

Answers


  1. The relationship:

    use IlluminateDatabaseEloquentRelationsHasMany;
    
    public function noms(): HasMany
    {
        return $this->hasMany(Nom::class);
    }
    

    It should be that way, no more, no less. Extra logics should be the responsibility of a different place, such as an action controller.

    class NomsController extends Controller
    {
        public function index()
        {
            if ($this->role === "manager") {
                 return Nom::all();
             }
    
             return auth()->user()->noms()->get();
        }
    }
    
    Login or Signup to reply.
  2. You could do something like this:

    User model class:

    <?php
    
    class User extends Model
    {
        public function noms()
        {
            return $this->hasMany(Nom::class);
        }
    
        public function allNoms()
        {
            if ($this->role === 'manager') {
                return Nom::query();
            }
    
            return $this->noms();
        }
    }
    

    Ps: don’t forget to import necessary models in User model class like Nom class.

    Controller:

    class ListingController extends Controller
    {
        public function index()
        {
           return auth()->user()->allNoms()->get();
        }
    }
    

    Why this approach?

    1. It’ll be easier to filter data where ever you’ll need.
    2. Easier to maintain code and make changes in logic from one places i.e. User model class.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search