Trying pass query from Repository or Model to Controller The best way to pass query from the model to Controller
Hello,
What's the repository for you with Laravel ? I know the repository with Symfony, but not with Laravel.
What I understand is you want to pass query from model to controller. Do you have any code example to show ?
I usually write my queries directly in the controller. Why do you need to pass a query from the model to a controller ?
Example
public function index()
{
$todos = Todo::all();
}
In my example, the index() function in the controller calls the all() query from the Todo model to retrieve all the todos from the database.
Tell me if it helps ;).
@paravecdesign You’re going to need to provide some more detail if you’re expecting a helpful answer.
like this function. this form my model
public function JoinToBrand(){
return $this->join('brands', 'complains.brand_id', '=', 'brands.id')->where('id',$id);
}
A lot of people put query in the controller and if they need to reuse it they of to copy and paste it but if it's in the model can just call it from the model that way is less code.
I'm coming from a Codeigniter background this easy to do
with eloquent it's easier to create a relationship, but if I wanted to do this with a join then I would probably use a scope
public function scopeJoinBrand(Builder $query, $id)
{
$query->join('brands', 'complains.brand_id', '=', 'brands.id')->where('id',$id);
}
then you can call it like
Model:: joinBrand($id)->get;
(watch your code style, conventionally, functions should start with lowercase)
Thank you tried it works great now used it anywhere in the application
The best way to pass query from the model to Controller
return $query;
Please sign in or create an account to participate in this conversation.