David Tunnell
David Tunnell

Reputation: 7542

Variable passed from controller doesn't exist

I am trying to pass a variable with database information from a controller to the view.

public function getPrivateCount($term) {
    $data["private_count"] = '0';

    $privateCount = \DB::table("users")->where("username", "LIKE", "%". $term . "%")
                               ->orWhere("firstName", "LIKE", "%". $term . "%")
                               ->orWhere("lastName", "LIKE", "%". $term . "%")
                               ->orWhere("displayName", "LIKE", "%". $term . "%")
                               ->where("private", true)
                               ->count();

    if($privateCount){  
        $data['private_count'] = $privateCount;
    }

    return view('search.hl')->with($data);
}

And calling it on the view:

<div>Testing: [[ $private_count ]]</div>

But I am getting that the variable doesn't exist:

Undefined variable: private_count (View: /var/www/build/resources/views/search/hl.blade.php)

Why is this happening and what am I doing wrong?

Upvotes: 0

Views: 60

Answers (2)

Tim van Uum
Tim van Uum

Reputation: 1903

You could also use:

return view('search.hl', compact('data'));

This can be extended like this if you want to pass more than one variable:

return view('search.hl', compact('data', 'data2'));

Little bit cleaner if you ask me. Laravel will detect what you want to do. If there is a variable named data it will be passed to the view with the same name.

Upvotes: 0

Mina Abadir
Mina Abadir

Reputation: 2981

Two things to take into consideration.

First pass the data correctly

return view('search.hl')->with(['data' => $data]);

Then read your variables:

<div>Testing: {{ $data['private_count'] }}</div>

Upvotes: 3

Related Questions