bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 12] 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 12] 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 12] Explain controllers: Controllers

- Introduction
- Writing Controllers
    - Basic Controllers
    - Single Action Controllers
- Controller Middleware
- 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 12] 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 12] 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 12] 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 12] 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="resource-controllers"></a>
[Laravel 12] 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 12] Explain csrf: Preventing CSRF Requests

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:

The Illuminate\Foundation\Http\Middleware\ValidateCsrfToken middleware, which is included in the web middleware group by default, will automatically verify that the token in the request input matches the token stored in the session. When these two tokens match, we know that the authenticated user is the one initiating the request.

<a name="csrf-tokens-and-spas"></a>
[Laravel 12] 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 12] 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 12] 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 defining a $seed property on your base test class:

When the $seed property is true, the test will run the Database\Seeders\DatabaseSeeder class before each test that uses the RefreshDatabase trait. However, you may specify a specific seeder that should be executed by defining a $seeder property on your test class:

<a name="available-assertions"></a>
[Laravel 12] 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 12] 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 12] 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>
[Laravel 12] Explain deployment: Deployment

- Introduction
- Server Requirements
- Server Configuration
    - Nginx
    - FrankenPHP
    - Directory Permissions
- Optimization
    - Caching Configuration
    - Caching Events
    - Caching Routes
    - Caching Views
- Reloading Services
- Debug Mode
- The Health Route
- Deploying With Laravel Cloud or Forge

<a name="introduction"></a>
[Laravel 12] Explain deployment: Server Requirements

The Laravel framework has a few system requirements. You should ensure that your web server has the following minimum PHP version and extensions:

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

- PHP >= 8.2
- Ctype PHP Extension
- cURL PHP Extension
- DOM PHP Extension
- Fileinfo PHP Extension
- Filter PHP Extension
- Hash PHP Extension
- Mbstring PHP Extension
- OpenSSL PHP Extension
- PCRE PHP Extension
- PDO PHP Extension
- Session PHP Extension
- Tokenizer PHP Extension
- XML PHP Extension

</div>

<a name="server-configuration"></a>
[Laravel 12] Explain deployment: Nginx

If you are deploying your application to a server that is running Nginx, you may use the following configuration file as a starting point for configuring your web server. Most likely, this file will need to be customized depending on your server's configuration. **If you would like assistance in managing your server, consider using a fully-managed Laravel platform like Laravel Cloud.**

Please ensure, like the configuration below, your web server directs all requests to your application's public/index.php file. You should never attempt to move the index.php file to your project's root, as serving the application from the project root will expose many sensitive configuration files to the public Internet:

<a name="frankenphp"></a>
[Laravel 12] Explain deployment: FrankenPHP

FrankenPHP may also be used to serve your Laravel applications. FrankenPHP is a modern PHP application server written in Go. To serve a Laravel PHP application using FrankenPHP, you may simply invoke its php-server command:

To take advantage of more powerful features supported by FrankenPHP, such as its Laravel Octane integration, HTTP/3, modern compression, or the ability to package Laravel applications as standalone binaries, please consult FrankenPHP's Laravel documentation.

<a name="directory-permissions"></a>
[Laravel 12] Explain dusk: Laravel Dusk

- Introduction
- Installation
    - Managing ChromeDriver Installations
    - Using Other Browsers
- Getting Started
    - Generating Tests
    - Resetting the Database After Each Test
    - Running Tests
    - Environment Handling
- Browser Basics
    - Creating Browsers
    - Navigation
    - Resizing Browser Windows
    - Browser Macros
    - Authentication
    - Cookies
    - Executing JavaScript
    - Taking a Screenshot
    - Storing Console Output to Disk
    - Storing Page Source to Disk
- Interacting With Elements
    - Dusk Selectors
    - Text, Values, and Attributes
    - Interacting With Forms
    - Attaching Files
    - Pressing Buttons
    - Clicking Links
    - Using the Keyboard
    - Using the Mouse
    - JavaScript Dialogs
    - Interacting With Inline Frames
    - Scoping Selectors
    - Waiting for Elements
    - Scrolling an Element Into View
- Available Assertions
- Pages
    - Generating Pages
    - Configuring Pages
    - Navigating to Pages
    - Shorthand Selectors
    - Page Methods
- Components
    - Generating Components
    - Using Components
- Continuous Integration
    - Heroku CI
    - Travis CI
    - GitHub Actions
    - Chipper CI

<a name="introduction"></a>
[Laravel 12] Explain dusk: Introduction

> [!WARNING]
> Pest 4 now includes automated browser testing which offers significant performance and usability improvements compared to Laravel Dusk. For new projects, we recommend using Pest for browser testing.

Laravel Dusk provides an expressive, easy-to-use browser automation and testing API. By default, Dusk does not require you to install JDK or Selenium on your local computer. Instead, Dusk uses a standalone ChromeDriver installation. However, you are free to utilize any other Selenium compatible driver you wish.

<a name="installation"></a>
[Laravel 12] Explain dusk: Installation

To get started, you should install Google Chrome and add the laravel/dusk Composer dependency to your project:

> [!WARNING]
> If you are manually registering Dusk's service provider, you should **never** register it in your production environment, as doing so could lead to arbitrary users being able to authenticate with your application.

After installing the Dusk package, execute the dusk:install Artisan command. The dusk:install command will create a tests/Browser directory, an example Dusk test, and install the Chrome Driver binary for your operating system:

Next, set the APP_URL environment variable in your application's .env file. This value should match the URL you use to access your application in a browser.

> [!NOTE]
> If you are using Laravel Sail to manage your local development environment, please also consult the Sail documentation on configuring and running Dusk tests.

<a name="managing-chromedriver-installations"></a>
[Laravel 12] Explain dusk: Install the version of ChromeDriver that matches the detected version of Chrome / Chromium for your OS...

php artisan dusk:chrome-driver --detect
``

> [!WARNING]
> Dusk requires the chromedriver binaries to be executable. If you're having problems running Dusk, you should ensure the binaries are executable using the following command: chmod -R 0755 vendor/laravel/dusk/bin/`.

<a name="using-other-browsers"></a>
[Laravel 12] Explain eloquent collections: Introduction

All Eloquent methods that return more than one model result will return instances of the Illuminate\Database\Eloquent\Collection class, including results retrieved via the get method or accessed via a relationship. The Eloquent collection object extends Laravel's base collection, so it naturally inherits dozens of methods used to fluently work with the underlying array of Eloquent models. Be sure to review the Laravel collection documentation to learn all about these helpful methods!

All collections also serve as iterators, allowing you to loop over them as if they were simple PHP arrays:

However, as previously mentioned, collections are much more powerful than arrays and expose a variety of map / reduce operations that may be chained using an intuitive interface. For example, we may remove all inactive models and then gather the first name for each remaining user:

<a name="eloquent-collection-conversion"></a>
[Laravel 12] Explain eloquent collections: Available Methods

All Eloquent collections extend the base Laravel collection object; therefore, they inherit all of the powerful methods provided by the base collection class.

In addition, the Illuminate\Database\Eloquent\Collection class provides a superset of methods to aid with managing your model collections. Most methods return Illuminate\Database\Eloquent\Collection instances; however, some methods, like modelKeys, return an Illuminate\Support\Collection instance.

<style>
    .collection-method-list > p {
        columns: 14.4em 1; -moz-columns: 14.4em 1; -webkit-columns: 14.4em 1;
    }

    .collection-method-list a {
        display: block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }

    .collection-method code {
        font-size: 14px;
    }

    .collection-method:not(.first-collection-method) {
        margin-top: 50px;
    }
</style>

<div class="collection-method-list" markdown="1">

append
contains
diff
except
find
findOrFail
fresh
intersect
load
loadMissing
modelKeys
makeVisible
makeHidden
mergeVisible
mergeHidden
only
partition
setAppends
setVisible
setHidden
toQuery
unique
withoutAppends

</div>

<a name="method-append"></a>
[Laravel 12] Explain eloquent factories: Eloquent: Factories

- Introduction
- Defining Model Factories
    - Generating Factories
    - Factory States
    - Factory Callbacks
- Creating Models Using Factories
    - Instantiating Models
    - Persisting Models
    - Sequences
- Factory Relationships
    - Has Many Relationships
    - Belongs To Relationships
    - Many to Many Relationships
    - Polymorphic Relationships
    - Defining Relationships Within Factories
    - Recycling an Existing Model for Relationships

<a name="introduction"></a>
[Laravel 12] Explain eloquent factories: Introduction

When testing your application or seeding your database, you may need to insert a few records into your database. Instead of manually specifying the value of each column, Laravel allows you to define a set of default attributes for each of your Eloquent models using model factories.

To see an example of how to write a factory, take a look at the database/factories/UserFactory.php file in your application. This factory is included with all new Laravel applications and contains the following factory definition:

As you can see, in their most basic form, factories are classes that extend Laravel's base factory class and define a definition method. The definition method returns the default set of attribute values that should be applied when creating a model using the factory.

Via the fake helper, factories have access to the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing and seeding.

> [!NOTE]
> You can change your application's Faker locale by updating the faker_locale option in your config/app.php configuration file.

<a name="defining-model-factories"></a>
[Laravel 12] Explain eloquent factories: Model and Factory Discovery Conventions

Once you have defined your factories, you may use the static factory method provided to your models by the Illuminate\Database\Eloquent\Factories\HasFactory trait in order to instantiate a factory instance for that model.

The HasFactory trait's factory method will use conventions to determine the proper factory for the model the trait is assigned to. Specifically, the method will look for a factory in the Database\Factories namespace that has a class name matching the model name and is suffixed with Factory. If these conventions do not apply to your particular application or factory, you may add the UseFactory attribute to the model to manually specify the model's factory:

```php
use Illuminate\Database\Eloquent\Attributes\UseFactory;
use Database\Factories\Administration\FlightFactory;
[Laravel 12] Explain eloquent factories: [UseFactory(FlightFactory::class)]

class Flight extends Model
{
    // ...
}
php
use Database\Factories\Administration\FlightFactory;

/**
 * Create a new factory instance for the model.
 */
protected static function newFactory()
{
    return FlightFactory::new();
}
php
use App\Administration\Flight;
use Illuminate\Database\Eloquent\Factories\Factory;

class FlightFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var class-string<\Illuminate\Database\Eloquent\Model>
     */
    protected $model = Flight::class;
}
```

<a name="factory-states"></a>
[Laravel 12] Explain eloquent mutators: Eloquent: Mutators & Casting

- Introduction
- Accessors and Mutators
    - Defining an Accessor
    - Defining a Mutator
- Attribute Casting
    - Array and JSON Casting
    - Binary Casting
    - Date Casting
    - Enum Casting
    - Encrypted Casting
    - Query Time Casting
- Custom Casts
    - Value Object Casting
    - Array / JSON Serialization
    - Inbound Casting
    - Cast Parameters
    - Comparing Cast Values
    - Castables

<a name="introduction"></a>