John Davidson

php - Controller and routes - Laravel 8

0 comments
Message:


i would know how i can insert all my controllers in routes without repeat use.... use...


example:


<?php use Illuminate\Support\Facades\Route;
use App\Http\Controllers\DB;
use App\Http\Controllers\DB1;
use App\Http\Controllers\DB2;
use App\Http\Controllers\DB3;
use App\Http\Controllers\DB4;
use App\Http\Controllers\DB5;
use App\Http\Controllers\DB6;
etc.....
Route::get('/', function () {
return view('welcome');
});

How can i insert a lot of controllers in only one time??
Thanks a lot.


P.S. DB1,DB2,etcc are example XD



My Answer:
You can use Laravel's resourceful routing feature to define routes for all your controllers without repeating the `use` statement for each controller. Here's an example of how you can achieve this:

1. Define a resource route for your controllers in your `routes/web.php` file:

php
use App\Http\Controllers\HomeController;
use App\Http\Controllers\AboutController;
use App\Http\Controllers\ContactController;

Route::resources([
'home' => HomeController::class,
'about' => AboutController::class,
'contact' => ContactController::class,
]);


This will automatically generate the following routes for your controllers:

- `GET /home`
- `GET /home/create`
- `POST /home`
- `GET /home/{id}`
- `GET /home/{id}/edit`
- `PUT/PATCH /home/{id}`
- `DELETE /home/{id}`

- `GET /about`
- `GET /about/create`
- `POST /about`
- `GET /about/{id}`
- `GET /about/{id}/edit`
- `PUT/PATCH /about/{id}`
- `DELETE /about/{id}`

- `GET /contact`
- `GET /contact/create`
- `POST /contact`
- `GET /contact/{id}`
- `GET /contact/{id}/edit`
- `PUT/PATCH /contact/{id}`
- `DELETE /contact/{id}`

2. You can also define custom routes for your controllers by using the `Route::get`, `Route::post`, `Route::put`, `Route::patch`, and `Route::delete` methods:

php
Route::get('/custom-route', [HomeController::class, 'customMethod']);


This will create a `GET /custom-route` route that will call the `customMethod` method in the `HomeController` controller.

By using resourceful routing and custom routes, you can define all your controller routes in a single file without repeating the `use` statement for each controller.

Rate this post

5 of 5 based on 7461 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us