Laravel Route Wildcards

Sometimes you will need create a route that will accept a wildcard value, and then retrieve that value. This is where route parameters come. Route parameters allow you set a segment of the URI to be required or option and then capture that segment. Route parameters are always encased within {} braces and should consist of alphabetic characters, and may not contain a - character.

Route::get('/posts/{post}', function () {
  return view('post');
});

The route above will accept any value after /posts/ and direct to the post view. Now to capture that value, just add a parameter to the callback function. Route parameters are injected into route callback function based on their order.

Route::get('/posts/{post}', function ($post) {
  return view('post');
});

The parameter can then be used to inside of the callback function to make query to the database, pass it on to the view, or perform some other logic.

Route::get('/posts/{post}', function ($post) {
  $posts = [
    'post-1' => 'This is my first post';
    'post-2' => 'This is my second post';
  ];

  return view('post', [
    'post' => $posts[$post]
  ]);
});

Now, in the example above if the value passed through the URI is not one of the keys int he $posts array, the code will break. To fix this we can check if the key is in the array and if it is not then abort the script using the abort helper function.

Route::get('/posts/{post}', function ($post) {
  $posts = [
    'post-1' => 'This is my first post';
    'post-2' => 'This is my second post';
  ];

  if (!isset($posts[$post])) {
    abort(404, 'The post was not found.');
  }

  return view('post', [
    'post' => $posts[$post]
  ]);
});