0
0
Laravelframework~30 mins

Creating controllers with Artisan in Laravel - Try It Yourself

Choose your learning style9 modes available
Creating Controllers with Artisan
📖 Scenario: You are building a simple Laravel web application that manages books. To organize your code, you need to create controllers that handle requests related to books.
🎯 Goal: Learn how to create Laravel controllers using the Artisan command-line tool step-by-step.
📋 What You'll Learn
Use the Artisan command php artisan make:controller to create controllers
Create a controller named BookController
Add a method index inside the controller
Add a method show inside the controller that accepts a parameter $id
💡 Why This Matters
🌍 Real World
Controllers organize how your Laravel app responds to user requests, making your code clean and maintainable.
💼 Career
Knowing how to create and use controllers with Artisan is essential for Laravel developers to build scalable web applications.
Progress0 / 4 steps
1
Create the BookController using Artisan
Use the Artisan command php artisan make:controller BookController to create a new controller named BookController inside the app/Http/Controllers directory.
Laravel
Need a hint?

Open your terminal and type exactly php artisan make:controller BookController to create the controller.

2
Add an index method to BookController
Open the BookController.php file and add a public method named index that returns a simple string 'List of books'.
Laravel
Need a hint?

Inside the BookController class, write public function index() and return the string 'List of books'.

3
Add a show method with an ID parameter
Inside BookController, add a public method named show that accepts a parameter $id and returns the string 'Showing book with ID: ' . $id.
Laravel
Need a hint?

Define public function show($id) and return the string concatenating 'Showing book with ID: ' and $id.

4
Register routes for the controller methods
Open the routes/web.php file and add two routes: one GET route for /books that uses BookController@index, and one GET route for /books/{id} that uses BookController@show.
Laravel
Need a hint?

Use Route::get with the URL and controller method array syntax to register the routes.