Laravel Controllers
A controller is a PHP class that groups the actions for a set of routes. It keeps route files short and puts related logic in one place.
Make a controller
Artisan creates the controller class for you.
php artisan make:controller BookControllerAdd an action
A controller groups related actions in one class.
public function index()
{
return 'Books: Dune, Foundation';
}Point a route at the action
The route names the controller class and the action.
use App\Http\Controllers\BookController;
Route::get('/books', [BookController::class, 'index']);Example
use App\Http\Controllers\BookController;
Route::get('/books', [BookController::class, 'index']);
class BookController extends Controller
{
public function index()
{
return 'Books: Dune, Foundation';
}
}Key points
- Controller: a PHP class that holds the logic for a group of routes.
- Action: a method in a controller that handles one request.
- Use a controller to move logic out of a route closure.
- Use the array form [BookController::class, 'index'] to point a route at an action.
In this example, the route sends GET requests for /books to the index action of BookController. The controller class holds that action. The action returns a plain text list of books. A visit to /books shows the list.
Note
Artisan makes the controller in app/Http/Controllers.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a controller do?