0

I am working over a project. I have required some basic values in different routes. e.g. show the list of users, locations, products in different pages/routes. So I wanted to create a common method for these like where i want to show list of users I will call the method for user and pass this list to view.

I've tried the following method:

$usersArr = User::where('loc_id',session('organization'))
  ->where('status', '!=', 'Deleted')
  ->orderBy('id', 'desc')
  ->lists('username', 'id');

So i wanted to know which is best place to define these type of methods. Should i define this in Model,Controller or create some type of common functions?

maxhb
  • 8,554
  • 9
  • 29
  • 53
Kapil Verma
  • 178
  • 3
  • 17

2 Answers2

0

Create CommonModel , and define function there ..and cal that model

shalini
  • 1,291
  • 11
  • 13
0

That is a common question. I think that the most popular approach is to create a Repository class for that (for example with a name UserRepository). You can define a the repo method like this:

class UserRepository{

    public static function getOrganizationActiveUsers($organization){
        return User::where('loc_id', $organization)
              ->where('status', '!=', 'Deleted')
              ->orderBy('id', 'desc')
              ->lists('username', 'id');
    }

}

and then use this method in other classes like:

$variable = UserRepository::getOrganizationActiveUsers(session('organization'));

This way your class would not have to know that some kind of session exists. That is usefull if you cannot access session when accessing specific API for example.

Also you can inject your repository in your controller (or any other class) this way:

<?php 


use Namespace/SubnameSpace/UserRepository; // this is very important, to specify the correct full classname with namespace; 


class SomeController
{


    __construct(UserRepository $userRepo) 
    {
        $this->userRepo = $userRepo;
    }

    public  function showUserOrganizationUsers()
    {
        $users = $this->userRepo->getOrganizationActiveUsers(session('organization'));

        return $users;
    }

}

This is also convenient, in case you for example want to inject a completely different class but with the same methods. (if you want to dive deeper in dependency injection read about interfaces and Laravel DI container, which provide a lot of convenience when injecting dependencies. What I have shown above is just a straightforward way).

By the way, you can check some sample codebases with different approaches here: Awesome Laravel on GitHub

naneri
  • 3,771
  • 2
  • 29
  • 53