Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Rest Api Laravel Package

birim/laravel-rest-api

Expose Eloquent models as a simple JSON REST API in Laravel. Configure endpoints in a config file, then query /laravel-json/{resource} for lists, skip/take pagination, and basic field search. Optionally control returned attributes via model properties.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation

    composer require birim/laravel-rest-api
    php artisan vendor:publish --provider="Birim\LaravelRestApi\RestApiServiceProvider"
    php artisan migrate
    
    • Publishes config (config/rest-api.php) and migrations (creates rest_api_tokens table).
  2. Basic API Token Setup

    • Generate a token via Tinker:
      php artisan tinker
      >>> \Birim\LaravelRestApi\Token::create(['name' => 'My API Client', 'scopes' => ['read']]);
      
    • Use the token in headers:
      Authorization: Bearer <token>
      
  3. First API Endpoint

    • Define a route with middleware:
      Route::middleware(['auth:api'])->group(function () {
          Route::get('/api/data', [DataController::class, 'index']);
      });
      
    • Test with Postman/curl:
      curl -H "Authorization: Bearer <token>" http://your-app.test/api/data
      

Implementation Patterns

1. Token-Based Authentication

  • Scopes for Granular Access Assign scopes (read, write, admin) during token creation:

    Token::create(['name' => 'Admin Dashboard', 'scopes' => ['read', 'write', 'admin']]);
    

    Validate scopes in controllers:

    public function update(Request $request) {
        if (!$request->user()->tokenCan('write')) {
            abort(403);
        }
        // ...
    }
    
  • Token Rotation Rotate tokens programmatically:

    $token = $user->tokens()->first();
    $token->rotate();
    

2. API Resource Protection

  • Route-Level Protection Use auth:api middleware for all API routes:

    Route::middleware(['auth:api'])->prefix('api')->group(function () {
        // Protected routes
    });
    
  • Controller-Level Validation Extend BaseController (if provided) or use traits for shared logic:

    use Birim\LaravelRestApi\Traits\AuthorizesRequests;
    
    class PostController extends Controller {
        use AuthorizesRequests;
    
        public function store(Request $request) {
            $this->authorize('create', Post::class);
            // ...
        }
    }
    

3. Integration with Laravel Features

  • API Rate Limiting Combine with Laravel’s rate limiting:

    Route::middleware(['auth:api', 'throttle:60,1'])->group(function () {
        // Rate-limited endpoints
    });
    
  • API Documentation Use tools like Laravel API Docs or Postman to document token-based endpoints.

  • Event Listeners Listen for token events (e.g., TokenCreated):

    public function handle(TokenCreated $event) {
        Log::info("New token created for {$event->token->name}");
    }
    

Gotchas and Tips

Pitfalls

  1. Token Storage Security

    • Issue: Tokens are stored in the rest_api_tokens table (plaintext by default).
    • Fix: Use Laravel’s HasApiTokens trait with encrypted storage (if extending).
      // config/rest-api.php
      'encrypt_tokens' => env('REST_API_ENCRYPT_TOKENS', false),
      
  2. Scope Misconfiguration

    • Issue: Forgetting to assign scopes or validating them in controllers.
    • Fix: Use tokenCan() consistently:
      if (!$request->user()->tokenCan('scope:name')) {
          abort(403, 'Insufficient permissions');
      }
      
  3. Middleware Conflicts

    • Issue: auth:api may conflict with other auth middleware (e.g., auth:sanctum).
    • Fix: Ensure only one API auth system is active per route group.

Debugging Tips

  • Token Validation Errors Check the failed_jobs table if tokens aren’t revoked properly.

    php artisan queue:work
    
  • Logging Enable debug mode in config/rest-api.php:

    'debug' => env('APP_DEBUG', false),
    

Extension Points

  1. Custom Token Models Extend the Token model to add fields (e.g., ip_whitelist):

    php artisan make:model TokenExtension --extend=Birim\LaravelRestApi\Token
    
  2. Token Providers Override the default token provider for custom logic:

    // app/Providers/AuthServiceProvider.php
    public function boot() {
        $this->app['auth']->extend('api', function ($app) {
            return new CustomTokenProvider();
        });
    }
    
  3. API Response Formatting Use Laravel’s Response macro to standardize API responses:

    Response::macro('api', function ($data, $status = 200) {
        return response()->json([
            'success' => true,
            'data' => $data,
        ], $status);
    });
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
daikazu/eloquent-salesforce-objects
unseen-codes/chat
romalytar/yammi-jobs-monitoring-laravel
kisame76/filament-db-table-state
nqxcode/laravel-lucene-search
dpfx/laravel-livewire-wizards
workos/workos-php-laravel
sofa/laravel-global-scope
nawasara/auth-primitives
adhocrat-io/arkhe-main
make-dev/orca-harpoon
itsemon245/lamet
baks-dev/dashboard
amoifr/pickle-panther-bundle
make-dev/orca
dmstr/symfony-system-resources-bundle
dmstr/symfony-job-queue-bundle
dmstr/openapi-json-schema-bundle
dmstr/keycloak-security-bundle
dmstr/doctrine-audit-log-bundle