Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel orm database query inside model function

I am new in Laravel. I want to make some custom functions in models which is related to 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 database query in get_user() function? I know this method:

B::table('user')->get();
like image 276
Vam Avatar asked Dec 25 '16 06:12

Vam


1 Answers

You can define query scopes for adding the query on the model as:

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

Then you can use it in you controller as:

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

Docs

like image 97
Amit Gupta Avatar answered Sep 20 '22 14:09

Amit Gupta