Laravel API - Add New APIRoute Component.,

Note: If you need further help, watch a video at the bottom of the page might help.

or https://youtu.be/57Ej3X6tzfw?t=319 is a good one


NOTE: Button to change will appear in 5 seconds to allow Jquery to load. Use this form to change the component name to whatever you provide in the text field. The text you provide will replace all the 'ComponentName' instances on this page with whatever you enter in the field above.
  1. Generate a model with migration, ComponentName resource class, and form request classes..
    $ php artisan make:model ComponentName -m --controller --resource --requests
  2. MOVE THE NEWLY CREATED CONTROLLER TO THE API SUB FOLDER (IF ANY)
    $ mv app/Http/Controllers/ComponentNameController.php app/Http/Controllers/Api/ComponentNameController.php
    $ code app/Http/Controllers/Api/ComponentNameController.php
  3. ComponentNameController.php
    1. Add the following includes
      use Illuminate\Support\Facades\Auth;
      use Illuminate\Http\Request;
      use App\Http\Resources\ComponentNameResource;

      IMPORTANT: Also be sure to change the namespace to the Api folder and include the Controller in Controllers.
      namespace App\Http\Controllers\Api;
      use App\Http\Controllers\Controller;
       
    2. In public function index() ADD to get the last 5 records from the database:
      return ComponentNameResource::collection(ComponentName::take(5)->get());
  4. Create a resource:
    $ php artisan make:resource ComponentNameResource
    $ code app/Http/Resources/ComponentNameResource.php
  5. Add the database table columns, ComponentNameResource.php should look like this:
    <?php

    namespace App\Http\Resources;

    use Illuminate\Http\Resources\Json\JsonResource;

    class ComponentNameResource extends JsonResource
    {
        public static $wrap = false;
        /**
         * Transform the resource into an array.
         *
         * @param  \Illuminate\Http\Request  $request
         * @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
         */
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'user_id' => $this->user_id,
                'name' => $this->name,
                'type' => $this->type,
                'size' => $this->size,
                'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            ];
        }
    }
  6. OPEN MIGRATION FILE: 2023_05_07_210947_create_ComponentName_table.php
    $ code database/migrations/*create_ComponentName_table.php
  7. Add the migration column types. For more informatin go to: https://laravel.com/docs/10.x/migrations#available-column-types
            Schema::create('ComponentName', function (Blueprint $table) {
                // id will Increments
                $table->id();
                $table->timestamps();
                $table->string('user_id');
                $table->string('name')->nullable();
                $table->string('type')->nullable();
                $table->string('size');
            });
  8. NOTE: CANNOT USER WILD CARD> FULL FILE NAME MUS TBE PROVIDED
    // SHOW THE Migrations table you can copy and paste
    $ ls database/migrations
    $ php artisan migrate --path='./database/migrations/2023_05_07_210947_create_ComponentName_table.php'
  9. Set the Model
    $ code app/Models/ComponentName.php
  10. Add the  Notifiable, API Tokens and database columns
    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Foundation\Auth\User as Authenticatable;
    use Illuminate\Notifications\Notifiable;
    use Laravel\Sanctum\HasApiTokens;

    class ComponentName extends Authenticatable
    {
        use HasApiTokens, HasFactory, Notifiable;

        /**
         * The attributes that are mass assignable.
         *
         * @var array<int, string>
         */
        protected $fillable = [
            'name',
            'type',
            'size',
            'user_id'
        ];
    }
  11. Add the API Routes
    $ code routes/api.php
  12. Add the following Route:
    // NO LOGING REQUIRED HERE:
    // GET http://localhost:8000/api/ComponentName/files
    Route::apiResource('/files',   ComponentNameController::class);
  13. NOTE: For routes requiring authentication, add the route inside auth:sanctum
    Route::middleware('auth:sanctum')->group(function () {
    ....
    });
  14. PHPMyAdmin: Add seeds or add fake data to the ComponentName database table. For example:
    DROP TABLE IF EXISTS `ComponentName`;
    CREATE TABLE `ComponentName` (
      `id` bigint(20) UNSIGNED NOT NULL,
      `created_at` timestamp NULL DEFAULT NULL,
      `updated_at` timestamp NULL DEFAULT NULL,
      `name` varchar(255) DEFAULT NULL,
      `type` varchar(255) DEFAULT NULL,
      `size` varchar(255) NOT NULL
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

    INSERT INTO `ComponentName` (`id`, `created_at`, `updated_at`, `name`, `type`, `size`) VALUES
    (1, '2023-05-07 21:32:57', '2023-05-07 21:32:57', 'File #1 from database', 'image', '25641'),
    (2, '2023-05-07 21:32:57', '2023-05-07 21:32:57', 'File #2 from database', 'image', '225121');
  15. That's it. Give it a try: http://localhost:8000/api/ComponentName/files

 

Detailed Notes: I took these notes when adding a new page to the api with database.


# https://laravel.com/docs/10.x/eloquent#generating-model-classes

1. # Generate a model iwth migration, FlightController resource class, and form request classes...
$ php artisan make:model ComponentName -m --controller --resource --requests

OUTPUT:
   INFO  Model [G:/xampp/Models/ComponentName.php] created successfully.  

   INFO  Request [G:/xampp/Http/Requests/StoreComponentNameRequest.php] created successfully.  

   INFO  Request [G:/xampp/Http/Requests/UpdateComponentNameRequest.php] created successfully.  

   INFO  Controller [G:/xampp/Http/Controllers/ComponentNameController.php] created successfully.


API controller: https://laravel.com/docs/10.x/controllers#api-resource-routes
# $ php artisan make:controller ComponentNameController --api NOT NEEDED BECAUSE 1st STEP ALREADY CREATED CONROLLER
# MOVE THE NEWLY CREATED CONTROLLER TO THE API SUB FOLDER (IF ANY)
$ mv app/Http/Controllers/ComponentNameController.php app/Http/Controllers/Api/ComponentNameController.php
$ code app/Http/Controllers/Api/ComponentNameController.php

ADD:
# FOR AUTH
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Http\Resources\ComponentNameResource;


In public function index() ADD:

return ComponentNameResource::collection(ComponentName::take(5)->get());


2. Generating Resources
https://laravel.com/docs/10.x/eloquent-resources

$ php artisan make:resource ComponentNameResource
$ code app/Http/Resources/ComponentNameResource.php

ADD to return to:
        return [
            'id' => $this->id,
            'name' => $this->name,
            'type' => $this->type,
            'size' => $this->size,
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
        ];

3. ADD MODEL
Generating Model Classes
https://laravel.com/docs/10.x/eloquent#generating-model-classes


OPEN MIGRATION FILE:
https://www.youtube.com/watch?v=g-63ClKANsM
$ code database/migrations/*create_ComponentName_table.php

IN THE UP FUNCTIONADD THE COLUMNS FOR THE TABLE:
        Schema::create('ComponentName', function (Blueprint $table) {
            // id will Increments
            $table->id();
            $table->timestamps();
            $table->string('name')->nullable();
            $table->string('type')->nullable();
            $table->string('size');
        });

NOTE: CANNOT USER WILD CARD> FULL FILE NAME MUS TBE PROVIDED
$ php artisan migrate --path='./database/migrations/2023_05_07_210947_create_ComponentName_table.php'



## $ php artisan make:model ComponentNames --migration  NOT NEEDED BECAUSE 1st STEP ALREADY CREATED

$ code app/Models/ComponentName.php

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class ComponentName extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'type',
        'size',
        'user_id'


    ];
}


$ GET, POST, PUT, DELETE (show, update,destroy)
https://laravel.com/docs/10.x/controllers#shallow-nesting




2. go to routes/api.php add:
$ code routes/api.php

// NO LOGING REQUIRED HERE:
// GET http://localhost:8000/api/ComponentName/files
Route::apiResource('/ComponentName/files',   ComponentNameController::class);


for login: add between:
Route::middleware('auth:sanctum')->group(function () {

});

g-63ClKANsM