Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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" => "jhondoe@gmail.com"
  ]);
  return view("user", $data);
  }
}

web.php file

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading