0

I try to show variable from the controller to blade in laravel but the result is "Undefined Variable"

UserController.php

 public function user(){
    $people = ['Edwin','James','Rock','Peter','Maria'];
    return view('user', compact('people'));
}

Web.php

Route::get('/user', function (){
return view('user');

});

user.blade.php

 @if(count(array($people)))
   <ul>
   @foreach($people as $person)
       <li>{{$person}}</li>
   @endforeach
   </ul> @endif

I really appreciate your answer.

2
  • your route should be pointing to your controller method since that is where you are actually passing data to the view and this view requires that data Commented Mar 5, 2021 at 9:10
  • Route::get('/user',[\App\Http\Controllers\UserController::class,'user']) Commented Mar 5, 2021 at 9:12

2 Answers 2

1

change your web.php file

use App\Http\Controllers\UserController;

Route::get('/user', [UserController::class, 'user']);
Sign up to request clarification or add additional context in comments.

Comments

0

In route

Route::get('/user', function (){ return view('user');

That means you are directly loading the view , It will not go to controller . Instead use

Route::get('/user', 'UserController@user');

This will go to user method in usercontroller class

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.