Laravel Artisan summary

566 0 0 0

Last Updated : 2024-04-16 14:48:47

Here is a list of a quick guide for almost all important artisan commands that can be used to make it easy to go a long with new laravel application


  • Make Controllers, Models and resource controller
    php artisan make:model Bill -m // (Create a model along with a migration)
    php artisan make:model post -mcrsf // (Migration + Controller + Resource for controller + seeder + factory)
    php artisan make:controller BillController --resource --model=Bill //(Create a resource controller and assign a model)


  • Models
    protected $fillable = ['field1', 'field2'];


  • DataBase Migrations, RollBacks, and Seeding
    php artisan db:seed
    php artisan db:seed --class=MembersandsenatorSeeder //Specific Seeder class

    php artisan migrate
    php artisan migrate:refresh
    php artisan migrate:refresh --path=/database/migrations/fileName.php //Specific migration file
    php artisan migrate:rollback
    php artisan migrate:rollback --step=3

    ############################################################### Migration
    public function up(): void
    {
    Schema::create('bills', function (Blueprint $table) {
    $table->id();
    $table->string('title');
    $table->tinyInteger('parl')->default(44);
    $table->integer('session')->default(1);
    // $table->char('prefix', 2);chamber is a replacement
    $table->smallInteger('billNumber');
    $table->enum('type', ['Senate Government Bill','Senate Public Bill','Senate Private Bill','House Government Bill','Private Members Bill','House Private Bill']);
    $table->enum('chamber', ['senate','house'])->default('senate');
    $table->integer('pMember_id');
    $table->string('status')->nullable();
    $table->string('tags')->nullable();
    $table->string('keywords')->nullable();
    $table->text('description')->nullable();
    $table->date('introduced_date');
    $table->date('ComesIntoForceDate');
    $table->string('legislativeSummaryURL')->nullable();
    $table->string('govURL');

    $table->timestamps();
    $table->comment('For both Federal and Provincial bills');


    // $table->id('user_id'); //Will create a primary bigincrement unsigned and you can pass a column name (optional)
    // $table->enum('prefix', ['s', 'c']);
    // $table->foreignId('user_id');
    // $table->foreignIdFor(User::class);
    // $table->set('flavors', ['strawberry', 'vanilla']);
    // $table->string('name', 100); //varchar equivalent
    // $table->lineString('legislativeSummaryURL');
    // $table->tinyInteger('parl'); //-128 - 127
    // $table->smallInteger('votes'); //-32768 - 65535
    // $table->bigInteger('id'); //-2(32) - 2(32)

    // $table->foreign('category_id')->references('id')->on('categories');
    // $table->foreignId('bill_id')->nullable()->constrained()->onUpdate('CASCADE')->onDelete('CASCADE'); //[CASCADE|RESTRICT|NO ACTION|SET DEFAULT|SET NULL]

    // --------------------------------------- >>>> ADDING INDICES
    // $table->primary('id'); Adds a primary key.
    // $table->primary(['id', 'parent_id']); Adds composite keys.
    // $table->unique('email'); Adds a unique index.
    // $table->index('state'); Adds an index.
    // $table->fullText('body'); Adds a full text index (MySQL/PostgreSQL).
    // $table->fullText('body')->language('english'); Adds a full text index of the specified language (PostgreSQL).
    // $table->spatialIndex('location'); Adds a spatial index (except SQLite).
    });
    }


  • Routes, Route list
    php artisan route:list
    php artisan route:list --name=account [filter by name]
    php artisan route:list --method=GET


  • Request and Validation
    php artisan make:request StorePostRequest

    ------------------------------ Validation start
    $request->validate([
    'title'-> 'required',
    'post_text'-> 'required',
    'category_id'->'required'
    ]);

    @if($errors->any())
    @foreach($errors->all() as $error)
    {{$error}}
    @endforeach
    @endif
    ------------------------------ Validation end

    //------ Unique against table, field and ignore one specific model:
    1) return [
    'title' => "required|unique:posts,title,{$this->post->id}"
    ];
    2) return [
    'title' => [
    'required',
    Rule::unique('posts', 'title')->ignore($this->post)
    ]
    ];
    3) 'name' => 'required|string|unique:chambers,name,'.$this->request->get('id'),

    4)
    use Illuminate\Validation\Rule;
    'bill_number' => ['required','numeric',
    Rule::unique('bills')->ignore($this->bill)->where('chamber_id', $this->chamber_id)
    ],

    //--------------- Value either in
    'chamber_type' => ['required',Rule::in(['federal', 'provincial'])],


  • Blade Directives and guides
    @csrf
    @method('PUT')
    @method('DELETE')
    @section('sectionName') @endsection
    @yield('sectionName')
    @include('viewAfterviewFolder')

    //----------------------------------------------------------------------------------
    <option value="{{$category->id}}" @selected($category->id == $post->category_id)>{{$category->name}}</option>
    <input type="radio" name="aa" value="{{$category->id}}" @checked($category->id == $post->category_id)>Text
    <input type="text" name="aa" value="{{$category->id}}" @disabled($category->id == $post->category_id)>


  • Redirection in Controllers and others
    return redirect()->route('categories.index');


  • General Info and Tips
    app\Http\Kernel.php  //[Has the middlewares]


  • Composer and dependencies
    composer require barryvdh/laravel-debugbar


  • Models & Controllers Codes
    //Update record in DB + with FormRequest Validation + and JSON response
    1)
    $chamber = Chamber::find($id);
    $chamber->update($request->validated());
    2)
    /* $success = ChamberModel::where('chamber_id', $currentId)->update([
    'chamber_id' => $id,
    'chamber_name' => $name,
    ]); */

    return response()->json($chamber, 201);

    //Send a response with 404
    abort(404);

    //====================================== DELETING RECORDS
    App\Model::destroy(1);
    App\Model::destroy([1, 2, 3]);
    App\Model::where('active', 0)->delete();
    //---------------
    $user = User::find(1);
    $user->delete();


  • Eloquent techniques :
    //Search By relationship, Here is it the 'company' 
    //Note: the relationship is not in an array more in 'with' method, otherwise it won't work
    $items = (new User())->newQuery();
    $items->with('company');
    $items->where(function($q) use ($searchValue){
    $q->where("name" , 'like', "%{$searchValue}%");
    $q->orwhere("email" , 'like', "%{$searchValue}%");
    $q->orwhere("company_role" , 'like', "%{$searchValue}%");

    $q->orWhereHas('company', function($qCompany) use ($searchValue){
    $qCompany->where("name" , 'like', "%{$searchValue}%");
    });
    });


  • File Upload
    //Get file name and extension
    $file = Input::file('upfile')->getClientOriginalName();

    $filename = pathinfo($file, PATHINFO_FILENAME);
    $extension = pathinfo($file, PATHINFO_EXTENSION);


  • -

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .