Reputation: 37
I need to use below code in a lot of route of my laravel 5 application so first: how to make it a simple function? second: how to cache result of this query for at least 10 minutes
$devices = \Auth::user()->devices()->whereNumber($number)->firstOrFail();
Upvotes: 1
Views: 1143
Reputation: 1959
About your first question ,you could add another method to your User
class like this -
public function MyFuncName($number){
return $this->devices()->whereNumber($number)->firstOrFail();
}
if you want it to be cached for each user you could do it like this in Laravel 4 -
public function MyFuncName($number){
return $this->devices()->whereNumber($number)->remember(10)->firstOrFail();
}
But in Laravel 5 you should do this like this:
public function myFuncName($number){
return \Cache::remember('user_device_' . $number, 10, function() use ($number)
{
return $this->devices()->whereNumber($number)->firstOrFail();
});
}
To call the function you would do
$devices = \Auth::user()->MyFuncName($number)
Forgot to mention that you must verify the user before as if \Auth::user() return null/false [user is not authenticated] then it will throw you an exception that this method doesnt exist
Upvotes: 2