php - How should I structure my routes and controllers in Laravel?
Get the solution ↓↓↓I've got two buttons on my page, which each have different behaviours when clicked. Currently I've got my routes and controllers set up like this...
routes/web.php
Route::post('/users/button1clicked', 'UsersController@button1clicked');
Route::post('/users/button2clicked', 'UsersController@button2clicked');
app/http/controllers/UsersController.php
class UsersController extends Controller
{
public function button1clicked(Request $request){
//Do something
}
public function button2clicked(Request $request){
//Do something else
}
}
It works ... but I don't think I'm following the correct convention for my controller, because controllers should just have the standard actions (index, create, store, show, edit, update, destroy).
What would be a better way for me to structure this code?
Answer
Solution:
What does each button do? For example, if the button submits a form to 'save' an entity (say a 'Post' in a Blog app) then the form action can direct to thePostController@store
. If the button click is intended to show a html form to create an Post, then the it can lead toPostController@show
. The table below from the Laravel docs will help you.
Route definitions conventions
Please also see https://laravel.com/docs/7.x/controllers#restful-naming-resource-route-parameters.
If you are using ajax or axios to make async calls then you can call a function using button events (on-click for example) and that function can make a post (or any other async call to the relevant controller method (PostController@store
). Please let me know if you'd like an example.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: cannot access offset of type string on string
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.