Laravel frame database query inside model function

I am new to Laravel. I want to make some custom functions in models related to a database query.

Class A Extends Controller{
  public function view(){
    B::get_user();
  }
}

Class B Extends Model{
  protected $table = "user";

  public function get_user(){
    //Here is my database query
  }
}

How can I use the database query in the get_user () function? I know this method:

B::table('user')->get();
+4
source share
1 answer

You can define a query scopesto add a query to a model as:

public function scopeUser($query)
{
    return $query->where('some_field', 'some_value');
}

Then you can use it in your controller like:

B::user()->get();

Docs

+3
source

Source: https://habr.com/ru/post/1664815/


All Articles