Coco Coco - 1 month ago 6
PHP Question

Trigger controller function when link is pressed laravel

I am trying to trigger a controller function when a link is pressed.

So.., this is the HTML

<a class="hollow button primary" href="{{ route('hire.worker', ['id' => $id]) }}"><i class="fa fa-user-plus"></i> Hire as Worker</a>


This is the route:

Route::post('/profile/{id}', [
'as' => 'hire.worker',
'uses' => 'ProfileController@hire'
]);


And this is the controller:

public function hire($id)
{
$worker = New Worker;

$worker->workerID = $id;

$worker->save();
}


When I press the button, the page only refreshes, nothing is stored in the database, I also have few other routes so that may be the issue.

// Profile

Route::get('/profile/{id}', [
'as' => 'display.profile',
'uses' => 'ProfileController@index'
]);

Route::post('/profile/{id}', [
'as' => 'display.profile',
'uses' => 'ProfileController@store'
]);

Route::post('/profile/{id}', [
'as' => 'hire.worker',
'uses' => 'ProfileController@hire'
]);

Answer Source

Links use GET as the request method so Route::post is not correct. Create a new route like the one below and at the end of the controller method redirect to whatever page you originally wanted to go.

Route::get('/profile/link/{id}', [ 'as' => 'hire.worker', 'uses' => 'ProfileController@hire' ]);