The Missing Laravel Commands

Overview

StyleCI

SensioLabsInsight

Latest Version on Packagist

Total Downloads

Made with ❤️ by SecTheater Foundation

Artify CheatSheet will be availble soon


Laravel is a great framework and it provides us the ability to create our custom artisan commands, so why not to have a couple of commands that makes your life easier while develping your application.

If you have any inspiration about a new command , or you do something routinely and you want a command for that , Please do not hesitate at all.

Artify cares about the commands that you should have within your application, for now, it ships with commands that will help you to create files that laravel don't supply a command for them till now such as Repositories,Observers,Responsable Interface,facades and so on..

Installation Steps

1. Require the Package

After creating your new Laravel application you can include the Artify package with the following command:

composer require sectheater/artify:dev-master

If your laravel version is 5.5+, you don't need to register ArtifyServiceProvider as It"s automatically discovered, unless that you got to register it manually in your config/app.php

"providers" => [
   // other providers
   Artify\Artify\ArtifyServiceProvider::class
]

2. Add the DB Credentials & APP_URL

Next make sure to create a new database and add your database credentials to your .env file:

DB_HOST=localhost
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

3. Getting Your Environment Ready.

Just Run The following command.

	php artisan artify:install -c 20
Command Interpretation

1- It publishes the roles migrations,its seed, and the config file that artify will use.

2- "-c" stands for the caching whether to enable or not, 20 stands for the number of minutes that's going to be cached.

If you don't want to enable the cache just remove the -c and the number to become like that


php artisan artify:install

3- It asks about the Role model, and the permissions column which will artify handle during the generating files related to roles.

Artify Provides you the ability to set your custom namespace and your custom user model within config/artify.php

Installation Preview

Now everything is set, Let's dive into the Commands.

4. Commands that artify covers.


4.1 Create an Observer

Observer is typically observing for a particular eloquent event. On happening this event, Observer is fired, You can read about it at the documentation.

  // ? means optional.
 // php artisan artify:observer <name of Observer> <-m?> <-p?>
 // creates a model for this observer in case the model doesn't exist
 // registering on the provider is always set to true, if you don't want to register the observer just type "-p"
 
 php artisan artify:observer PostObserver -m 
 

The upon command generates an observer file within your App/Observers with name of PostObserver The methods there now have Post Model as parameter passed, The ignored methods while creating the observer ( which won't be within this file) are created and updated.


4.2 Create A Responsable Interface

Responsable Interface is a Laravel 5.5 feature that you should use to make your controller slim, you can see a tutorial about it.

	php artisan artify:response <name>
	// Example , please try to follow the convention of naming.. <model><method>Response
    php artisan artify:response PostShowResponse

The command upon is going to create you a new file with the name you attached under App/Responses


4.3 Synchronozing Your Roles table with Policy & Gates

This command is in charge of converting the available roles within your database into policy and gates

It's preferable to follow the convention of naming the roles as mentioned in the Roles Table Seeder

Artify also supplies you with the migration for roles, if you are going to change the permissions column, don't forget to update that within the config file

Permissions column should be an array, if they are jsonb in your database, use the accessors, or observers, or use casts property to convert permissions to an array

// Role Model

protected $casts = ["permissions" => "array"];

By Default this command requires the hasRole method ( it should return boolean ) , you can create your custom one within user model, or just import the Roles trait

 use Artify\Artify\Traits\Roles\Roles;

 Class User Extends Model {
   use Roles;    
 }

This method is required to check whether the user has a specific role to access somewhere or not, It's used within the gates. Feel free to change the gates"s logic to suit your needs.

  php artisan artify:register-authorization

By Firing this command, you can use the can middleware anywhere within your route file

  Route::get("/post/create","PostController@create")->middleware("can:create-post");

also you can access the method can anywhere in your project.

 if($user->can("create-post"))
 // do something

4.4 Assign User To A Specific Rank.

This command is just there to save you a couple of minutes whenever you assign a user manually to a specific role through database.

 php artisan artify:assign <username> <slug>
 //  Example : 
 php artisan artify:assign Alex admin

4.5 Create A Repository

Repository patten is absolutely a powerful pattern that you should use in order to separate logic from your database layer ( model ) and keep your model cleaner.

 php artisan artify:repository <name of repo> (-m?) (-f?)
 // -m stands for the model associated with the repository.
 // -f create a facade for this repository, so you can call it immediately , i.e you can just do that anywhere "\MyRepository::method();"

4.6 Generate a facade.

php artisan artify:facade <name>

4.7 Generate CRUD

Well, This artifier is really a beast, it could save you up to 20 minutes or something , It helps you to generate the following

  • Model
  • Resource Controller with the common logic you mostly do within your methods.
  • Request Form files for your store and update methods.
  • Resource Route within your web file
  • If Repository Option is enabled, It will create you the repository associating with the model.
 php artisan artify:crud <model-name> (-r?)
 // -r is optional , it will generate you the repository.

4.8 ADR Installation

You may know the ADR pattern, out of the blue artify supports this pattern, It's an alternative of MVC that we personally think it's better, if you don't know much about it yet, we recommend you getting started with this link , If you a tutorial fan, you can see this course

This command actually sets up the environment by publishing the standards of adr inside your App\App directory, which will create the directory in case you don't have it.

php artisan adr:install

4.9 ADR Generation

This command is actually powerful as it ships with various options consisting of

  • create model, migration, repository, factory "-m"
  • create resource "-c"
  • create responder "-r"
  • create action "-a"
  • create service "-s"
  • create everything "-A"

Let's start with the basics

php artisan adr:generate Addresses IndexAddress -sra

This is going to create you Addresses folder under the app directory and will look like the following structure :

├── App

├── Addresses   

│   ├── Actions    

│   │   ├── IndexAddressAction.php

│   ├── Domain

│   |   ├── Services

|	|      ├── IndexAdressService.php

│   ├── Responders

│   |   ├── IndexAddressResponder

└── ...

Which in essence creates you Action, Service, Responder.

You can also model, associated with the repository and migration

php artisan adr:generate Addresses -m

Note that passing the filename in this case will be ignored, as the domain is only our main concern in this case, anyways this will generate you the repository, model, migration and the factory.

You can also create a resource for this domain using the -c option.

	php artisan adr:generate Addresses -c

You can also combine them all at once using the -A option.

 php artisan adr:generate Videos IndexVideo -A

This will create you Responder,Action, and Domain components.

Note that action,responder,service will contain of IndexVideo file only, for creating other files, use the command again and mention their names again.

5.0 Roles Trait

This trait is there to handle the authorization process for artify commands , but feel free to use it for your own purposes. It contains of a few methods that"s really helpful for you to handle authorization anywhere within your application. Let"s dive into the Methods there.

The Trait supports checking roles within your roles table and the users table ( secondary permissions to be assigned for users )

Authorization Methods.

1.0 hasRole Method

This method accepts only one argument and it should be string, the string should match a role name within your permissions column either on users table or roles table.

$user = \App\User::first();

dd($user->hasRole("create-post")); // if the current logged in user has the ability to "create-post", it will return true

The method is going to search for the permission associated with the user either on roles table or users table.

2.0 hasAnyRole Method

I think you"ve guessed what"s going on here, It searches for all of the roles you pass and returns true on the first role that a user may have

  dd($user->hasAnyRole(["create-post","foo-bar","approve-post"])); // returns true/false;
3.0 hasAllRole Method

This method accepts one argument, it should be an array containing of the permissions you are checking for.

This method checks on all the roles passed, whether the user has them all or not.
  dd($user->hasAllRole(["foo-bar","upgrade-user"])); // returns true/false;
3.0 inRole Method

This method checks if the user"s rank is typically equal to the passed argument.

- Slug that represents your permissions in role table. - returns boolean
 dd($user->inRole("admin"); // This slug exists within the seeder

Permissions Handling Methods.

The permissions are assigned to the current user you are working on only. i.e you can retrieve the user by finding him/her or get the authenticated user then handle his/her permisisons.

1.0 Add Permission

This method accepts two arguments which are the permissions and boolean value.

- Permissions can be either string or array. - boolean value represents the ability of the user to do mentioned permission. - returns boolean.
   $user->addPermission("create-custom-post"); // second parameter is set to true by default, so the added permission is available for this user.
   $user->addPermission("create-something",false) // the user isn\'t allowed to "create-something" now.
   $user->addPermission(["create-something" => true , "can-push-code" => false]) 
   /* you don\'t need the second parameter now as the key and value of this array is going to be in charge of handling the permissions. */
   

2.0 Update Permission

This method accepts three arguments

- Permission , should be a string. - boolean value represents the ability of the user to do mentioned permission. - boolean value , represents creating the permission if it doesn't exist. - returns boolean.
 $user->updatePermission("create-post"); // this will update the permission to set it to true.
 $user->updatePermission("create-post",false); // this will update the permission to set it to false
 $user->updatePermission("foo-bar",false,true); // this will create the permission if it doesn\'t exist and set it to false.

3.0 Remove Permission

This method accepts one argument only representing the permission

- n of permissions can be passed a separate parameter. - returns boolean

If the permission isn't set, an exception is thrown.

  $user->removePermission("create-post"); // returns boolean
  $user->removePermission("create-post","delete-post","whatever-role",...); // returns boolean

For Further Resources, Here is an article on [medium] : https://medium.com/@secmuhammed/the-missing-laravel-commands-have-arrived-e0db7092cf07

You might also like...
A package for more Laravel commands.

Lara-Commands A package for more Laravel commands. Installation This package can be installed via Composer: composer require nimaw/lara-commands --dev

Laravel API architecture builder based on artisan commands.

🧑‍🔬 API-Formula Laravel API architecture builder based on artisan commands. This package provides a nice and fluent way to generate combined control

This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.
This Laravel Nova tool lets you run artisan and bash commands directly from Nova 4 or higher.

Laravel Nova tool for running Artisan & Shell commands. This Nova tool lets you run artisan and bash commands directly from nova. This is an extended

Execute Laravel Artisan commands via REST APIs and HTTP requests safely.

Artisan Api There might be some times you wanted to execute an Artisan command, but you did not have access to shell or SSH. Here we brought REST API

A package that makes it easy to have the `artisan make:` commands open the newly created file in your editor of choice.

Open On Make A package that makes it easy to have the artisan make: commands open the newly created file in your editor of choice. Installation compos

List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Breeze, Laravel Cashier, Laravel Nova and Laravel Spark.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.
⚡ Laravel Charts — Build charts using laravel. The laravel adapter for Chartisan.

What is laravel charts? Charts is a Laravel library used to create Charts using Chartisan. Chartisan does already have a PHP adapter. However, this li

Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster.

Laravel Kickstart What is Laravel Kickstart? Laravel Kickstart is a Laravel starter configuration that helps you build Laravel websites faster. It com

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app
Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Laravel User Activity Log - a package for Laravel 8.x that provides easy to use features to log the activities of the users of your Laravel app

Comments
  • Laravel 5.8 tenant connection migration issue.

    Laravel 5.8 tenant connection migration issue.

    I am following the tutorial on medium about multi-tenancy, when I ran art:migrate it give a foreign key error.

    SQLSTATE[HY000]: General error: 1005 Can't create table multi-tenant.tenant_connections (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table tenant_connections add constraint tenant_connections_tenant_id_foreign foreign key (tenant_id) references companies (id))

    Any help would be appreciated.

    question 
    opened by shahzad-sarwar 8
  • Default migration crashing

    Default migration crashing

    Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (0.01 seconds) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (0.01 seconds) Migrating: 2017_11_21_171555_artify_roles_tables

    Illuminate\Database\QueryException : SQLSTATE[HY000]: General error: 1005 Can't create table common.role_users (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table role_users add constraint role_users_user_id_foreign foreign key (user_id) references users (id) on delete cascade)

    opened by YouzOnline 2
  • Fix repositories generator

    Fix repositories generator

    1- Removed deprecated trait DetectsApplicationNamespace in laravel 7 in RegisterAuthorizationCommand

    2- Namespace fixed fro repositories by using lcfirst() in macro transformNamespaceToLocation

    3-the adr switch unified between install command and other commands

    enhancement 
    opened by mohamed-abdelrhman 0
Releases(v2.0.5)
Owner
Security Theater
Security Theater
The missing laravel helper that allows you to inspect your eloquent queries with it's bind parameters

Laravel Query Inspector The missing laravel helper that allows you to ispect your eloquent queries with it's bind parameters Motivations Let's say you

Mouad ZIANI 59 Sep 25, 2022
Voyager - The Missing Laravel Admin

Voyager - The Missing Laravel Admin Made with ❤️ by The Control Group Website & Documentation: https://voyager.devdojo.com/ Video Tutorial Here: https

PeopleConnect 11.3k Jan 7, 2023
Missing pet flyer - Laravel 4 application

Laravel 4.0 Application - Pet Flyer generator Features This is the source of http://missingpetflyer.com that is deployed to Pagodabox. This applicatio

Maksim Surguy 70 Nov 18, 2022
Provides the missing range field for the Filament forms.

The missing range field for the Filament forms. Installation You can install the package via composer: composer require yepsua/filament-range-field Pu

null 11 Sep 10, 2022
A package for Laravel to perform basic git commands on locally integrated packages.

A package for Laravel to perform basic git commands on locally integrated development packages. If working within multiple local development packages or repositories at once this package is meant to ease the burden of navigating to each individual repository to perform basic git commands.

null 3 Jul 26, 2022
Mutex for Laravel Console Commands.

Laravel Console Mutex Mutex for Laravel Console Commands. Laravel Console Mutex 8.x 8.x 7.x 7.x 6.x 6.x 5.8.* 5.8.* 5.7.* 5.7.* 5.6.* 5.6.* 5.5.* 5.5.

Dmitry Ivanov 125 Dec 17, 2022
A simple laravel package to validate console commands arguments and options.

Command Validator A simple laravel package to validate console commands arguments and options. Installation Require/Install the package using composer

Touhidur Rahman 20 Jan 20, 2022
Package for Laravel that gives artisan commands to setup and edit environment files.

Setup and work with .env files in Laravel from the command line NOTE: This doesn't work with Laravel 5 since .env files were changed. This is for Lara

Matt Brunt 6 Dec 17, 2022
A wrapper package to run mysqldump from laravel console commands.

A wrapper package to run mysqldump from laravel console commands.

Yada Khov 24 Jun 24, 2022
A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands.

artisan.page A bookmarkable, searchable cheatsheet for all of Laravel's default Artisan commands. Generation The generation of the manifest files is d

James Brooks 284 Dec 25, 2022