bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 11] Explain eloquent resources: Introduction

When building an API, you may need a transformation layer that sits between your Eloquent models and the JSON responses that are actually returned to your application's users. For example, you may wish to display certain attributes for a subset of users and not others, or you may wish to always include certain relationships in the JSON representation of your models. Eloquent's resource classes allow you to expressively and easily transform your models and model collections into JSON.

Of course, you may always convert Eloquent models or collections to JSON using their toJson methods; however, Eloquent resources provide more granular and robust control over the JSON serialization of your models and their relationships.

<a name="generating-resources"></a>
[Laravel 11] Explain eloquent resources: Resource Collections

In addition to generating resources that transform individual models, you may generate resources that are responsible for transforming collections of models. This allows your JSON responses to include links and other meta information that is relevant to an entire collection of a given resource.

To create a resource collection, you should use the --collection flag when creating the resource. Or, including the word Collection in the resource name will indicate to Laravel that it should create a collection resource. Collection resources extend the Illuminate\Http\Resources\Json\ResourceCollection class:

<a name="concept-overview"></a>
[Laravel 11] Explain eloquent resources: Concept Overview

> [!NOTE]  
> This is a high-level overview of resources and resource collections. You are highly encouraged to read the other sections of this documentation to gain a deeper understanding of the customization and power offered to you by resources.

Before diving into all of the options available to you when writing resources, let's first take a high-level look at how resources are used within Laravel. A resource class represents a single model that needs to be transformed into a JSON structure. For example, here is a simple UserResource resource class:

    <?php

    namespace App\Http\Resources;

    use Illuminate\Http\Request;
    use Illuminate\Http\Resources\Json\JsonResource;

    class UserResource extends JsonResource
    {
        /**
         * Transform the resource into an array.
         *
         * @return array<string, mixed>
         */
        public function toArray(Request $request): array
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'email' => $this->email,
                'created_at' => $this->created_at,
                'updated_at' => $this->updated_at,
            ];
        }
    }

Every resource class defines a toArray method which returns the array of attributes that should be converted to JSON when the resource is returned as a response from a route or controller method.

Note that we can access model properties directly from the $this variable. This is because a resource class will automatically proxy property and method access down to the underlying model for convenient access. Once the resource is defined, it may be returned from a route or controller. The resource accepts the underlying model instance via its constructor:

    use App\Http\Resources\UserResource;
    use App\Models\User;

    Route::get('/user/{id}', function (string $id) {
        return new UserResource(User::findOrFail($id));
    });

<a name="resource-collections"></a>
[Laravel 11] Explain eloquent serialization: Introduction

When building APIs using Laravel, you will often need to convert your models and relationships to arrays or JSON. Eloquent includes convenient methods for making these conversions, as well as controlling which attributes are included in the serialized representation of your models.

> [!NOTE]  
> For an even more robust way of handling Eloquent model and collection JSON serialization, check out the documentation on Eloquent API resources.

<a name="serializing-models-and-collections"></a>
[Laravel 11] Explain eloquent serialization: Serializing to Arrays

To convert a model and its loaded relationships to an array, you should use the toArray method. This method is recursive, so all attributes and all relations (including the relations of relations) will be converted to arrays:

    use App\Models\User;

    $user = User::with('roles')->first();

    return $user->toArray();

The attributesToArray method may be used to convert a model's attributes to an array but not its relationships:

    $user = User::first();

    return $user->attributesToArray();

You may also convert entire collections of models to arrays by calling the toArray method on the collection instance:

    $users = User::all();

    return $users->toArray();

<a name="serializing-to-json"></a>
[Laravel 11] Explain eloquent serialization: Serializing to JSON

To convert a model to JSON, you should use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON. You may also specify any JSON encoding options that are supported by PHP:

    use App\Models\User;

    $user = User::find(1);

    return $user->toJson();

    return $user->toJson(JSON_PRETTY_PRINT);

Alternatively, you may cast a model or collection to a string, which will automatically call the toJson method on the model or collection:

    return (string) User::find(1);

Since models and collections are converted to JSON when cast to a string, you can return Eloquent objects directly from your application's routes or controllers. Laravel will automatically serialize your Eloquent models and collections to JSON when they are returned from routes or controllers:

    Route::get('/users', function () {
        return User::all();
    });

<a name="relationships"></a>
[Laravel 11] Explain eloquent: Eloquent: Getting Started

- Introduction
- Generating Model Classes
- Eloquent Model Conventions
    - Table Names
    - Primary Keys
    - UUID and ULID Keys
    - Timestamps
    - Database Connections
    - Default Attribute Values
    - Configuring Eloquent Strictness
- Retrieving Models
    - Collections
    - Chunking Results
    - Chunk Using Lazy Collections
    - Cursors
    - Advanced Subqueries
- Retrieving Single Models / Aggregates
    - Retrieving or Creating Models
    - Retrieving Aggregates
- Inserting and Updating Models
    - Inserts
    - Updates
    - Mass Assignment
    - Upserts
- Deleting Models
    - Soft Deleting
    - Querying Soft Deleted Models
- Pruning Models
- Replicating Models
- Query Scopes
    - Global Scopes
    - Local Scopes
    - Pending Attributes
- Comparing Models
- Events
    - Using Closures
    - Observers
    - Muting Events

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

Laravel includes Eloquent, an object-relational mapper (ORM) that makes it enjoyable to interact with your database. When using Eloquent, each database table has a corresponding "Model" that is used to interact with that table. In addition to retrieving records from the database table, Eloquent models allow you to insert, update, and delete records from the table as well.

> [!NOTE]  
> Before getting started, be sure to configure a database connection in your application's config/database.php configuration file. For more information on configuring your database, check out the database configuration documentation.
[Laravel 11] Explain eloquent: Generating Model Classes

To get started, let's create an Eloquent model. Models typically live in the app\Models directory and extend the Illuminate\Database\Eloquent\Model class. You may use the make:model Artisan command to generate a new model:

If you would like to generate a database migration when you generate the model, you may use the --migration or -m option:

You may generate various other types of classes when generating a model, such as factories, seeders, policies, controllers, and form requests. In addition, these options may be combined to create multiple classes at once:

```shell
[Laravel 11] Explain encryption: Configuration

Before using Laravel's encrypter, you must set the key configuration option in your config/app.php configuration file. This configuration value is driven by the APP_KEY environment variable. You should use the php artisan key:generate command to generate this variable's value since the key:generate command will use PHP's secure random bytes generator to build a cryptographically secure key for your application. Typically, the value of the APP_KEY environment variable will be generated for you during Laravel's installation.

<a name="gracefully-rotating-encryption-keys"></a>
[Laravel 11] Explain encryption: Gracefully Rotating Encryption Keys

If you change your application's encryption key, all authenticated user sessions will be logged out of your application. This is because every cookie, including session cookies, are encrypted by Laravel. In addition, it will no longer be possible to decrypt any data that was encrypted with your previous encryption key.

To mitigate this issue, Laravel allows you to list your previous encryption keys in your application's APP_PREVIOUS_KEYS environment variable. This variable may contain a comma-delimited list of all of your previous encryption keys:

When you set this environment variable, Laravel will always use the "current" encryption key when encrypting values. However, when decrypting values, Laravel will first try the current key, and if decryption fails using the current key, Laravel will try all previous keys until one of the keys is able to decrypt the value.

This approach to graceful decryption allows users to keep using your application uninterrupted even if your encryption key is rotated.

<a name="using-the-encrypter"></a>
[Laravel 11] Explain encryption: Encrypting a Value

You may encrypt a value using the encryptString method provided by the Crypt facade. All encrypted values are encrypted using OpenSSL and the AES-256-CBC cipher. Furthermore, all encrypted values are signed with a message authentication code (MAC). The integrated message authentication code will prevent the decryption of any values that have been tampered with by malicious users:

    <?php

    namespace App\Http\Controllers;

    use Illuminate\Http\RedirectResponse;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Crypt;

    class DigitalOceanTokenController extends Controller
    {
        /**
         * Store a DigitalOcean API token for the user.
         */
        public function store(Request $request): RedirectResponse
        {
            $request->user()->fill([
                'token' => Crypt::encryptString($request->token),
            ])->save();

            return redirect('/secrets');
        }
    }

<a name="decrypting-a-value"></a>
[Laravel 11] Explain envoy: Defining Tasks

Tasks are the basic building block of Envoy. Tasks define the shell commands that should execute on your remote servers when the task is invoked. For example, you might define a task that executes the php artisan queue:restart command on all of your application's queue worker servers.

All of your Envoy tasks should be defined in an Envoy.blade.php file at the root of your application. Here's an example to get you started:

As you can see, an array of @servers is defined at the top of the file, allowing you to reference these servers via the on option of your task declarations. The @servers declaration should always be placed on a single line. Within your @task declarations, you should place the shell commands that should execute on your servers when the task is invoked.

<a name="local-tasks"></a>
[Laravel 11] Explain errors: Introduction

When you start a new Laravel project, error and exception handling is already configured for you; however, at any point, you may use the withExceptions method in your application's bootstrap/app.php to manage how exceptions are reported and rendered by your application.

The $exceptions object provided to the withExceptions closure is an instance of Illuminate\Foundation\Configuration\Exceptions and is responsible for managing exception handling in your application. We'll dive deeper into this object throughout this documentation.

<a name="configuration"></a>
[Laravel 11] Explain errors: Configuration

The debug option in your config/app.php configuration file determines how much information about an error is actually displayed to the user. By default, this option is set to respect the value of the APP_DEBUG environment variable, which is stored in your .env file.

During local development, you should set the APP_DEBUG environment variable to true. **In your production environment, this value should always be false. If the value is set to true in production, you risk exposing sensitive configuration values to your application's end users.**

<a name="handling-exceptions"></a>
[Laravel 11] Explain errors: Reporting Exceptions

In Laravel, exception reporting is used to log exceptions or send them to an external service like Sentry or Flare. By default, exceptions will be logged based on your logging configuration. However, you are free to log exceptions however you wish.

If you need to report different types of exceptions in different ways, you may use the report exception method in your application's bootstrap/app.php to register a closure that should be executed when an exception of a given type needs to be reported. Laravel will determine what type of exception the closure reports by examining the type-hint of the closure:

    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->report(function (InvalidOrderException $e) {
            // ...
        });
    })

When you register a custom exception reporting callback using the report method, Laravel will still log the exception using the default logging configuration for the application. If you wish to stop the propagation of the exception to the default logging stack, you may use the stop method when defining your reporting callback or return false from the callback:

    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->report(function (InvalidOrderException $e) {
            // ...
        })->stop();

        $exceptions->report(function (InvalidOrderException $e) {
            return false;
        });
    })

> [!NOTE]  
> To customize the exception reporting for a given exception, you may also utilize reportable exceptions.

<a name="global-log-context"></a>
[Laravel 11] Explain errors: Global Log Context

If available, Laravel automatically adds the current user's ID to every exception's log message as contextual data. You may define your own global contextual data using the context exception method in your application's bootstrap/app.php file. This information will be included in every exception's log message written by your application:

    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->context(fn () => [
            'foo' => 'bar',
        ]);
    })

<a name="exception-log-context"></a>
[Laravel 11] Explain events: Events

- Introduction
- Generating Events and Listeners
- Registering Events and Listeners
    - Event Discovery
    - Manually Registering Events
    - Closure Listeners
- Defining Events
- Defining Listeners
- Queued Event Listeners
    - Manually Interacting With the Queue
    - Queued Event Listeners and Database Transactions
    - Handling Failed Jobs
- Dispatching Events
    - Dispatching Events After Database Transactions
- Event Subscribers
    - Writing Event Subscribers
    - Registering Event Subscribers
- Testing
    - Faking a Subset of Events
    - Scoped Events Fakes

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

Laravel's events provide a simple observer pattern implementation, allowing you to subscribe and listen for various events that occur within your application. Event classes are typically stored in the app/Events directory, while their listeners are stored in app/Listeners. Don't worry if you don't see these directories in your application as they will be created for you as you generate events and listeners using Artisan console commands.

Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an App\Events\OrderShipped event which a listener can receive and use to dispatch a Slack notification.

<a name="generating-events-and-listeners"></a>
[Laravel 11] Explain events: Generating Events and Listeners

To quickly generate events and listeners, you may use the make:event and make:listener Artisan commands:

For convenience, you may also invoke the make:event and make:listener Artisan commands without additional arguments. When you do so, Laravel will automatically prompt you for the class name and, when creating a listener, the event it should listen to:

<a name="registering-events-and-listeners"></a>
[Laravel 11] Explain events: Event Discovery

By default, Laravel will automatically find and register your event listeners by scanning your application's Listeners directory. When Laravel finds any listener class method that begins with handle or __invoke, Laravel will register those methods as event listeners for the event that is type-hinted in the method's signature:

    use App\Events\PodcastProcessed;

    class SendPodcastNotification
    {
        /**
         * Handle the given event.
         */
        public function handle(PodcastProcessed $event): void
        {
            // ...
        }
    }

You may listen to multiple events using PHP's union types:

    /**
     * Handle the given event.
     */
    public function handle(PodcastProcessed|PodcastPublished $event): void
    {
        // ...
    }

If you plan to store your listeners in a different directory or within multiple directories, you may instruct Laravel to scan those directories using the withEvents method in your application's bootstrap/app.php file:

    ->withEvents(discover: [
        __DIR__.'/../app/Domain/Orders/Listeners',
    ])

You may scan for listeners in multiple similar directories using the * character as a wildcard:

    ->withEvents(discover: [
        __DIR__.'/../app/Domain/*/Listeners',
    ])

The event:list command may be used to list all of the listeners registered within your application:

<a name="event-discovery-in-production"></a>
[Laravel 11] Explain events: Event Discovery in Production

To give your application a speed boost, you should cache a manifest of all of your application's listeners using the optimize or event:cache Artisan commands. Typically, this command should be run as part of your application's deployment process. This manifest will be used by the framework to speed up the event registration process. The event:clear command may be used to destroy the event cache.

<a name="manually-registering-events"></a>
[Laravel 11] Explain facades: Introduction

Throughout the Laravel documentation, you will see examples of code that interacts with Laravel's features via "facades". Facades provide a "static" interface to classes that are available in the application's service container. Laravel ships with many facades which provide access to almost all of Laravel's features.

Laravel facades serve as "static proxies" to underlying classes in the service container, providing the benefit of a terse, expressive syntax while maintaining more testability and flexibility than traditional static methods. It's perfectly fine if you don't totally understand how facades work - just go with the flow and continue learning about Laravel.

All of Laravel's facades are defined in the Illuminate\Support\Facades namespace. So, we can easily access a facade like so:

    use Illuminate\Support\Facades\Cache;
    use Illuminate\Support\Facades\Route;

    Route::get('/cache', function () {
        return Cache::get('key');
    });

Throughout the Laravel documentation, many of the examples will use facades to demonstrate various features of the framework.

<a name="helper-functions"></a>
[Laravel 11] Explain facades: Helper Functions

To complement facades, Laravel offers a variety of global "helper functions" that make it even easier to interact with common Laravel features. Some of the common helper functions you may interact with are view, response, url, config, and more. Each helper function offered by Laravel is documented with their corresponding feature; however, a complete list is available within the dedicated helper documentation.

For example, instead of using the Illuminate\Support\Facades\Response facade to generate a JSON response, we may simply use the response function. Because helper functions are globally available, you do not need to import any classes in order to use them:

    use Illuminate\Support\Facades\Response;

    Route::get('/users', function () {
        return Response::json([
            // ...
        ]);
    });

    Route::get('/users', function () {
        return response()->json([
            // ...
        ]);
    });

<a name="when-to-use-facades"></a>
[Laravel 11] Explain facades: When to Utilize Facades

Facades have many benefits. They provide a terse, memorable syntax that allows you to use Laravel's features without remembering long class names that must be injected or configured manually. Furthermore, because of their unique usage of PHP's dynamic methods, they are easy to test.

However, some care must be taken when using facades. The primary danger of facades is class "scope creep". Since facades are so easy to use and do not require injection, it can be easy to let your classes continue to grow and use many facades in a single class. Using dependency injection, this potential is mitigated by the visual feedback a large constructor gives you that your class is growing too large. So, when using facades, pay special attention to the size of your class so that its scope of responsibility stays narrow. If your class is getting too large, consider splitting it into multiple smaller classes.

<a name="facades-vs-dependency-injection"></a>
[Laravel 11] Explain facades: Facades vs. Dependency Injection

One of the primary benefits of dependency injection is the ability to swap implementations of the injected class. This is useful during testing since you can inject a mock or stub and assert that various methods were called on the stub.

Typically, it would not be possible to mock or stub a truly static class method. However, since facades use dynamic methods to proxy method calls to objects resolved from the service container, we actually can test facades just as we would test an injected class instance. For example, given the following route:

    use Illuminate\Support\Facades\Cache;

    Route::get('/cache', function () {
        return Cache::get('key');
    });

Using Laravel's facade testing methods, we can write the following test to verify that the Cache::get method was called with the argument we expected:

<a name="facades-vs-helper-functions"></a>
[Laravel 11] Explain filesystem: File Storage

- Introduction
- Configuration
    - The Local Driver
    - The Public Disk
    - Driver Prerequisites
    - Scoped and Read-Only Filesystems
    - Amazon S3 Compatible Filesystems
- Obtaining Disk Instances
    - On-Demand Disks
- Retrieving Files
    - Downloading Files
    - File URLs
    - Temporary URLs
    - File Metadata
- Storing Files
    - Prepending and Appending To Files
    - Copying and Moving Files
    - Automatic Streaming
    - File Uploads
    - File Visibility
- Deleting Files
- Directories
- Testing
- Custom Filesystems

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