How to pass data from a controller to a view in Laravel?

In Laravel, you can pass data from a controller to a view using the with method or by returning an associative array containing the data.

  1. Using the with method: In your controller's method, you can use the with method to pass data to the view. The with method accepts an associative array where the keys are the variable names and the values are the data to be passed.

    public function index() { $data = ['name' => 'John Doe', 'age' => 30]; return view('welcome')->with($data); }

    In the above example, $data is an associative array containing the variables name and age. The with method is used to pass this data to the welcome view.

    In the view, you can access the passed data using the variable names specified:

    <h1>Welcome, {{ $name }}</h1> <p>Your age is {{ $age }}</p>

    The {{ $name }} and {{ $age }} will be replaced with the respective values passed from the controller.

  2. Returning an associative array: Alternatively, you can also pass data to the view by returning an associative array from the controller method. Laravel will automatically convert the array into a View instance.

    public function index() { $data = ['name' => 'John Doe', 'age' => 30]; return view('welcome', $data); }

    In this method, you pass the $data array directly as the second parameter to the view function. The keys of the associative array will be accessible as variables within the view.

    Accessing the data in the view remains the same as in the previous method:

    <h1>Welcome, {{ $name }}</h1> <p>Your age is {{ $age }}</p>

Both methods accomplish the same task of passing data from the controller to the view. Choose whichever method feels more convenient for your use case.