Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4: How to use an Accessor in a where-clause

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

?

like image 680
Olli Avatar asked Dec 02 '14 17:12

Olli


2 Answers

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.

like image 140
Nayjest Avatar answered Nov 15 '22 07:11

Nayjest


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.

like image 34
Marcin Nabiałek Avatar answered Nov 15 '22 06:11

Marcin Nabiałek