Passing data to controller

First Method

In your controller (PostsController), edit one of the functions to pass a variable like this:

public function index($id)
{
    return "its working ".$id;
}

Edit your routes to accept the variable like so:

Route::get('/post/{id}', [PostsController::class, 'index']);

Second Method

Add your controller as a resource like this:

Route::resource('posts', PostsController::class);

Then type this into terminal to find which method accepts variables like this:

php artisan route:list

GET|HEAD        posts ........................................... posts.index › PostsController@index  
  POST            posts ........................................... posts.store › PostsController@store  
  GET|HEAD        posts/create .................................. posts.create › PostsController@create  
  GET|HEAD        posts/{post} ...................................... posts.show › PostsController@show  
  PUT|PATCH       posts/{post} .................................. posts.update › PostsController@update  
  DELETE          posts/{post} ................................ posts.destroy › PostsController@destroy  
  GET|HEAD        posts/{post}/edit ................................. posts.edit › PostsController@edit

Method show accepts a variable. So edit the show function in PostsController to display the variable on screen:

public function show($id)
{
    return "hi ".$id;
}

Leave a Reply

Your email address will not be published. Required fields are marked *