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.

#laravel #php #coding

How to Create Custom Namespace in Laravel 8
10.85 GEEK