bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 13] Explain container: When to Utilize the Container

Thanks to zero configuration resolution, you will often type-hint dependencies on routes, controllers, event listeners, and elsewhere without ever manually interacting with the container. For example, you might type-hint the Illuminate\Http\Request object on your route definition so that you can easily access the current request. Even though we never have to interact with the container to write this code, it is managing the injection of these dependencies behind the scenes:

In many cases, thanks to automatic dependency injection and facades, you can build Laravel applications without **ever** manually binding or resolving anything from the container. **So, when would you ever manually interact with the container?** Let's examine two situations.

First, if you write a class that implements an interface and you wish to type-hint that interface on a route or class constructor, you must tell the container how to resolve that interface. Secondly, if you are writing a Laravel package that you plan to share with other Laravel developers, you may need to bind your package's services into the container.

<a name="binding"></a>
[Laravel 13] Explain container: Simple Bindings

Almost all of your service container bindings will be registered within service providers, so most of these examples will demonstrate using the container in that context.

Within a service provider, you always have access to the container via the $this->app property. We can register a binding using the bind method, passing the class or interface name that we wish to register along with a closure that returns an instance of the class:

Note that we receive the container itself as an argument to the resolver. We can then use the container to resolve sub-dependencies of the object we are building.

As mentioned, you will typically be interacting with the container within service providers; however, if you would like to interact with the container outside of a service provider, you may do so via the App facade:

You may use the bindIf method to register a container binding only if a binding has not already been registered for the given type:

For convenience, you may omit providing the class or interface name that you wish to register as a separate argument and instead allow Laravel to infer the type from the return type of the closure you provide to the bind method:

> [!NOTE]
> There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.

<a name="binding-a-singleton"></a>
[Laravel 13] Explain context: How it Works

The best way to understand Laravel's context capabilities is to see it in action using  the built-in logging features. To get started, you may add information to the context using the Context facade. In this example, we will use a middleware to add the request URL and a unique trace ID to the context on every incoming request:

Information added to the context is automatically appended as metadata to any log entries that are written throughout the request. Appending context as metadata allows information passed to individual log entries to be differentiated from the information shared via Context. For example, imagine we write the following log entry:

The written log will contain the auth_id passed to the log entry, but it will also contain the context's url and trace_id as metadata:

Information added to the context is also made available to jobs dispatched to the queue. For example, imagine we dispatch a ProcessPodcast job to the queue after adding some information to the context:

When the job is dispatched, any information currently stored in the context is captured and shared with the job. The captured information is then hydrated back into the current context while the job is executing. So, if our job's handle method was to write to the log:

The resulting log entry would contain the information that was added to the context during the request that originally dispatched the job:

Although we have focused on the built-in logging related features of Laravel's context, the following documentation will illustrate how context allows you to share information across the HTTP request / queued job boundary and even how to add hidden context data that is not written with log entries.

<a name="capturing-context"></a>
[Laravel 13] Explain context: Capturing Context

You may store information in the current context using the Context facade's add method:

To add multiple items at once, you may pass an associative array to the add method:

The add method will override any existing value that shares the same key. If you only wish to add information to the context if the key does not already exist, you may use the addIf method:

Context also provides convenient methods for incrementing or decrementing a given key. Both of these methods accept at least one argument: the key to track. A second argument may be provided to specify the amount by which the key should be incremented or decremented:

<a name="conditional-context"></a>
[Laravel 13] Explain context: Scoped Context

The scope method provides a way to temporarily modify the context during the execution of a given callback and restore the context to its original state when the callback finishes executing. Additionally, you can pass extra data that should be merged into the context (as the second and third arguments) while the closure executes.

> [!WARNING]
> If an object within the context is modified inside the scoped closure, that mutation will be reflected outside of the scope.

<a name="stacks"></a>
[Laravel 13] Explain contracts: Introduction

Laravel's "contracts" are a set of interfaces that define the core services provided by the framework. For example, an Illuminate\Contracts\Queue\Queue contract defines the methods needed for queueing jobs, while the Illuminate\Contracts\Mail\Mailer contract defines the methods needed for sending e-mail.

Each contract has a corresponding implementation provided by the framework. For example, Laravel provides a queue implementation with a variety of drivers, and a mailer implementation that is powered by Symfony Mailer.

All of the Laravel contracts live in their own GitHub repository. This provides a quick reference point for all available contracts, as well as a single, decoupled package that may be utilized when building packages that interact with Laravel services.

<a name="contracts-vs-facades"></a>
[Laravel 13] Explain contracts: Contracts vs. Facades

Laravel's facades and helper functions provide a simple way of utilizing Laravel's services without needing to type-hint and resolve contracts out of the service container. In most cases, each facade has an equivalent contract.

Unlike facades, which do not require you to require them in your class' constructor, contracts allow you to define explicit dependencies for your classes. Some developers prefer to explicitly define their dependencies in this way and therefore prefer to use contracts, while other developers enjoy the convenience of facades. **In general, most applications can use facades without issue during development.**

<a name="when-to-use-contracts"></a>
[Laravel 13] Explain contracts: When to Use Contracts

The decision to use contracts or facades will come down to personal taste and the tastes of your development team. Both contracts and facades can be used to create robust, well-tested Laravel applications. Contracts and facades are not mutually exclusive. Some parts of your applications may use facades while others depend on contracts. As long as you are keeping your class' responsibilities focused, you will notice very few practical differences between using contracts and facades.

In general, most applications can use facades without issue during development. If you are building a package that integrates with multiple PHP frameworks you may wish to use the illuminate/contracts package to define your integration with Laravel's services without the need to require Laravel's concrete implementations in your package's composer.json file.

<a name="how-to-use-contracts"></a>
[Laravel 13] Explain contracts: How to Use Contracts

So, how do you get an implementation of a contract? It's actually quite simple.

Many types of classes in Laravel are resolved through the service container, including controllers, event listeners, middleware, queued jobs, and even route closures. So, to get an implementation of a contract, you can just "type-hint" the interface in the constructor of the class being resolved.

For example, take a look at this event listener:

When the event listener is resolved, the service container will read the type-hints on the constructor of the class, and inject the appropriate value. To learn more about registering things in the service container, check out its documentation.

<a name="contract-reference"></a>
[Laravel 13] Explain contracts: Contract Reference

This table provides a quick reference to all of the Laravel contracts and their equivalent facades:

<div class="overflow-auto">

| Contract | References Facade |
| --- | --- |
| Illuminate\Contracts\Auth\Access\Authorizable | &nbsp; |
| Illuminate\Contracts\Auth\Access\Gate | Gate |
| Illuminate\Contracts\Auth\Authenticatable | &nbsp; |
| Illuminate\Contracts\Auth\CanResetPassword | &nbsp; |
| Illuminate\Contracts\Auth\Factory | Auth |
| Illuminate\Contracts\Auth\Guard | Auth::guard() |
| Illuminate\Contracts\Auth\PasswordBroker | Password::broker() |
| Illuminate\Contracts\Auth\PasswordBrokerFactory | Password |
| Illuminate\Contracts\Auth\StatefulGuard | &nbsp; |
| Illuminate\Contracts\Auth\SupportsBasicAuth | &nbsp; |
| Illuminate\Contracts\Auth\UserProvider | &nbsp; |
| Illuminate\Contracts\Broadcasting\Broadcaster | Broadcast::connection() |
| Illuminate\Contracts\Broadcasting\Factory | Broadcast |
| Illuminate\Contracts\Broadcasting\ShouldBroadcast | &nbsp; |
| Illuminate\Contracts\Broadcasting\ShouldBroadcastNow | &nbsp; |
| Illuminate\Contracts\Bus\Dispatcher | Bus |
| Illuminate\Contracts\Bus\QueueingDispatcher | Bus::dispatchToQueue() |
| Illuminate\Contracts\Cache\Factory | Cache |
| Illuminate\Contracts\Cache\Lock | &nbsp; |
| Illuminate\Contracts\Cache\LockProvider | &nbsp; |
| Illuminate\Contracts\Cache\Repository | Cache::driver() |
| Illuminate\Contracts\Cache\Store | &nbsp; |
| Illuminate\Contracts\Config\Repository | Config |
| Illuminate\Contracts\Console\Application | &nbsp; |
| Illuminate\Contracts\Console\Kernel | Artisan |
| Illuminate\Contracts\Container\Container | App |
| Illuminate\Contracts\Cookie\Factory | Cookie |
| Illuminate\Contracts\Cookie\QueueingFactory | Cookie::queue() |
| Illuminate\Contracts\Database\ModelIdentifier | &nbsp; |
| Illuminate\Contracts\Debug\ExceptionHandler | &nbsp; |
| Illuminate\Contracts\Encryption\Encrypter | Crypt |
| Illuminate\Contracts\Events\Dispatcher | Event |
| Illuminate\Contracts\Filesystem\Cloud
[Laravel 13] Explain controllers: Controllers

- Introduction
- Writing Controllers
    - Basic Controllers
    - Single Action Controllers
- Controller Middleware
    - Middleware Attributes
    - Authorization Attributes
- Resource Controllers
    - Partial Resource Routes
    - Nested Resources
    - Naming Resource Routes
    - Naming Resource Route Parameters
    - Scoping Resource Routes
    - Localizing Resource URIs
    - Supplementing Resource Controllers
    - Singleton Resource Controllers
    - Middleware and Resource Controllers
- Dependency Injection and Controllers

<a name="introduction"></a>
[Laravel 13] Explain controllers: Introduction

Instead of defining all of your request handling logic as closures in your route files, you may wish to organize this behavior using "controller" classes. Controllers can group related request handling logic into a single class. For example, a UserController class might handle all incoming requests related to users, including showing, creating, updating, and deleting users. By default, controllers are stored in the app/Http/Controllers directory.

<a name="writing-controllers"></a>
[Laravel 13] Explain controllers: Basic Controllers

To quickly generate a new controller, you may run the make:controller Artisan command. By default, all of the controllers for your application are stored in the app/Http/Controllers directory:

Let's take a look at an example of a basic controller. A controller may have any number of public methods which will respond to incoming HTTP requests:

Once you have written a controller class and method, you may define a route to the controller method like so:

When an incoming request matches the specified route URI, the show method on the App\Http\Controllers\UserController class will be invoked and the route parameters will be passed to the method.

> [!NOTE]
> Controllers are not **required** to extend a base class. However, it is sometimes convenient to extend a base controller class that contains methods that should be shared across all of your controllers.

<a name="single-action-controllers"></a>
[Laravel 13] Explain controllers: Single Action Controllers

If a controller action is particularly complex, you might find it convenient to dedicate an entire controller class to that single action. To accomplish this, you may define a single __invoke method within the controller:

When registering routes for single action controllers, you do not need to specify a controller method. Instead, you may simply pass the name of the controller to the router:

You may generate an invokable controller by using the --invokable option of the make:controller Artisan command:

> [!NOTE]
> Controller stubs may be customized using stub publishing.

<a name="controller-middleware"></a>
[Laravel 13] Explain controllers: Controller Middleware

Middleware may be assigned to the controller's routes in your route files:

Or, you may find it convenient to specify middleware within your controller class. To do so, your controller should implement the HasMiddleware interface, which dictates that the controller should have a static middleware method. From this method, you may return an array of middleware that should be applied to the controller's actions:

You may also define controller middleware as closures, which provides a convenient way to define an inline middleware without writing an entire middleware class:

<a name="middleware-attributes"></a>
[Laravel 13] Explain csrf: An Explanation of the Vulnerability

In case you're not familiar with cross-site request forgeries, let's discuss an example of how this vulnerability can be exploited. Imagine your application has a /user/email route that accepts a POST request to change the authenticated user's email address. Most likely, this route expects an email input field to contain the email address the user would like to begin using.

Without CSRF protection, a malicious website could create an HTML form that points to your application's /user/email route and submits the malicious user's own email address:

If the malicious website automatically submits the form when the page is loaded, the malicious user only needs to lure an unsuspecting user of your application to visit their website and their email address will be changed in your application.

To prevent this vulnerability, we need to inspect every incoming POST, PUT, PATCH, or DELETE request for a secret session value that the malicious application is unable to access.

<a name="preventing-csrf-requests"></a>
[Laravel 13] Explain csrf: Preventing CSRF Requests

The Illuminate\Foundation\Http\Middleware\PreventRequestForgery middleware, which is included in the web middleware group by default, protects your application from cross-site request forgeries using a two-layer approach.

First, the middleware checks the browser's Sec-Fetch-Site header. Modern browsers automatically set this header on every request, indicating whether it originated from the same origin, the same site, or a cross-site source. If the header indicates the request came from the same origin, the request is allowed immediately without any token verification.

If origin verification does not pass — for example, because the request comes from an older browser that doesn't send the Sec-Fetch-Site header or because the connection is not secure — the middleware falls back to traditional CSRF token validation.

Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the person actually making the requests to the application. Since this token is stored in the user's session and changes each time the session is regenerated, a malicious application is unable to access it.

The current session's CSRF token can be accessed via the request's session or via the csrf_token helper function:

Anytime you define a "POST", "PUT", "PATCH", or "DELETE" HTML form in your application, you should include a hidden CSRF _token field in the form so that the CSRF protection middleware can validate the request. For convenience, you may use the @csrf Blade directive to generate the hidden token input field:

<a name="csrf-tokens-and-spas"></a>
[Laravel 13] Explain csrf: Origin Verification

As discussed above, Laravel's request forgery middleware first checks the Sec-Fetch-Site header to determine if the request is from the same origin. By default, if this check does not pass, the middleware falls back to CSRF token validation.

However, if you would like to rely solely on origin verification and disable the CSRF token fallback entirely, you may do so using the preventRequestForgery method in your application's bootstrap/app.php file:

When using origin-only mode, requests that fail origin verification will receive a 403 HTTP response instead of the 419 response typically associated with CSRF token mismatches.

> [!WARNING]
> The Sec-Fetch-Site header is only sent by browsers over secure (HTTPS) connections. If your application is not served over HTTPS, origin verification will not be available and the middleware will fall back to CSRF token validation.

If your application needs to accept requests from subdomains (for example, dashboard.example.com accepting requests from example.com), you may allow same-site requests in addition to same-origin requests:

<a name="csrf-excluding-uris"></a>
[Laravel 13] Explain database testing: Resetting the Database After Each Test

Before proceeding much further, let's discuss how to reset your database after each of your tests so that data from a previous test does not interfere with subsequent tests. Laravel's included Illuminate\Foundation\Testing\RefreshDatabase trait will take care of this for you. Simply use the trait on your test class:

The Illuminate\Foundation\Testing\RefreshDatabase trait does not migrate your database if your schema is up to date. Instead, it will only execute the test within a database transaction. Therefore, any records added to the database by test cases that do not use this trait may still exist in the database.

If you would like to totally reset the database, you may use the Illuminate\Foundation\Testing\DatabaseMigrations or Illuminate\Foundation\Testing\DatabaseTruncation traits instead. However, both of these options are significantly slower than the RefreshDatabase trait.

<a name="model-factories"></a>
[Laravel 13] Explain database testing: Model Factories

When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a set of default attributes for each of your Eloquent models using model factories.

To learn more about creating and utilizing model factories to create models, please consult the complete model factory documentation. Once you have defined a model factory, you may utilize the factory within your test to create models:

<a name="running-seeders"></a>
[Laravel 13] Explain database testing: Running Seeders

If you would like to use database seeders to populate your database during a feature test, you may invoke the seed method. By default, the seed method will execute the DatabaseSeeder, which should execute all of your other seeders. Alternatively, you pass a specific seeder class name to the seed method:

Alternatively, you may instruct Laravel to automatically seed the database before each test that uses the RefreshDatabase trait. You may accomplish this by adding the Seed attribute to your base test class:

```php
<?php

namespace Tests;

use Illuminate\Foundation\Testing\Attributes\Seed;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
[Laravel 13] Explain database: Database: Getting Started

- Introduction
    - Configuration
    - Read and Write Connections
    - Pooled PostgreSQL Connections
- Running SQL Queries
    - Using Multiple Database Connections
    - Listening for Query Events
    - Monitoring Cumulative Query Time
- Database Transactions
- Connecting to the Database CLI
- Inspecting Your Databases
- Monitoring Your Databases

<a name="introduction"></a>
[Laravel 13] Explain database: Introduction

Almost every modern web application interacts with a database. Laravel makes interacting with databases extremely simple across a variety of supported databases using raw SQL, a fluent query builder, and the Eloquent ORM. Currently, Laravel provides first-party support for five databases:

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

- MariaDB 10.3+ (Version Policy)
- MySQL 5.7+ (Version Policy)
- PostgreSQL 10.0+ (Version Policy)
- SQLite 3.26.0+
- SQL Server 2017+ (Version Policy)

</div>

Additionally, MongoDB is supported via the mongodb/laravel-mongodb package, which is officially maintained by MongoDB. Check out the Laravel MongoDB documentation for more information.

<a name="configuration"></a>
[Laravel 13] Explain database: Configuration

The configuration for Laravel's database services is located in your application's config/database.php configuration file. In this file, you may define all of your database connections, as well as specify which connection should be used by default. Most of the configuration options within this file are driven by the values of your application's environment variables. Examples for most of Laravel's supported database systems are provided in this file.

By default, Laravel's sample environment configuration is ready to use with Laravel Sail, which is a Docker configuration for developing Laravel applications on your local machine. However, you are free to modify your database configuration as needed for your local database.

<a name="sqlite-configuration"></a>
[Laravel 13] Explain database: SQLite Configuration

SQLite databases are contained within a single file on your filesystem. You can create a new SQLite database using the touch command in your terminal: touch database/database.sqlite. After the database has been created, you may easily configure your environment variables to point to this database by placing the absolute path to the database in the DB_DATABASE environment variable:

By default, foreign key constraints are enabled for SQLite connections. If you would like to disable them, you should set the DB_FOREIGN_KEYS environment variable to false:

> [!NOTE]
> If you use the Laravel installer to create your Laravel application and select SQLite as your database, Laravel will automatically create a database/database.sqlite file and run the default database migrations for you.

<a name="mssql-configuration"></a>