Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

laravel
controllers
communitycreator

How can we create a Laravel controller in a custom namespace

Zubair Idris Aweda

In Laravel, controllers are created using the artisan make command. They are created in the app/Http/Controllers directory. They are also automatically namespace, using this pathname.

Hence, we will create a PostController like this:

PHP artisan make:controller PostController

We will create a new file called PostController.php at app/Http/Controllers. Sometimes, for organizational purposes, we may want to have a bunch of controllers grouped in a folder under the same namespace.

To create a controller with a custom namespace, we will add the custom folder name before the controller name, with a forward slash (/) between them. For example, to create a PostController in a Users directory, we will run the following code:

PHP artisan make:controller Users/PostController

This creates the PostController.php file in the app/Http/Controllers/Users folder. This folder is created automatically if it doesn’t already exist. The controller is also automatically namespace like so:

namespace App\Http\Controllers\Users;

RELATED TAGS

laravel
controllers
communitycreator
RELATED COURSES

View all Courses

Keep Exploring