Is it possible to use an Accessor for comparison in Laravel 4, for example:
class User extends Eloquent {
// define Accessor
public function getSpecialNameAttribute()
{
return 'Joda';
}
}
$User = User::where('gender','=','male')->where('specialName','=','Joda');
?
Yes, you can use it to filter query results:
User
::where('gender','=','male')
->get()
->filter(function($item) {
return $item->specialName === 'Luke';
});
(!) Note that filtering will be applied after quering DB, so in case of big data this solution will have performance issues.
For more details I've googled for you this Collections tutorial.
Also I suggest query scopes may be useful to complete your task in best way.
No, you cannot use it this way.
When you use:
$user = User::where('gender','=','male')->where('specialName','=','Joda')->get();
you will try to compare specialName
column in database with Joda
string.
You cannot use accessor here, because accessor may be very complicated and then Laravel would need to take all data from table in database (for example 100000 records) and calculate accessors for all of them to get for you only records you need (for example 1 record).
You can use accessor only when you have object instance, and you won't be able to use it when querying database.
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