Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter all query results in laravel 4.2 app by year

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')?

like image 863
Maged Hamid Avatar asked Oct 18 '22 12:10

Maged Hamid


1 Answers

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?

like image 200
Florian Arndt Avatar answered Oct 21 '22 03:10

Florian Arndt