Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

paravecdesign's avatar

Trying pass query from Repository or Model to Controller

The best way to pass query from the model to Controller

0 likes
6 replies
vincent15000's avatar

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's avatar

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

Snapey's avatar
Snapey
Best Answer
Level 122

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)

1 like
paravecdesign's avatar

Thank you tried it works great now used it anywhere in the application

Snapey's avatar

The best way to pass query from the model to Controller

return $query;
1 like

Please or to participate in this conversation.