How to create a Restful Crud for API using Laravel

WINW > Software Development > Symfony > How to create a Restful Crud for API using Laravel

Create a Model with Migration:

If you want to create a database table for your model, use the -m or --migration option:

php artisan make:model ModelName

This will generate a migration file in the database/migrations/ directory. Edit the migration file to define your table schema.

Create a Controller:

To create a resourceful controller (with CRUD methods), use the --resource or -r option:

php artisan make:controller ModelController --resource

This command will generate a controller named ModelController with methods for listing, creating, updating, and deleting model records.

Define Routes:

In your routes/web.php or routes/api.php file, define routes that map to the controller methods.

For example:

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Domains\Model\ModelController;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "api" middleware group. Make something great!
|
*/

Route::resource('model', ModelController::class);

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Configure your controller:

Configure the controller that you’ve created on step 2, with the code to execute the operations.

For example:

<?php

namespace App\Http\Controllers\Domains\Model;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Domains\Model\Model;

class ModelController extends Controller
{
    /**
     * Display a listing of the Model.
     *
     * @return JsonResponse
     */
    public function index()
    {
        $Model = Model::all();
        return response()->json(['Model' => $Model]);
    }

    /**
     * Store a newly created model in storage.
     *
     * @param  Request  $request
     * @return JsonResponse
     */
    public function store(Request $request)
    {
        // Validate input and save the model
        // Example: Model::create($request->all());

        return response()->json(['message' => 'Model created!']);
    }

    /**
     * Display the specified model.
     *
     * @param  Model  $model
     * @return JsonResponse
     */
    public function show(Model $model)
    {
        return response()->json(['model' => $model]);
    }

    /**
     * Update the specified model in storage.
     *
     * @param  Request  $request
     * @param  Model  $model
     * @return JsonResponse
     */
    public function update(Request $request, Model $model)
    {
        // Validate input and update the model
        // Example: $model->update($request->all());

        return response()->json(['message' => 'Model updated!']);
    }

    /**
     * Remove the specified model from storage.
     *
     * @param  Model  $model
     * @return JsonResponse
     */
    public function destroy(Model $model)
    {
        $model->delete();
        return response()->json(['message' => 'Model deleted!']);
    }
}

Create a table for your model:

php artisan make:migration create_users_table --schema="username:string, email:string:unique"

If you want to check how to create table with different field types, check this link: Examples of creation of tables via make on laravel

Or if you prefer you can edit the migration that are located in: database/migrations, example:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('pecas', function (Blueprint $table) {
            $table->id();
            $table->string('nome');
            $table->text('descricao')->nullable();
            $table->string('imagemPrincialPath')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('pecas');
    }
};

After defining the model execute the migrations:

php artisan migrate

Leave a Reply