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

Framework Laravel Package

laravel/framework

Laravel is a modern PHP web application framework with expressive syntax and batteries-included tooling: fast routing, dependency injection, sessions/cache, migrations, queues, and real-time broadcasting—built to make development enjoyable for apps of any size.

View on GitHub
Deep Wiki
Context7
## Getting Started

### Minimal Steps
1. **Installation**:
   ```bash
   composer create-project laravel/laravel project-name
  • Follow the official installation guide for environment setup (PHP, Composer, database, etc.).
  • Use php artisan serve to spin up a local server for immediate testing.
  1. First Use Case:

    • Routing: Define a route in routes/web.php:
      Route::get('/greet', function () {
          return "Hello, Laravel!";
      });
      
    • Controller: Generate a controller scaffold:
      php artisan make:controller UserController --resource
      
    • Database: Create a migration:
      php artisan make:migration create_users_table
      
      Define schema in the migration file, then run:
      php artisan migrate
      
  2. Where to Look First:

    • Documentation: Start here for API references, guides, and best practices.
    • app/ Directory: Core application logic (controllers, models, providers).
    • routes/ Directory: Web and API route definitions.
    • config/ Directory: Framework configurations (e.g., app.php, database.php).
    • resources/views/: Blade templates for frontend rendering.
    • tests/: Built-in testing utilities (PHPUnit, Pest).

Implementation Patterns

Core Workflows

  1. Dependency Injection (DI) and Service Container:

    • Pattern: Bind interfaces to implementations in AppServiceProvider:
      public function register()
      {
          $this->app->bind(
              \App\Contracts\PaymentGateway::class,
              \App\Services\StripePayment::class
          );
      }
      
    • Usage: Resolve dependencies in controllers or commands:
      public function __construct(private PaymentGateway $paymentGateway) {}
      
  2. Eloquent ORM:

    • Pattern: Define models in app/Models/ with relationships:
      class Post extends Model
      {
          public function comments()
          {
              return $this->hasMany(Comment::class);
          }
      }
      
    • Usage: Query with fluent methods:
      $posts = Post::with('comments')->where('published', true)->get();
      
    • Eager Loading: Avoid N+1 queries:
      Post::with(['comments', 'author'])->find(1);
      
  3. Middleware:

    • Pattern: Create middleware for cross-cutting concerns:
      php artisan make:middleware EnsureVerifiedEmail
      
    • Usage: Register in app/Http/Kernel.php:
      protected $routeMiddleware = [
          'verified.email' => \App\Http\Middleware\EnsureVerifiedEmail::class,
      ];
      
    • Apply to Routes:
      Route::get('/dashboard', function () {
          // ...
      })->middleware('verified.email');
      
  4. Artisan Commands:

    • Pattern: Extend Illuminate\Console\Command:
      class SendEmailsCommand extends Command
      {
          protected $signature = 'emails:send';
          protected $description = 'Send scheduled emails';
      
          public function handle()
          {
              // Logic here
          }
      }
      
    • Usage: Register in app/Console/Kernel.php and run:
      php artisan emails:send
      
  5. Events and Listeners:

    • Pattern: Dispatch events in models/controllers:
      event(new OrderPlaced($order));
      
    • Usage: Register listeners in EventServiceProvider:
      protected $listen = [
          OrderPlaced::class => [
              SendOrderConfirmation::class,
          ],
      ];
      
  6. API Resources:

    • Pattern: Transform models for API responses:
      class PostResource extends JsonResource
      {
          public function toArray($request)
          {
              return [
                  'id' => $this->id,
                  'title' => $this->title,
                  'comments' => CommentResource::collection($this->comments),
              ];
          }
      }
      
    • Usage: Return from controllers:
      return new PostResource($post);
      
  7. Queues and Jobs:

    • Pattern: Dispatch jobs for background processing:
      SendEmailJob::dispatch($user);
      
    • Usage: Define jobs:
      class SendEmailJob implements ShouldQueue
      {
          use Dispatchable, InteractsWithQueue;
      
          public function handle()
          {
              // Send email logic
          }
      }
      
    • Run Workers:
      php artisan queue:work
      
  8. Testing:

    • Pattern: Use Laravel’s testing helpers:
      public function test_example()
      {
          $response = $this->get('/');
          $response->assertStatus(200);
      }
      
    • Usage: Mock dependencies with Mockery or createMock:
      $this->mock(PaymentGateway::class, function ($mock) {
          $mock->shouldReceive('charge')->once();
      });
      

Integration Tips

  • Service Providers: Override or extend Laravel’s providers in config/app.php under providers.
  • Blade Directives: Create custom directives:
    Blade::directive('datetime', function ($expression) {
        return "<?php echo ($expression)->format('Y-m-d H:i:s'); ?>";
    });
    
  • Macros: Extend Laravel classes dynamically:
    Str::macro('slug', function ($string) {
        return Str::of($string)->slug();
    });
    
  • Packages: Publish package configs/assets:
    php artisan vendor:publish --provider="Vendor\Package\ServiceProvider"
    
  • Testing: Use RefreshDatabase trait for database testing:
    use RefreshDatabase;
    
    public function test_user_creation()
    {
        $user = User::factory()->create();
        // ...
    }
    

Gotchas and Tips

Pitfalls

  1. N+1 Query Problem:

    • Issue: Eager load relationships to avoid repeated queries.
    • Fix: Use with() or load():
      $posts = Post::with('comments')->get();
      
  2. Session/Redis Connection Leaks:

    • Issue: Cloning session managers can cause duplicate connections.
    • Fix: Avoid cloning or use withoutEvents() where possible.
  3. Attribute Parsing Conflicts:

    • Issue: Trait initializers may collide with attribute parsing.
    • Fix: Ensure traits are loaded before attributes or use #[WithoutRelations].
  4. Queue Job Timeouts:

    • Issue: Jobs may fail silently due to timeouts.
    • Fix: Monitor with php artisan queue:failed and retry:
      php artisan queue:retry all
      
  5. Route Caching:

    • Issue: Cached routes may not reflect changes.
    • Fix: Clear cache after route changes:
      php artisan route:clear
      
  6. Validation Strict Mode:

    • Issue: Form requests may behave unexpectedly in tests.
    • Fix: Reset strict mode with flushState():
      $request->flushState();
      
  7. Carbon Timezone Issues:

    • Issue: Timezone mismatches in Carbon instances.
    • Fix: Set timezone explicitly:
      Carbon::setTimezone('UTC');
      
  8. Middleware Order:

    • Issue: Middleware may not run in the expected order.
    • Fix: Define order in app/Http/Kernel.php:
      protected $middleware = [
          \App\Http\Middleware\TrustProxies::class,
          \App\Http\Middleware\CheckForMaintenanceMode::class,
      ];
      
  9. Eloquent Mutators/Accessors:

    • Issue: Mutators may override attribute values unexpectedly.
    • Fix: Use $attributes array for direct assignments:
      $user->setRawAttributes(['name' => 'John']);
      
  10. Queue Job Serialization:

    • Issue: Complex objects may not serialize correctly.
    • Fix: Use #[WithoutRelations] or implement Serializable:
      #[WithoutRelations]
      class ComplexJob implements ShouldQueue {}
      

Debugging Tips

  • Log Everything:

    • Use Log::debug(), Log::info(), or dd() (dump and die) for debugging.
    • Configure logging in config/logging.php.
  • Tinker:

    • Use php artisan tinker for interactive debugging:
      php artisan tinker
      >>> $user = App\Models\User::first();
      >>> $user->posts
      
  • Exception Handling:

    • Customize error pages in `app/Exceptions/
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport