query as a function inside model for reusing Hi Everyone,
I wanted to use a common query in multiple controllers, so I decided to put it in a model as function.
But initially I used as simple function, but it didn't work as it doesn't work without creating object in controller.
Then I used scope like below:
\\Model - Section
public function scopeAllSections() {
return $this->get()->pluck('sname', íd');
}
\\Controller
$sections = Section::AllSections();
It is doing what I need but I want to ask - Is the above approach fine?
Should we do it often to avoid writing queries multiple times in different controllers?
And for complex queries ? using scopes?
Thanks
@ramniksingh could you share your first attempt using a simple function before using scope?
Hi @neilstee
I was wrongly trying like below :
// Model - Section
public function allSections() {
return $this->get()->pluck('sname', íd');
}
// Controller
$sections = Section::allSections();
or
$sections = Section->allSections();
@ramniksingh because you are calling the function statically, you could do something like this:
// Model
public static function allSections() {
return self::get()->pluck('sname', 'id');
}
// Controller
Section::allSections();
Hi @ramniksingh first of all, query builder have pluck method, so, you can just call in controller
$sections = Section::pluck('sname', 'id');
now your questions
No. Scopes are for scoping query, not returning the result, so, your way to use scopes is wrong
Sure. But for simple queries like Section::pluck('sname', 'id') - it's ok to repeat
a. You can specify methods in your Model directly (if is small application)
b. You can use Repository layer
c. You can create separated Query class
Thanks @silencebringer
Actually using pluck is just an example, I am asking for multiple types of database queries to achieve DRY.
Thanks I get some of your points.
3.a. How to call the method directly as I couldn't run method without creating the object. Will it be okay to write queries in those methods?
3.c. Separate query class will includes methods so why not we add methods in model itself ? Can you elaborate this point please.
@ramniksingh
3.a. You can inject Model via __construct, for example
//controller
protected Section $section;
public function __construct(Section $section)
{
$this->section = $section;
}
public function yourMethod()
{
$sections = $this->section->yourComplexQuery();
}
3.b. For a large projects you Model will grows extremely quick if you'll keep everything (include all the methods) in your model. This way it make sence to move queries in separated layer (repository or queries class)
Thanks. What should be the approach in calling functions in controller ?
A static method vs forcing to create object via constructor in controller ?
I prefer to use dependency injections (it means - via contructor)
Please sign in or create an account to participate in this conversation.