Laravel Artisan summary

345 0 0 0

Last Updated : 2023-09-23 22:13:44

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->char('prefix', 2);chamber is a replacement
    $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->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
    'title'-> 'required',
    'post_text'-> 'required',

    @foreach($errors->all() as $error)
    ------------------------------ Validation end

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

    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
    @section('sectionName') @endsection

    <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
    $chamber = Chamber::find($id);
    /* $success = ChamberModel::where('chamber_id', $currentId)->update([
    'chamber_id' => $id,
    'chamber_name' => $name,
    ]); */

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

    //Send a response with 404

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

  • 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->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 .