Reputation: 1160
I'm working on a Laravel project, and I made a simple CRUD system, but I have a small problem
to generate the URL system in my project, I made a Route::macro
and add it to AppServiceProvider
:
Route::macro('crud', function () {
Route::group([
], function () {
// Route::resource('', 'CrudController');
Route::get('{model}', 'CrudController@index');
Route::get('{model}/create', 'CrudController@create');
Route::post('{model}', 'CrudController@store'); /** << post **/
Route::get('{model}/{id}', 'CrudController@show');
Route::get('{model}/{id}/edit', 'CrudController@edit');
Route::match(['PUT', 'PATCH'],'{model}/{id}', 'CrudController@update'); /** << post **/
Route::delete('{model}/{id}', 'CrudController@destroy'); /** << post **/
});
});
this works great so far, but the issue is I need to use ->name()
with it, and adding the $model
parameter to it!
Route::get('{model}', 'CrudController@index')->name('{model}.index');
is it possible?, Thanks in advance
Upvotes: 2
Views: 783
Reputation: 373
You can get all models names and loop through them and add the model name to the route name prefix at runtime
loop (model in models)
Route::get("{model}","Atcion")->name("{model}.index")
endloop
I hope my answare helps you in your project
Upvotes: 1
Reputation: 2101
Here in this example you can loop over of some numbers and dynamically create some routes:
for ($i = 0; $i < 5; $i++) {
Route::get('test/' . $i, 'Controller@test_' . $i)->name('test.' . $i);
}
You can check that all added routes with "php artisan route:list". I don't recommend you to do that, but for your case you can somewhere in routes.php define array like this, and loop over on that:
$models = ['user', 'owner', 'admin'];
foreach ($models as $model) {
Route::get($model, 'CrudController@index')->name($model . '.index');
}
Or you can define that array in configs (for example in "config/app.php") like:
'models' => ['user', 'owner', 'admin'];
And in routes.php you can just retrieve that with this (don't forget to run "php artisan config:cache" after changing app.php):
$models = config('app.models');
// foreach loop
Upvotes: 1