Callback / anonymous functions

Posted 5 months ago by fabricecw

Hi

I try to understand callback / anonymous function but it still confuses me a lot... I tried to write callback functions for operational filters:

public function scopeSearch($query)
    {
        $like = function($value, $field) use($query) {
            $test = $value;
            $query->where($field, 'like', '%' . $test);
        };

        $match = function($value, $field) use($query) {
            $query->where($field, $value);
        };

        $searchable = [
            [
                'field' => 'client_reference',
                'operator' => 'like',
                'filter' => request()->filterClientReference
            ],

            [
                'field' => 'article_number',
                'operator' => 'match',
                'filter' => request()->filterArticleNumber
            ]
        ];

        foreach($searchable as $search) {
            if($search['filter']) {
                // Here it should call the right function depending on the operator... Hardcoded example:
        $like($search['filter'], $search['field']); // But this also isn't working...
            }
        }

        return $query;
    }

Maybe I'm on a totally wrong way.

Please sign in or create an account to participate in this conversation.