2

I'm trying to figure out how to run a raw query from within a model.

Let's say I have a model FOO and this model has a method which does cross table joints, grouping a bit more logic and is way to heavy for Eloquent ORM.

What I want is the ability to call this method from controller, like so:

Model::method()->get()

To be honest, any other call is fine as long as I can keep the raw query inside the model and call it from controller.

What I want to avoid is to have DB::raw() and the query itself in controller.

rock3t
  • 2,193
  • 2
  • 19
  • 24

2 Answers2

2

If you add static to the method you can call it directly from the model Model::method() else you should use a model instance $modelInstance->method() :

So in your model :

public static function method(){
    // your query
    return queryBuilder;
}

That's all, and in the controller you can do it like you want :

Model::method()->get()
Maraboc
  • 10,550
  • 3
  • 37
  • 48
  • Try this link: https://stackoverflow.com/questions/22925451/how-can-i-query-raw-via-eloquent – Kannan K Nov 02 '17 at 11:33
  • Thanks Maraboc and Kanna, that worked. Question: is static necessary for model methods? Is this how Eloquent works? – rock3t Nov 02 '17 at 11:39
  • If you add `static` to the method you can call it directly from the model `Model::method()` else you should use a model instance `$modelInstance->method()` – Maraboc Nov 02 '17 at 11:41
0

The efficient way is to do it with laravel Query scope

public static function scopeFoo($query)
{
    return $query->whereStatus(...);
}

and in controller

Model::Foo()->get();
Bilal Maqsood
  • 1,163
  • 3
  • 15
  • 43