Home > Enterprise >  Why I cannot get the data from UserController to my user.blade.php file in Laravel 9?
Why I cannot get the data from UserController to my user.blade.php file in Laravel 9?

Time:09-03

Hello I need some help I am learning Laravel 9 and I have a problem, in the UserController I declare a public function show with a parameter $id and return it in user.blade.php file and call using template literals, my problem is I cannot get the data inside my function show.

This is the codein UserController file

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
 public function show($id){
  $data = array([
   "id" => $id,
   "name" => "John Doe",
   "age" => 22,
   "email" => "[email protected]"
  ]);
  return view("user", $data);
  }
}

web.php file

use App\Http\Controllers\UserController;
use Illuminate\Support\Facades\Route;

Route::get('/show/{id}', [UserController::class, 'show']);

user.blade.php file

{{ $data }}

it says

"ErrorException Undefined variable $data"

enter image description here

CodePudding user response:

The view function expects an associative array as second parameter (see docs). Each key of the array will have an equivalent variable in your blade view.

So you should respond either be :

return view("user", ['data' => $data]);

Or use PHP's compact helper

return view("user", compact('data'));

Or change your view so that it uses

{{ $id }}
{{ $name }}
{{ $age }}
{{ $email }}

Do whatever makes more sense to your use case

  • Related