Search code examples
laravelparametersbuilder

Undefined variable but it's already declared Laravel


I'm having some problems with my website.

Lately, I've been working on a "filtering page" where the user selects/writes a character, and then it searches X data with that character (From A-Z and 0-9). The character can be optional.

This is my getAffiliates function:

public static function getAffiliates($community_id, $character) {
    if (!empty($character)) {
        $character = strval($character);
        if (is_numeric($character)) {
            $users = UserCommunity::with('user')->where('community_id', $community_id)->whereHas('user', function($q) {
                $q->where('name', 'regexp', '^[0-9]+');
            })->get();
        } else {
            $users = UserCommunity::with('user')->where('community_id', $community_id)->whereHas('user', function($q) {
                $q->where('name', 'like', $character.'%');
            })->get();
        }
    } else {
        $users = UserCommunity::with('user')->where('community_id', $community_id)->take(50)->get();
    }
    return $users;
}

What this code does is, given an X $community_id, and an X $character, it will determine whether $character is integer or not. Then, it will do a query to the database and it will retrieve a collection conditioned on the given parameters. Basically, the query looks for a value where the initial character equals my $character parameter.

What I don't know is, why am I getting the "undefined variable $character" error?

enter image description here

My controller's code is this (Notice the parameter can be null):

enter image description here

Can someone explain what is actually wrong?

UPDATE With the Full Trace Error

enter image description here


Solution

  • You have to use variable top of where has function. to access it.

    public static function getAffiliates($community_id, $character) {
    if (!empty($character)) {
        $character = strval($character);
        if (is_numeric($character)) {
            $users = UserCommunity::with('user')->where('community_id', $community_id)->whereHas('user', function($q) {
                $q->where('name', 'regexp', '^[0-9]+');
            })->get();
        } else {
            $users = UserCommunity::with('user')->where('community_id', $community_id)->whereHas('user', function($q) use ($character) {
                $q->where('name', 'like', $character.'%');
            })->get();
        }
    } else {
        $users = UserCommunity::with('user')->where('community_id', $community_id)->take(50)->get();
    }
    return $users;
    }