I want to add a filter for all application queries to get the result by a specific year.
I am putting the current year into the session as shown below:
public function postLogin()
{
Session::put('currentYear', date("Y"));
}
I have many controllers in my application. I want any model's query result to filter by session year => Session::get('currentYear')
I have a lot of models; for example I have one route to view all users, teachers and students.
public function getList()
{
$data['students'] = User::where('group_id', '=', 4)->get();
return View::make('students.list', $data);
}
Can I put __construct
in BaseController to filter all app queries by Session::get('currentYear')
?
I would create a repository class with a method that provides the desired base query, such as
function getUserBaseQuery() {
return User::where('year', '=', Session::get('currentYear'));
}
Obviously make sure that currentYear
is set - and return this without running get()
just yet.
Then get this base query whenever you make a query, add more operations (limit, order, whatever) and run get()
.
This way you can access with your filter without doing some global potential damage and stay aware what filters are run by choosing that base query.
Does that make sense to you?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With