Laravel Framework

repository·13.x·Indexed 12 days ago

https://github.com/laravel/framework

A PHP web application framework featuring an expressive syntax and a robust toolset for routing, dependency injection, database management, and background processing. Includes the Illuminate components such as the Eloquent ORM, Query Builder, and Queue manager, which can be used independently via the Capsule manager.

Tokens
15.3K
Snippets
69
Records
80
Agent score
99%

What's inside Laravel

  1. Overview of the Laravel Framework

    13.x

    Laravel is a web application framework designed with an expressive and elegant syntax to ease common web development tasks. It provides a complete toolset for building large, robust applications by handling core concerns such as routing, dependency injection, session management, and database migrations.

    Key features include:

    • Routing: A simple and fast routing engine.
    • Dependency Injection: A powerful container for managing class dependencies.
    • Storage: Multiple back-ends for session and cache storage.
    • Database Migrations: Database-agnostic schema migrations.
    • Queues: Robust background job processing.
    • Broadcasting: Real-time event broadcasting.
  2. Set up the Illuminate Queue Capsule manager

    13.x

    If you are using the Queue component outside of the full Laravel framework, you can use the Capsule manager to configure and manage queue connections. This is similar to how the Eloquent ORM Capsule works.

    1. Instantiate Illuminate\Queue\Capsule\Manager.
    2. Use addConnection() to define your queue driver and connection settings (e.g., driver, host, queue).
    3. (Optional) Call setAsGlobal() to allow accessing the queue manager via static methods on the Queue class.
    use Illuminate\Queue\Capsule\Manager as Queue;
    
    $queue = new Queue;
    
    $queue->addConnection([
        'driver' => 'beanstalkd',
        'host' => 'localhost',
        'queue' => 'default',
    ]);
    
    // Make this Capsule instance available globally via static methods...
    $queue->setAsGlobal();
  3. How to learn Laravel

    13.x

    Laravel offers several resources for developers to learn the framework, ranging from official documentation to video-based learning:

    • Official Documentation: The most extensive and thorough documentation available at laravel.com/docs.
    • Laravel Learn: A guided experience for building modern Laravel applications from scratch, including PHP fundamentals, at laravel.com/learn.
    • Laracasts: A video tutorial library containing thousands of lessons on Laravel, modern PHP, unit testing, JavaScript, and more at laracasts.com.
  4. Install and configure Illuminate Database using Capsule

    13.x

    To use the Illuminate Database component outside of the Laravel framework, use the Capsule manager. This allows you to configure connections, set up an event dispatcher, and boot the Eloquent ORM.

    Note: If you intend to use Eloquent observers, you must also install the events package: composer require "illuminate/events".

    use Illuminate\Database\Capsule\Manager as Capsule;
    
    $capsule = new Capsule;
    
    $capsule->addConnection([
        'driver' => 'mysql',
        'host' => 'localhost',
        'database' => 'database',
        'username' => 'root',
        'password' => 'password',
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
    ]);
    
    // Set the event dispatcher used by Eloquent models... (optional)
    use Illuminate\Events\Dispatcher;
    use Illuminate\Container\Container;
    $capsule->setEventDispatcher(new Dispatcher(new Container));
    
    // Make this Capsule instance available globally via static methods... (optional)
    $capsule->setAsGlobal();
    
    // Setup the Eloquent ORM... (optional; unless you've used setEventDispatcher())
    $capsule->bootEloquent();
  5. Access Batch properties and callbacks via options

    13.x

    The Batch class uses an options array to store configuration and callback handlers. You can access these options dynamically as properties on the Batch instance.

    Supported Callback Types

    When creating a batch (typically via the Bus facade), you can define the following callbacks:

    • progress: Executed as jobs are processed.
    • then: Executed when the batch successfully finishes.
    • finally: Executed when all jobs have run exactly once, regardless of success or failure.
    • catch: Executed when a job fails and the batch is configured to catch errors.
    • failure: Executed when a job fails (if allowFailures is enabled).

    Configuration Options

    • allowFailures: (boolean) If set to true, individual job failures will not cancel the entire batch.
    • queue: The specific queue to use for jobs added to this batch.
    • connection: The database connection to use for the batch.
  6. Prevent overlapping scheduled tasks

    13.x

    To prevent a scheduled task from running if a previous instance is still active, use the withoutOverlapping() method (provided via the ManagesFrequencies trait used in Event).

    Customizing Mutex Behavior

    By default, Laravel uses a mutex to track overlapping tasks. You can customize how this works:

    • preventOverlapsUsing(EventMutex $mutex): Use a custom mutex implementation.
    • createMutexNameUsing(Closure|string $mutexName): Define a custom name or a resolver callback for the mutex.

    If the task is skipped because of an overlap, the skippedBecauseOverlapping property on the Event instance will be set to true.

  7. How Gate, Policies, and Callbacks work together

    13.x

    The Gate manages the authorization lifecycle through several layers:

    1. Before Callbacks: The Gate first executes all registered before callbacks. If any return a non-null value, that result is returned immediately.
    2. Ability/Policy Resolution: If no before callback intervenes, the Gate looks for a defined ability. If the ability is associated with a class (via resource or policy), it resolves the appropriate Policy class.
    3. Policy before Method: If a Policy is used, the Gate calls the Policy's own before method. If it returns a non-null value, that result is used.
    4. Policy Method: The Gate then calls the specific method on the Policy corresponding to the ability (e.g., update for the update ability).
    5. After Callbacks: Finally, all registered after callbacks are executed, allowing for side effects like logging.
  8. Format and style console output with OutputStyle

    13.x

    The Illuminate\Console\OutputStyle class extends Symfony's SymfonyStyle to provide advanced console output formatting and styling. It is primarily used within Laravel commands to render consistent, beautiful CLI interfaces (such as success blocks, error blocks, tables, and progress bars) while tracking newline state to manage spacing between outputs.

    Key features include:

    • Styling: Inherits all high-level styling methods from SymfonyStyle (e.g., info(), error(), success(), warn(), table()).
    • Verbosity Control: Provides helper methods to check the current verbosity level of the command.
    • Newline Tracking: Implements NewLineAware to track how many trailing newlines were written by the last output operation, allowing for smarter spacing management.
  9. Monitor and manage job batches with the Batch class

    13.x

    The Illuminate\Bus\Batch class represents a collection of queued jobs that are processed together. It allows you to track the progress of a group of jobs, handle failures, and execute callbacks when specific batch milestones are reached (e.g., when the batch finishes, fails, or makes progress).

    Key Properties

    • id: The unique identifier for the batch.
    • totalJobs: Total number of jobs in the batch.
    • pendingJobs: Number of jobs yet to be processed.
    • failedJobs: Number of jobs that have failed.
    • failedJobIds: Array of IDs for jobs that failed.
    • progress(): Returns the percentage of completion (0-100).
    • finished(): Returns true if the batch has completed.
    • canceled(): Returns true if the batch was cancelled.

    Common Tasks

    Refresh batch data

    If you have an existing batch instance and want to get the most up-to-date state from the database, use fresh().

    Add jobs to an existing batch

    You can add more jobs to a batch using the add() method. This method supports single jobs, arrays of jobs, or job chains.

    Cancel a batch

    Use cancel() to stop the batch. If the batch does not allow failures (via the allowFailures option), a single job failure will trigger this automatically.

  10. Use the Failover Cache Store

    13.x

    The FailoverStore allows you to define a sequence of cache stores to use as fallbacks. When performing a cache operation, the FailoverStore attempts the action on the first store in the list. If that store fails (throws a Throwable), the error is caught, a CacheFailedOver event is dispatched, and the operation is automatically retried on the next store in the sequence. This continues until a store succeeds or all stores in the list have failed.

    If all stores fail, a RuntimeException is thrown with the message: All failover cache stores failed.

  11. Execute callbacks after a scheduled task

    13.x

    Laravel allows you to register callbacks that run at different stages of a scheduled event's lifecycle.

    Lifecycle Hooks

    • before(Closure $callback): Runs before the command starts.
    • after(Closure $callback): Runs after the command finishes. This is an alias for then().
    • then(Closure $callback): Runs after the command finishes. If the callback type-hints Illuminate\Support\Stringable, it will receive the command's output.
    • onSuccess(Closure $callback): Runs only if the command exits with a status code of 0.
    • onFailure(Closure $callback): Runs only if the command exits with a non-zero status code.

    Accessing Command Output in Callbacks

    If your callback type-hints Illuminate\Support\Stringable, Laravel will inject the command's output into the callback. This requires that output is being captured (via storeOutput() or sendOutputTo()).

    $schedule->command('report:generate')
        ->daily()
        ->storeOutput()
        ->then(function (Stringable $output) {
            // $output contains the command's output
        });