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

Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model. Or, you may want to convert a JSON string that is stored in your database to an array when it is accessed via your Eloquent model.

<a name="accessors-and-mutators"></a>
[Laravel 12] Explain eloquent mutators: Defining an Accessor

An accessor transforms an Eloquent attribute value when it is accessed. To define an accessor, create a protected method on your model to represent the accessible attribute. This method name should correspond to the "camel case" representation of the true underlying model attribute / database column when applicable.

In this example, we'll define an accessor for the first_name attribute. The accessor will automatically be called by Eloquent when attempting to retrieve the value of the first_name attribute. All attribute accessor / mutator methods must declare a return type-hint of Illuminate\Database\Eloquent\Casts\Attribute:

All accessor methods return an Attribute instance which defines how the attribute will be accessed and, optionally, mutated. In this example, we are only defining how the attribute will be accessed. To do so, we supply the get argument to the Attribute class constructor.

As you can see, the original value of the column is passed to the accessor, allowing you to manipulate and return the value. To access the value of the accessor, you may simply access the first_name attribute on a model instance:

> [!NOTE]
> If you would like these computed values to be added to the array / JSON representations of your model, you will need to append them.

<a name="building-value-objects-from-multiple-attributes"></a>
[Laravel 12] Explain eloquent mutators: Accessor Caching

When returning value objects from accessors, any changes made to the value object will automatically be synced back to the model before the model is saved. This is possible because Eloquent retains instances returned by accessors so it can return the same instance each time the accessor is invoked:

However, you may sometimes wish to enable caching for primitive values like strings and booleans, particularly if they are computationally intensive. To accomplish this, you may invoke the shouldCache method when defining your accessor:

If you would like to disable the object caching behavior of attributes, you may invoke the withoutObjectCaching method when defining the attribute:

<a name="defining-a-mutator"></a>
[Laravel 12] Explain eloquent relationships: Eloquent: Relationships

- Introduction
- Defining Relationships
    - One to One / Has One
    - One to Many / Has Many
    - One to Many (Inverse) / Belongs To
    - Has One of Many
    - Has One Through
    - Has Many Through
- Scoped Relationships
- Many to Many Relationships
    - Retrieving Intermediate Table Columns
    - Filtering Queries via Intermediate Table Columns
    - Ordering Queries via Intermediate Table Columns
    - Defining Custom Intermediate Table Models
- Polymorphic Relationships
    - One to One
    - One to Many
    - One of Many
    - Many to Many
    - Custom Polymorphic Types
- Dynamic Relationships
- Querying Relations
    - Relationship Methods vs. Dynamic Properties
    - Querying Relationship Existence
    - Querying Relationship Absence
    - Querying Morph To Relationships
- Aggregating Related Models
    - Counting Related Models
    - Other Aggregate Functions
    - Counting Related Models on Morph To Relationships
- Eager Loading
    - Constraining Eager Loads
    - Lazy Eager Loading
    - Automatic Eager Loading
    - Preventing Lazy Loading
- Inserting and Updating Related Models
    - The save Method
    - The create Method
    - Belongs To Relationships
    - Many to Many Relationships
- Touching Parent Timestamps

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

Database tables are often related to one another. For example, a blog post may have many comments or an order could be related to the user who placed it. Eloquent makes managing and working with these relationships easy, and supports a variety of common relationships:

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

- One To One
- One To Many
- Many To Many
- Has One Through
- Has Many Through
- One To One (Polymorphic)
- One To Many (Polymorphic)
- Many To Many (Polymorphic)

</div>

<a name="defining-relationships"></a>
[Laravel 12] Explain eloquent relationships: Defining Relationships

Eloquent relationships are defined as methods on your Eloquent model classes. Since relationships also serve as powerful query builders, defining relationships as methods provides powerful method chaining and querying capabilities. For example, we may chain additional query constraints on this posts relationship:

But, before diving too deep into using relationships, let's learn how to define each type of relationship supported by Eloquent.

<a name="one-to-one"></a>
[Laravel 12] Explain eloquent relationships: One to One / Has One

A one-to-one relationship is a very basic type of database relationship. For example, a User model might be associated with one Phone model. To define this relationship, we will place a phone method on the User model. The phone method should call the hasOne method and return its result. The hasOne method is available to your model via the model's Illuminate\Database\Eloquent\Model base class:

The first argument passed to the hasOne method is the name of the related model class. Once the relationship is defined, we may retrieve the related record using Eloquent's dynamic properties. Dynamic properties allow you to access relationship methods as if they were properties defined on the model:

Eloquent determines the foreign key of the relationship based on the parent model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

Additionally, Eloquent assumes that the foreign key should have a value matching the primary key column of the parent. In other words, Eloquent will look for the value of the user's id column in the user_id column of the Phone record. If you would like the relationship to use a primary key value other than id or your model's $primaryKey property, you may pass a third argument to the hasOne method:

<a name="one-to-one-defining-the-inverse-of-the-relationship"></a>
[Laravel 12] Explain eloquent relationships: Defining the Inverse of the Relationship

So, we can access the Phone model from our User model. Next, let's define a relationship on the Phone model that will let us access the user that owns the phone. We can define the inverse of a hasOne relationship using the belongsTo method:

When invoking the user method, Eloquent will attempt to find a User model that has an id which matches the user_id column on the Phone model.

Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with _id. So, in this case, Eloquent assumes that the Phone model has a user_id column. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method:

If the parent model does not use id as its primary key, or you wish to find the associated model using a different column, you may pass a third argument to the belongsTo method specifying the parent table's custom key:

<a name="one-to-many"></a>
[Laravel 12] 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 12] 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 12] 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:

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:

For convenience, you may use the model's toResource method, which will use framework conventions to automatically discover the model's underlying resource:

When invoking the toResource method, Laravel will attempt to locate a resource that matches the model's name and is optionally suffixed with Resource within the Http\Resources namespace closest to the model's namespace.

If your resource class doesn't follow this naming convention or is located in a different namespace, you may specify the default resource for the model using the UseResource attribute:

```php
<?php

namespace App\Models;

use App\Http\Resources\CustomUserResource;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Attributes\UseResource;
[Laravel 12] 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 12] 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:

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

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

<a name="serializing-to-json"></a>
[Laravel 12] 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:

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

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:

<a name="relationships"></a>
[Laravel 12] 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 12] 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.

<a name="generating-model-classes"></a>
[Laravel 12] 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 12] 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 12] 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 12] 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:

<a name="decrypting-a-value"></a>
[Laravel 12] 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 12] 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 12] 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.

> [!WARNING]
> In your production environment, the value of APP_DEBUG 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 12] 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:

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:

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

<a name="global-log-context"></a>
[Laravel 12] 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
    - Queued Listener Middleware
    - Encrypted Queued Listeners
    - Unique Event Listeners
        - Keeping Listeners Unique Until Processing Begins
        - Unique Listener Locks
    - Handling Failed Jobs
- Dispatching Events
    - Dispatching Events After Database Transactions
    - Deferring Events
- Event Subscribers
    - Writing Event Subscribers
    - Registering Event Subscribers
- Testing
    - Faking a Subset of Events
    - Scoped Events Fakes

<a name="introduction"></a>
[Laravel 12] 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 12] 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 12] 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:

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

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:

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

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

<a name="event-discovery-in-production"></a>