bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 10] 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 10] Explain reverb: Laravel Reverb

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

<a name="introduction"></a>
[Laravel 10] Explain reverb: Installation

> [!WARNING]  
> Laravel Reverb requires PHP 8.2+ and Laravel 10.47+.

You may use the Composer package manager to install Reverb into your Laravel project:

Once the package is installed, you may run Reverb's installation command to publish the configuration, add Reverb's required environment variables, and enable event broadcasting in your application:

<a name="configuration"></a>
[Laravel 10] Explain routing: Routing

- Basic Routing
    - Redirect Routes
    - View Routes
    - The Route List
- 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 10] 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 your application's App\Providers\RouteServiceProvider. 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. The routes in routes/api.php are stateless and are assigned the api middleware group.

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']);

Routes defined in the routes/api.php file are nested within a route group by the RouteServiceProvider. Within this group, the /api URI prefix is automatically applied so you do not need to manually apply it to every route in the file. You may modify the prefix and other route group options by modifying your RouteServiceProvider class.

<a name="available-router-methods"></a>
[Laravel 10] 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 10] Explain routing: Dependency Injection

You may type-hint any dependencies required by your route in your route's callback signature. The declared dependencies will automatically be resolved and injected into the callback by the Laravel service container. For example, you may type-hint the Illuminate\Http\Request class to have the current HTTP request automatically injected into your route callback:

    use Illuminate\Http\Request;

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

<a name="csrf-protection"></a>
[Laravel 10] Explain sail: Laravel Sail

- Introduction
- Installation and Setup
    - Installing Sail Into Existing Applications
    - 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
    - Redis
    - 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 10] 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 10] 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 10] 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 10] 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 at 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 10] 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 a SPA created using Vue CLI or a Next.js application.

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 10] 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
- Running the Scheduler
    - Sub-Minute Scheduled Tasks
    - Running the Scheduler Locally
- Task Output
- Task Hooks
- Events

<a name="introduction"></a>
[Laravel 10] 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 defined in the app/Console/Kernel.php file's schedule method. To help you get started, a simple example is defined within the method.

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

You may define all of your scheduled tasks in the schedule method of your application's App\Console\Kernel class. 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

    namespace App\Console;

    use Illuminate\Console\Scheduling\Schedule;
    use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
    use Illuminate\Support\Facades\DB;

    class Kernel extends ConsoleKernel
    {
        /**
         * Define the application's command schedule.
         */
        protected function schedule(Schedule $schedule): void
        {
            $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 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>
[Laravel 10] Explain scheduling: Scheduling Artisan Commands

In addition to scheduling closures, you may also schedule Artisan commands and system commands. For example, you may use the command method to schedule an Artisan command using either the command's name or class.

When scheduling Artisan commands using the command's class name, you may pass an array of additional command-line arguments that should be provided to the command when it is invoked:

    use App\Console\Commands\SendEmailsCommand;

    $schedule->command('emails:send Taylor --force')->daily();

    $schedule->command(SendEmailsCommand::class, ['Taylor', '--force'])->daily();

<a name="scheduling-queued-jobs"></a>
[Laravel 10] Explain scheduling: Scheduling Queued Jobs

The job method may be used to schedule a queued job. This method provides a convenient way to schedule queued jobs without using the call method to define closures to queue the job:

    use App\Jobs\Heartbeat;

    $schedule->job(new Heartbeat)->everyFiveMinutes();

Optional second and third arguments may be provided to the job method which specifies the queue name and queue connection that should be used to queue the job:

    use App\Jobs\Heartbeat;

    // Dispatch the job to the "heartbeats" queue on the "sqs" connection...
    $schedule->job(new Heartbeat, 'heartbeats', 'sqs')->everyFiveMinutes();

<a name="scheduling-shell-commands"></a>
[Laravel 10] Explain scout: Laravel Scout

- Introduction
- Installation
    - Queueing
- Driver Prerequisites
    - Algolia
    - Meilisearch
    - Typesense
- Configuration
    - Configuring Model Indexes
    - Configuring Searchable Data
    - Configuring the Model ID
    - Configuring Search Engines per Model
    - Identifying Users
- Database / Collection Engines
    - Database Engine
    - Collection Engine
- Indexing
    - Batch Import
    - Adding Records
    - Updating Records
    - Removing Records
    - Pausing Indexing
    - Conditionally Searchable Model Instances
- Searching
    - Where Clauses
    - Pagination
    - Soft Deleting
    - Customizing Engine Searches
- Custom Engines

<a name="introduction"></a>
[Laravel 10] Explain scout: Introduction

Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.

Currently, Scout ships with Algolia, Meilisearch, Typesense, and MySQL / PostgreSQL (database) drivers. In addition, Scout includes a "collection" driver that is designed for local development usage and does not require any external dependencies or third-party services. Furthermore, writing custom drivers is simple and you are free to extend Scout with your own search implementations.

<a name="installation"></a>
[Laravel 10] Explain scout: Installation

First, install Scout via the Composer package manager:

After installing Scout, you should publish the Scout configuration file using the vendor:publish Artisan command. This command will publish the scout.php configuration file to your application's config directory:

Finally, add the Laravel\Scout\Searchable trait to the model you would like to make searchable. This trait will register a model observer that will automatically keep the model in sync with your search driver:

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;
    use Laravel\Scout\Searchable;

    class Post extends Model
    {
        use Searchable;
    }

<a name="queueing"></a>
[Laravel 10] Explain scout: Queueing

While not strictly required to use Scout, you should strongly consider configuring a queue driver before using the library. Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface.

Once you have configured a queue driver, set the value of the queue option in your config/scout.php configuration file to true:

    'queue' => true,

Even when the queue option is set to false, it's important to remember that some Scout drivers like Algolia and Meilisearch always index records asynchronously. Meaning, even though the index operation has completed within your Laravel application, the search engine itself may not reflect the new and updated records immediately.

To specify the connection and queue that your Scout jobs utilize, you may define the queue configuration option as an array:

    'queue' => [
        'connection' => 'redis',
        'queue' => 'scout'
    ],

Of course, if you customize the connection and queue that Scout jobs utilize, you should run a queue worker to process jobs on that connection and queue:

    php artisan queue:work redis --queue=scout

<a name="driver-prerequisites"></a>
[Laravel 10] Explain seeding: Introduction

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

> [!NOTE]  
> Mass assignment protection is automatically disabled during database seeding.

<a name="writing-seeders"></a>
[Laravel 10] Explain seeding: Writing Seeders

To generate a seeder, execute the make:seeder Artisan command. All seeders generated by the framework will be placed in the database/seeders directory:

A seeder class only contains one method by default: run. This method is called when the db:seed Artisan command is executed. Within the run method, you may insert data into your database however you wish. You may use the query builder to manually insert data or you may use Eloquent model factories.

As an example, let's modify the default DatabaseSeeder class and add a database insert statement to the run method:

    <?php

    namespace Database\Seeders;

    use Illuminate\Database\Seeder;
    use Illuminate\Support\Facades\DB;
    use Illuminate\Support\Facades\Hash;
    use Illuminate\Support\Str;

    class DatabaseSeeder extends Seeder
    {
        /**
         * Run the database seeders.
         */
        public function run(): void
        {
            DB::table('users')->insert([
                'name' => Str::random(10),
                'email' => Str::random(10).'@example.com',
                'password' => Hash::make('password'),
            ]);
        }
    }

> [!NOTE]  
> You may type-hint any dependencies you need within the run method's signature. They will automatically be resolved via the Laravel service container.

<a name="using-model-factories"></a>
[Laravel 10] Explain seeding: Using Model Factories

Of course, manually specifying the attributes for each model seed is cumbersome. Instead, you can use model factories to conveniently generate large amounts of database records. First, review the model factory documentation to learn how to define your factories.

For example, let's create 50 users that each has one related post:

    use App\Models\User;

    /**
     * Run the database seeders.
     */
    public function run(): void
    {
        User::factory()
                ->count(50)
                ->hasPosts(1)
                ->create();
    }

<a name="calling-additional-seeders"></a>
[Laravel 10] Explain seeding: Calling Additional Seeders

Within the DatabaseSeeder class, you may use the call method to execute additional seed classes. Using the call method allows you to break up your database seeding into multiple files so that no single seeder class becomes too large. The call method accepts an array of seeder classes that should be executed:

    /**
     * Run the database seeders.
     */
    public function run(): void
    {
        $this->call([
            UserSeeder::class,
            PostSeeder::class,
            CommentSeeder::class,
        ]);
    }

<a name="muting-model-events"></a>
[Laravel 10] Explain session: HTTP Session

- Introduction
    - Configuration
    - Driver Prerequisites
- Interacting With the Session
    - Retrieving Data
    - Storing Data
    - Flash Data
    - Deleting Data
    - Regenerating the Session ID
- Session Blocking
- Adding Custom Session Drivers
    - Implementing the Driver
    - Registering the Driver

<a name="introduction"></a>
[Laravel 10] Explain session: Configuration

Your application's session configuration file is stored at config/session.php. Be sure to review the options available to you in this file. By default, Laravel is configured to use the file session driver, which will work well for many applications. If your application will be load balanced across multiple web servers, you should choose a centralized store that all servers can access, such as Redis or a database.

The session driver configuration option defines where session data will be stored for each request. Laravel ships with several great drivers out of the box:

<div class="content-list" markdown="1">

- file - sessions are stored in storage/framework/sessions.
- cookie - sessions are stored in secure, encrypted cookies.
- database - sessions are stored in a relational database.
- memcached / redis - sessions are stored in one of these fast, cache based stores.
- dynamodb - sessions are stored in AWS DynamoDB.
- array - sessions are stored in a PHP array and will not be persisted.

</div>

> [!NOTE]  
> The array driver is primarily used during testing and prevents the data stored in the session from being persisted.

<a name="driver-prerequisites"></a>
[Laravel 10] Explain session: Database

When using the database session driver, you will need to create a table to contain the session records. An example Schema declaration for the table may be found below:

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

    Schema::create('sessions', function (Blueprint $table) {
        $table->string('id')->primary();
        $table->foreignId('user_id')->nullable()->index();
        $table->string('ip_address', 45)->nullable();
        $table->text('user_agent')->nullable();
        $table->text('payload');
        $table->integer('last_activity')->index();
    });

You may use the session:table Artisan command to generate this migration. To learn more about database migrations, you may consult the complete migration documentation:

<a name="redis"></a>
[Laravel 10] Explain session: Redis

Before using Redis sessions with Laravel, you will need to either install the PhpRedis PHP extension via PECL or install the predis/predis package (~1.0) via Composer. For more information on configuring Redis, consult Laravel's Redis documentation.

> [!NOTE]  
> In the session configuration file, the connection option may be used to specify which Redis connection is used by the session.

<a name="interacting-with-the-session"></a>
[Laravel 10] Explain socialite: Introduction

In addition to typical, form based authentication, Laravel also provides a simple, convenient way to authenticate with OAuth providers using Laravel Socialite. Socialite currently supports authentication via Facebook, Twitter, LinkedIn, Google, GitHub, GitLab, Bitbucket, and Slack.

> [!NOTE]  
> Adapters for other platforms are available via the community driven Socialite Providers website.

<a name="installation"></a>