In this article, I’ll go to through a basic example of how to create a Laravel Package in Laravel with few steps:
Fresh installation of the Laravel using: “composer create-project –prefer-dist lravel/laravel projectname”.
After install Laravel project, we will follow steps like:
Next, for our packages we need “composer.json” file because every package should have composer.json file, which will contain dependencies and information about the package itself. So inside your terminal navigate to the folder with your package “calc” name and run the following command: “composer init”
“composer.json” file look like:
Next, we need to make our package visible to the Laravel structure, open the main “composer.json” file under the root directory and add the namespaces of our packages in “autoload>psr-4”.
After adding this, run this command: “composer dump-autoload”.
Next, create a service provider file under your “Packages/digital/calc/src” directory and don’t forget to use your namespace “Vendor\Package_name”. Basically service provider is the main entry of your package. This is where your package is loaded or booted.
Next, open “Config/app.php” file and add your service provider inside the “Providers array ”.
Next, inside of your “src” folder create a new “routes.php” file and write the following code:
Then go to your Service Provider and add the “routes.php” inside “boot ()” method:
After this, run command “php artisan serve” and enter the URL http://127.0.0.1:8000/calculator in your browser. This we should end up with the page look like:
Inside the packages directory under “src” folder create a new Controller file:
Under this “CalculatorController.php” file don’t forget to include your package namespace and also include the “App\Http\Controllers\Controller;”
After creating the controller we need to register the controller inside our Service Provider class in “register ()” method.
Next, add routes for this controller inside “routes.php” file:
To create a view, we need create a “views” folder inside “packages/digital/calc/src” directory then create an “app.blade.php” file inside view folder.
After creating “add.blade.php”, write following code:
We need to register the views inside our Service Provider class in “boot ()” method.
After creating controller, views and register into service provider then navigate the browser look like:
Tags: Laravel Package