Pass Request through Laravel Routes

Retrieving Request Data

We have previously learned that data passed through the URL or query string is stored by PHP in the $_GET variable. In Laravel, the request help function is used instead.

Route::get('/', function () {
  /* /?name=John */
  $name = request('name'); // John

  return view('home');
});

Sending Data to the View

An array of data may be passed to views. When doing this, the array of data must be an associative array, with key / value pairs. The array is added as the optional argument to the view helper function.

Route::get('/', function () {
  /* /?name=John */
  $name = request('name'); // John

  return view('home', ["name" => $name]);
});

Inside the view, each value can be access using its corresponding key. A variable with the same name as the key will be accessible in the view.

<html>
  <body>
    <h1>Hello, <?php echo $name; ?></h1>
  </body>
</html>

Of course, "echoing" data directly received from a user is an unsafe practice as could leave your site vulnerable to attack. That is why is better to use Blade to display the data.

<html>
  <body>
    <h1>Hello, {{ $name }}</h1>
  </body>
</html>