Home > database >  Laravel - Best practice for a lot of views & gets for forms
Laravel - Best practice for a lot of views & gets for forms

Time:01-07

I have a lot of forms for editing, moving, viewing, etc

Option 1: What I was thinking of doing:

Route::get('/submission/{action}/{id}', [UserSubmissionController::class, 'viewAction']);

And then my links would be:

{{ route('submission', ['action' => 'move', 'id' => $submission->id]) }}
{{ route('submission', ['action' => 'edit', 'id' => $submission->id]) }}

And my controller:

public function viewAction(Request $request)
{
$action = $request->action; //action to be performed (deposit, confirm, waitlist)
$id = $request->id;

/**
* MOVE VIEW - move someone to another place
*/
if($action=='move'){
//magic here
}

if($action=='edit'){
//magic here
}

}

Option 2: Another option:

Route::get('/submission/move/{id}', [UserSubmissionController::class, 'move'])->name('submission.move');
Route::get('/submission/edit/{id}', [UserSubmissionController::class, 'edit'])->name('submission.edit');

And then my links would be:

{{ route('submission.move', $submission->id) }}
{{ route('submission.edit', $submission->id) }}

And my controller:

public function move($id)
{
//magic here
}

public function edit($id)
{
//magic here
}

My reasoning for Option 1 is that I can have multiple form views under 1 route, which I do plan to add things like recording a payment, editing a payment, and other routes under the same UserSubmissionController and can use 1 route for all

But Option 2 might be the better way to go since it's probably more clear to understand, but then my web.php routes file is going to be really busy

CodePudding user response:

As @apokryfos mentioned in a comment, the best method is Option 2

As he states: Don't forget the single responsibility principle. Each function needs a single responsibility, the same can be extended to views, routes etc. For example, you have a controller responsible for submissions and a function responsible for editing said submissions.

So I'll be using Option #2. Thank you

CodePudding user response:

Remember the four functions that are considered necessary to implement a persistent storage application:

  • Create
  • Read
  • Update
  • Delete.... Each of them are different functions and so different routes (there are others like patch, index, etc.).

First create the main controller with resources:

php artisan make:controller MyController -r

This will create a full controller with all the main functions.

Then create the routes depending the type of request. Hope it helps.

  • Related