Code Demon Code Demon - 2 months ago 10
PHP Question

Filter specific column, if matched then get the record

I'm on Laravel 5.2. How to filter specific column if matched the given criteria on the query?

for example I have a record like


column[id] => '1', column[username] => 'id_45820', column[contents] =>
'test', column[to] => 'admin,id_45820,user', column[created_at] => '',
column[updated_at] => ''


and I have 2 variables as a criteria

$role = 'user';
$username = 'id_45820';


Now I want to do like filter the 'to' column using the '$role' and '$username' variable and if either the '$role' or '$username' or both is match to the contents of 'to' column (separated by comma) then pull that record, is that possible?

$q = notifications::where(function($query){
//I just don't know how to do it. Help please?
})->get();

Answer

If I'm understanding your question correctly then:

$role = 'user';
$username = 'id_45820';

$q = notifications::where(function($query) use($role, $username) {
    $query->where('to', 'like', "%{$role}%")
          ->orWhere('to', 'like', "%{$username%}");
})->get();

As you said you want to check if either or both exist then you just need to check if either exists.

Hope this helps!