bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 11] Explain redis: Configuration

You may configure your application's Redis settings via the config/database.php configuration file. Within this file, you will see a redis array containing the Redis servers utilized by your application:

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_DB', '0'),
        ],

        'cache' => [
            'url' => env('REDIS_URL'),
            'host' => env('REDIS_HOST', '127.0.0.1'),
            'username' => env('REDIS_USERNAME'),
            'password' => env('REDIS_PASSWORD'),
            'port' => env('REDIS_PORT', '6379'),
            'database' => env('REDIS_CACHE_DB', '1'),
        ],

    ],

Each Redis server defined in your configuration file is required to have a name, host, and a port unless you define a single URL to represent the Redis connection:

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'default' => [
            'url' => 'tcp://127.0.0.1:6379?database=0',
        ],

        'cache' => [
            'url' => 'tls://user:password@127.0.0.1:6380?database=1',
        ],

    ],

<a name="configuring-the-connection-scheme"></a>
[Laravel 11] Explain redis: Configuring the Connection Scheme

By default, Redis clients will use the tcp scheme when connecting to your Redis servers; however, you may use TLS / SSL encryption by specifying a scheme configuration option in your Redis server's configuration array:

    'default' => [
        'scheme' => 'tls',
        'url' => env('REDIS_URL'),
        'host' => env('REDIS_HOST', '127.0.0.1'),
        'username' => env('REDIS_USERNAME'),
        'password' => env('REDIS_PASSWORD'),
        'port' => env('REDIS_PORT', '6379'),
        'database' => env('REDIS_DB', '0'),
    ],

<a name="clusters"></a>
[Laravel 11] Explain redis: Clusters

If your application is utilizing a cluster of Redis servers, you should define these clusters within a clusters key of your Redis configuration. This configuration key does not exist by default so you will need to create it within your application's config/database.php configuration file:

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'options' => [
            'cluster' => env('REDIS_CLUSTER', 'redis'),
            'prefix' => env('REDIS_PREFIX', Str::slug(env('APP_NAME', 'laravel'), '_').'_database_'),
        ],

        'clusters' => [
            'default' => [
                [
                    'url' => env('REDIS_URL'),
                    'host' => env('REDIS_HOST', '127.0.0.1'),
                    'username' => env('REDIS_USERNAME'),
                    'password' => env('REDIS_PASSWORD'),
                    'port' => env('REDIS_PORT', '6379'),
                    'database' => env('REDIS_DB', '0'),
                ],
            ],
        ],

        // ...
    ],

By default, Laravel will use native Redis clustering since the options.cluster configuration value is set to redis. Redis clustering is a great default option, as it gracefully handles failover.

Laravel also supports client-side sharding when using Predis. However, client-side sharding does not handle failover; therefore, it is primarily suited for transient cached data that is available from another primary data store.

If you would like to use client-side sharding instead of native Redis clustering, you may remove the options.cluster configuration value within your application's config/database.php configuration file:

    'redis' => [

        'client' => env('REDIS_CLIENT', 'phpredis'),

        'clusters' => [
            // ...
        ],

        // ...
    ],

<a name="predis"></a>
[Laravel 11] Explain releases: Versioning Scheme

Laravel and its other first-party packages follow Semantic Versioning. Major framework releases are released every year (~Q1), while minor and patch releases may be released as often as every week. Minor and patch releases should **never** contain breaking changes.

When referencing the Laravel framework or its components from your application or package, you should always use a version constraint such as ^11.0, since major releases of Laravel do include breaking changes. However, we strive to always ensure you may update to a new major release in one day or less.

<a name="named-arguments"></a>
[Laravel 11] Explain releases: Support Policy

For all Laravel releases, bug fixes are provided for 18 months and security fixes are provided for 2 years. For all additional libraries, including Lumen, only the latest major release receives bug fixes. In addition, please review the database versions supported by Laravel.

<div class="overflow-auto">

| Version | PHP (*) | Release | Bug Fixes Until | Security Fixes Until |
| --- | --- | --- | --- | --- |
| 9 | 8.0 - 8.2 | February 8th, 2022 | August 8th, 2023 | February 6th, 2024 |
| 10 | 8.1 - 8.3 | February 14th, 2023 | August 6th, 2024 | February 4th, 2025 |
| 11 | 8.2 - 8.4 | March 12th, 2024 | September 3rd, 2025 | March 12th, 2026 |
| 12 | 8.2 - 8.4 | February 24th, 2025 | August 13th, 2026 | February 24th, 2027 |

</div>

<div class="version-colors">
    <div class="end-of-life">
        <div class="color-box"></div>
        <div>End of life</div>
    </div>
    <div class="security-fixes">
        <div class="color-box"></div>
        <div>Security fixes only</div>
    </div>
</div>

(*) Supported PHP versions

<a name="laravel-11"></a>
[Laravel 11] Explain releases: Laravel 11

Laravel 11 continues the improvements made in Laravel 10.x by introducing a streamlined application structure, per-second rate limiting, health routing, graceful encryption key rotation, queue testing improvements, Resend mail transport, Prompt validator integration, new Artisan commands, and more. In addition, Laravel Reverb, a first-party, scalable WebSocket server has been introduced to provide robust real-time capabilities to your applications.

<a name="php-8"></a>
[Laravel 11] Explain requests: HTTP Requests

- Introduction
- Interacting With The Request
    - Accessing the Request
    - Request Path, Host, and Method
    - Request Headers
    - Request IP Address
    - Content Negotiation
    - PSR-7 Requests
- Input
    - Retrieving Input
    - Input Presence
    - Merging Additional Input
    - Old Input
    - Cookies
    - Input Trimming and Normalization
- Files
    - Retrieving Uploaded Files
    - Storing Uploaded Files
- Configuring Trusted Proxies
- Configuring Trusted Hosts

<a name="introduction"></a>
[Laravel 11] Explain requests: Accessing the Request

To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your route closure or controller method. The incoming request instance will automatically be injected by the Laravel service container:

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\RedirectResponse;
    use Illuminate\Http\Request;

    class UserController extends Controller
    {
        /**
         * Store a new user.
         */
        public function store(Request $request): RedirectResponse
        {
            $name = $request->input('name');

            // Store the user...

            return redirect('/users');
        }
    }

As mentioned, you may also type-hint the Illuminate\Http\Request class on a route closure. The service container will automatically inject the incoming request into the closure when it is executed:

    use Illuminate\Http\Request;

    Route::get('/', function (Request $request) {
        // ...
    });

<a name="dependency-injection-route-parameters"></a>
[Laravel 11] Explain requests: Dependency Injection and Route Parameters

If your controller method is also expecting input from a route parameter you should list your route parameters after your other dependencies. For example, if your route is defined like so:

    use App\Http\Controllers\UserController;

    Route::put('/user/{id}', [UserController::class, 'update']);

You may still type-hint the Illuminate\Http\Request and access your id route parameter by defining your controller method as follows:

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\RedirectResponse;
    use Illuminate\Http\Request;

    class UserController extends Controller
    {
        /**
         * Update the specified user.
         */
        public function update(Request $request, string $id): RedirectResponse
        {
            // Update the user...

            return redirect('/users');
        }
    }

<a name="request-path-and-method"></a>
[Laravel 11] Explain responses: HTTP Responses

- Creating Responses
    - Attaching Headers to Responses
    - Attaching Cookies to Responses
    - Cookies and Encryption
- Redirects
    - Redirecting to Named Routes
    - Redirecting to Controller Actions
    - Redirecting to External Domains
    - Redirecting With Flashed Session Data
- Other Response Types
    - View Responses
    - JSON Responses
    - File Downloads
    - File Responses
    - Streamed Responses
- Response Macros

<a name="creating-responses"></a>
[Laravel 11] Explain responses: Strings and Arrays

All routes and controllers should return a response to be sent back to the user's browser. Laravel provides several different ways to return responses. The most basic response is returning a string from a route or controller. The framework will automatically convert the string into a full HTTP response:

    Route::get('/', function () {
        return 'Hello World';
    });

In addition to returning strings from your routes and controllers, you may also return arrays. The framework will automatically convert the array into a JSON response:

    Route::get('/', function () {
        return [1, 2, 3];
    });

> [!NOTE]  
> Did you know you can also return Eloquent collections from your routes or controllers? They will automatically be converted to JSON. Give it a shot!

<a name="response-objects"></a>
[Laravel 11] Explain responses: Response Objects

Typically, you won't just be returning simple strings or arrays from your route actions. Instead, you will be returning full Illuminate\Http\Response instances or views.

Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, which provides a variety of methods for building HTTP responses:

    Route::get('/home', function () {
        return response('Hello World', 200)
            ->header('Content-Type', 'text/plain');
    });

<a name="eloquent-models-and-collections"></a>
[Laravel 11] Explain responses: Eloquent Models and Collections

You may also return Eloquent ORM models and collections directly from your routes and controllers. When you do, Laravel will automatically convert the models and collections to JSON responses while respecting the model's hidden attributes:

    use App\Models\User;

    Route::get('/user/{user}', function (User $user) {
        return $user;
    });

<a name="attaching-headers-to-responses"></a>
[Laravel 11] Explain responses: Attaching Headers to Responses

Keep in mind that most response methods are chainable, allowing for the fluent construction of response instances. For example, you may use the header method to add a series of headers to the response before sending it back to the user:

    return response($content)
        ->header('Content-Type', $type)
        ->header('X-Header-One', 'Header Value')
        ->header('X-Header-Two', 'Header Value');

Or, you may use the withHeaders method to specify an array of headers to be added to the response:

    return response($content)
        ->withHeaders([
            'Content-Type' => $type,
            'X-Header-One' => 'Header Value',
            'X-Header-Two' => 'Header Value',
        ]);

<a name="cache-control-middleware"></a>
[Laravel 11] Explain reverb: Laravel Reverb

- Introduction
- Installation
- Configuration
    - Application Credentials
    - Allowed Origins
    - Additional Applications
    - SSL
- Running the Server
    - Debugging
    - Restarting
- Monitoring
- Running Reverb in Production
    - Open Files
    - Event Loop
    - Web Server
    - Ports
    - Process Management
    - Scaling

<a name="introduction"></a>
[Laravel 11] Explain routing: Routing

- Basic Routing
    - The Default Route Files
    - Redirect Routes
    - View Routes
    - Listing Your Routes
    - Routing Customization
- Route Parameters
    - Required Parameters
    - Optional Parameters
    - Regular Expression Constraints
- Named Routes
- Route Groups
    - Middleware
    - Controllers
    - Subdomain Routing
    - Route Prefixes
    - Route Name Prefixes
- Route Model Binding
    - Implicit Binding
    - Implicit Enum Binding
    - Explicit Binding
- Fallback Routes
- Rate Limiting
    - Defining Rate Limiters
    - Attaching Rate Limiters to Routes
- Form Method Spoofing
- Accessing the Current Route
- Cross-Origin Resource Sharing (CORS)
- Route Caching

<a name="basic-routing"></a>
[Laravel 11] Explain routing: The Default Route Files

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by Laravel using the configuration specified in your application's bootstrap/app.php file. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection.

For most applications, you will begin by defining routes in your routes/web.php file. The routes defined in routes/web.php may be accessed by entering the defined route's URL in your browser. For example, you may access the following route by navigating to http://example.com/user in your browser:

    use App\Http\Controllers\UserController;

    Route::get('/user', [UserController::class, 'index']);

<a name="api-routes"></a>
[Laravel 11] Explain routing: API Routes

If your application will also offer a stateless API, you may enable API routing using the install:api Artisan command:

The install:api command installs Laravel Sanctum, which provides a robust, yet simple API token authentication guard which can be used to authenticate third-party API consumers, SPAs, or mobile applications. In addition, the install:api command creates the routes/api.php file:

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

The routes in routes/api.php are stateless and are assigned to the api middleware group. Additionally, the /api URI prefix is automatically applied to these routes, so you do not need to manually apply it to every route in the file. You may change the prefix by modifying your application's bootstrap/app.php file:

    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        apiPrefix: 'api/admin',
        // ...
    )

<a name="available-router-methods"></a>
[Laravel 11] Explain routing: Available Router Methods

The router allows you to register routes that respond to any HTTP verb:

    Route::get($uri, $callback);
    Route::post($uri, $callback);
    Route::put($uri, $callback);
    Route::patch($uri, $callback);
    Route::delete($uri, $callback);
    Route::options($uri, $callback);

Sometimes you may need to register a route that responds to multiple HTTP verbs. You may do so using the match method. Or, you may even register a route that responds to all HTTP verbs using the any method:

    Route::match(['get', 'post'], '/', function () {
        // ...
    });

    Route::any('/', function () {
        // ...
    });

> [!NOTE]  
> When defining multiple routes that share the same URI, routes using the get, post, put, patch, delete, and options methods should be defined before routes using the any, match, and redirect methods. This ensures the incoming request is matched with the correct route.

<a name="dependency-injection"></a>
[Laravel 11] Explain sail: Laravel Sail

- Introduction
- Installation and Setup
    - Installing Sail Into Existing Applications
    - Rebuilding Sail Images
    - Configuring A Shell Alias
- Starting and Stopping Sail
- Executing Commands
    - Executing PHP Commands
    - Executing Composer Commands
    - Executing Artisan Commands
    - Executing Node / NPM Commands
- Interacting With Databases
    - MySQL
    - MongoDB
    - Redis
    - Valkey
    - Meilisearch
    - Typesense
- File Storage
- Running Tests
    - Laravel Dusk
- Previewing Emails
- Container CLI
- PHP Versions
- Node Versions
- Sharing Your Site
- Debugging With Xdebug
  - Xdebug CLI Usage
  - Xdebug Browser Usage
- Customization

<a name="introduction"></a>
[Laravel 11] Explain sail: Introduction

Laravel Sail is a light-weight command-line interface for interacting with Laravel's default Docker development environment. Sail provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience.

At its heart, Sail is the docker-compose.yml file and the sail script that is stored at the root of your project. The sail script provides a CLI with convenient methods for interacting with the Docker containers defined by the docker-compose.yml file.

Laravel Sail is supported on macOS, Linux, and Windows (via WSL2).

<a name="installation"></a>
[Laravel 11] Explain sail: Installing Sail Into Existing Applications

If you are interested in using Sail with an existing Laravel application, you may simply install Sail using the Composer package manager. Of course, these steps assume that your existing local development environment allows you to install Composer dependencies:

After Sail has been installed, you may run the sail:install Artisan command. This command will publish Sail's docker-compose.yml file to the root of your application and modify your .env file with the required environment variables in order to connect to the Docker services:

Finally, you may start Sail. To continue learning how to use Sail, please continue reading the remainder of this documentation:

> [!WARNING]  
> If you are using Docker Desktop for Linux, you should use the default Docker context by executing the following command: docker context use default.

<a name="adding-additional-services"></a>
[Laravel 11] Explain sanctum: Laravel Sanctum

- Introduction
    - How it Works
- Installation
- Configuration
    - Overriding Default Models
- API Token Authentication
    - Issuing API Tokens
    - Token Abilities
    - Protecting Routes
    - Revoking Tokens
    - Token Expiration
- SPA Authentication
    - Configuration
    - Authenticating
    - Protecting Routes
    - Authorizing Private Broadcast Channels
- Mobile Application Authentication
    - Issuing API Tokens
    - Protecting Routes
    - Revoking Tokens
- Testing

<a name="introduction"></a>
[Laravel 11] Explain sanctum: API Tokens

First, Sanctum is a simple package you may use to issue API tokens to your users without the complication of OAuth. This feature is inspired by GitHub and other applications which issue "personal access tokens". For example, imagine the "account settings" of your application has a screen where a user may generate an API token for their account. You may use Sanctum to generate and manage those tokens. These tokens typically have a very long expiration time (years), but may be manually revoked by the user anytime.

Laravel Sanctum offers this feature by storing user API tokens in a single database table and authenticating incoming HTTP requests via the Authorization header which should contain a valid API token.

<a name="how-it-works-spa-authentication"></a>
[Laravel 11] Explain sanctum: SPA Authentication

Second, Sanctum exists to offer a simple way to authenticate single page applications (SPAs) that need to communicate with a Laravel powered API. These SPAs might exist in the same repository as your Laravel application or might be an entirely separate repository, such as an SPA created using Next.js or Nuxt.

For this feature, Sanctum does not use tokens of any kind. Instead, Sanctum uses Laravel's built-in cookie based session authentication services. Typically, Sanctum utilizes Laravel's web authentication guard to accomplish this. This provides the benefits of CSRF protection, session authentication, as well as protects against leakage of the authentication credentials via XSS.

Sanctum will only attempt to authenticate using cookies when the incoming request originates from your own SPA frontend. When Sanctum examines an incoming HTTP request, it will first check for an authentication cookie and, if none is present, Sanctum will then examine the Authorization header for a valid API token.

> [!NOTE]  
> It is perfectly fine to use Sanctum only for API token authentication or only for SPA authentication. Just because you use Sanctum does not mean you are required to use both features it offers.

<a name="installation"></a>
[Laravel 11] Explain scheduling: Task Scheduling

- Introduction
- Defining Schedules
    - Scheduling Artisan Commands
    - Scheduling Queued Jobs
    - Scheduling Shell Commands
    - Schedule Frequency Options
    - Timezones
    - Preventing Task Overlaps
    - Running Tasks on One Server
    - Background Tasks
    - Maintenance Mode
    - Schedule Groups
- Running the Scheduler
    - Sub-Minute Scheduled Tasks
    - Running the Scheduler Locally
- Task Output
- Task Hooks
- Events

<a name="introduction"></a>
[Laravel 11] Explain scheduling: Introduction

In the past, you may have written a cron configuration entry for each task you needed to schedule on your server. However, this can quickly become a pain because your task schedule is no longer in source control and you must SSH into your server to view your existing cron entries or add additional entries.

Laravel's command scheduler offers a fresh approach to managing scheduled tasks on your server. The scheduler allows you to fluently and expressively define your command schedule within your Laravel application itself. When using the scheduler, only a single cron entry is needed on your server. Your task schedule is typically defined in your application's routes/console.php file.

<a name="defining-schedules"></a>
[Laravel 11] Explain scheduling: Defining Schedules

You may define all of your scheduled tasks in your application's routes/console.php file. To get started, let's take a look at an example. In this example, we will schedule a closure to be called every day at midnight. Within the closure we will execute a database query to clear a table:

    <?php

    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Schedule;

    Schedule::call(function () {
        DB::table('recent_users')->delete();
    })->daily();

In addition to scheduling using closures, you may also schedule invokable objects. Invokable objects are simple PHP classes that contain an __invoke method:

    Schedule::call(new DeleteRecentUsers)->daily();

If you prefer to reserve your routes/console.php file for command definitions only, you may use the withSchedule method in your application's bootstrap/app.php file to define your scheduled tasks. This method accepts a closure that receives an instance of the scheduler:

    use Illuminate\Console\Scheduling\Schedule;

    ->withSchedule(function (Schedule $schedule) {
        $schedule->call(new DeleteRecentUsers)->daily();
    })

If you would like to view an overview of your scheduled tasks and the next time they are scheduled to run, you may use the schedule:list Artisan command:

<a name="scheduling-artisan-commands"></a>