AppDividend
Latest Code Tutorials

How to Create Custom Namespace in Laravel 8

0

Laravel namespaces are defined as a class of elements in which each element has a unique name to the associated class. The namespaces may be shared with elements in other classes. Let’s understand why we need a namespace in Laravel.

Why we need a namespace

PHP does not allow you to have two classes with the same name at a global level. This idea may sound good, but it instantly becomes a problem when you import third-party libraries, and the name collision occurs between those libraries.

This collision occurs specifically when you are using third-party packages because the packages can contain similar class names.

To solve this collision issue, the concept of “namespaces” was added in PHP 5.3. As your application grows, the namespaces become essential to group the code logically, and namespace keeps the code separate from other code.

How to define namespace in Laravel 8

To define a namespace in Laravel, use the “namespace” keyword followed by a path identifier.

<?php

namespace AppStocks;

/**
* brief Handle all Stock Option preferences for a normal user of the application
*/
class StockOptions
{
    /**
     * Given a user object, retrieve all associated options for the user and return them in
     * an array and key-value pairs.
     */
    public function getOptions(User $user)
    {
      ...
    }
}

The “namespace” keyword should not have any other keywords, but comments are OK and needed for most documentation generators.

Here the namespace is already created; we just used it, but how to create a custom namespace? Well, let’s dive into that.

Install the Laravel 8 and if you don’t know how to do that, check out my Laravel 8 tutorial.

How to Create Custom Namespace in Laravel 8

To create a custom namespace in Laravel 8, create a separate controller with forward-slash(/) using the following command.

php artisan make:controller Admin/UserController --resource --model=User

If you closely look at the above command, you can see that we have used the forward slash to separate our namespace Admin. This gives us the ability to create a custom namespace, and it is easier for us to design the project.

The UserController will be created inside the Admin directory inside the app >> Http >> Controllers folder.

Also, we have attached the User.php model to the UserController.

If you open the UserController.php file, then it looks like below.

<?php

// UserController.php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function show(User $user)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function edit(User $user)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, User $user)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\User  $user
     * @return \Illuminate\Http\Response
     */
    public function destroy(User $user)
    {
        //
    }
}

You can see that our new namespace is App\Http\Controllers\Admin;

That means if in the future, we have to create a functionality related to the Admin module, then we will create another controller under the Admin namespace.

Other examples like if you are creating an API for a mobile application, then you should make an API namespace and all the controllers will be included under the API namespace.

How does routing work under a new namespace?

To write Admin namespace routes, open routes >> web.php file and add the following code.

// web.php

Route::namespace('Admin')->group(function() {
    Route::resource('users', 'UserController');
});

You can see that we are explicitly defining the routes for the Admin namespace. 

Under the Admin namespace, we are defining all the admin related routes.

Now, go to the UserController’s index() method and add the following code.

// UserController.php

public function index()
{
        return 'Yes!! Admin namespace is working successfully';
}

Okay, save the file and hit the following URL in the browser.

http://localhost:8000/users 

or

your-localhost-domain/users

You will see the page with a string like Yes!! Admin namespace is working successfully

That is it. We have successfully created a controller that now lives in a custom namespace. We were also able to group the routes to limit the work needed to define everything else and make it easier to find and understand where work is happening.

That is it for creating a custom namespace in Laravel 8.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.