0
0
Laravelframework~5 mins

Creating controllers with Artisan in Laravel

Choose your learning style9 modes available
Introduction

Controllers help organize your app's logic. Artisan makes creating them fast and easy.

When you want to handle user requests in a clean way.
When you need to group related actions like showing, creating, or deleting data.
When building a new feature that needs its own set of functions.
When you want to follow Laravel's recommended structure for apps.
When you want to quickly generate controller files without writing boilerplate code.
Syntax
Laravel
php artisan make:controller ControllerName
Replace ControllerName with your desired controller name.
You can add options like --resource to create a controller with common methods.
Examples
Creates a simple controller named UserController.
Laravel
php artisan make:controller UserController
Creates a controller with methods for common actions like index, create, store, show, edit, update, and destroy.
Laravel
php artisan make:controller ProductController --resource
Creates a controller inside the Admin folder to organize admin-related controllers.
Laravel
php artisan make:controller Admin/DashboardController
Sample Program

This is a simple controller named ArticleController with two methods: index to list articles and show to display a single article by ID.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ArticleController extends Controller
{
    public function index()
    {
        return 'List of articles';
    }

    public function show($id)
    {
        return "Showing article with ID: $id";
    }
}
OutputSuccess
Important Notes

Controllers created with Artisan are saved in app/Http/Controllers by default.

Use the --resource flag to quickly scaffold common CRUD methods.

Remember to register your controller routes in routes/web.php or routes/api.php to make them accessible.

Summary

Artisan helps you create controllers quickly with simple commands.

Controllers organize your app's logic and handle user requests.

Use options like --resource to generate common methods automatically.