bhavin-gajjar/laravel-coder-lora-train huggingface dataset:
[Laravel 10] Explain eloquent collections: `append($attributes)` {.collection-method .first-collection-method}

The append method may be used to indicate that an attribute should be appended for every model in the collection. This method accepts an array of attributes or a single attribute:

    $users->append('team');
    
    $users->append(['team', 'is_admin']);

<a name="method-contains"></a>
[Laravel 10] 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 10] 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:

    namespace Database\Factories;

    use Illuminate\Support\Str;
    use Illuminate\Database\Eloquent\Factories\Factory;

    class UserFactory extends Factory
    {
        /**
         * Define the model's default state.
         *
         * @return array<string, mixed>
         */
        public function definition(): array
        {
            return [
                'name' => fake()->name(),
                'email' => fake()->unique()->safeEmail(),
                'email_verified_at' => now(),
                'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
                'remember_token' => Str::random(10),
            ];
        }
    }

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 set your application's Faker locale by adding a faker_locale option to your config/app.php configuration file.

<a name="defining-model-factories"></a>
[Laravel 10] 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 overwrite the newFactory method on your model to return an instance of the model's corresponding factory directly:

    use Illuminate\Database\Eloquent\Factories\Factory;
    use Database\Factories\Administration\FlightFactory;

    /**
     * Create a new factory instance for the model.
     */
    protected static function newFactory(): Factory
    {
        return FlightFactory::new();
    }

Then, define a model property on the corresponding factory:

    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 10] Explain eloquent factories: Factory States

State manipulation methods allow you to define discrete modifications that can be applied to your model factories in any combination. For example, your Database\Factories\UserFactory factory might contain a suspended state method that modifies one of its default attribute values.

State transformation methods typically call the state method provided by Laravel's base factory class. The state method accepts a closure which will receive the array of raw attributes defined for the factory and should return an array of attributes to modify:

    use Illuminate\Database\Eloquent\Factories\Factory;

    /**
     * Indicate that the user is suspended.
     */
    public function suspended(): Factory
    {
        return $this->state(function (array $attributes) {
            return [
                'account_status' => 'suspended',
            ];
        });
    }

<a name="trashed-state"></a>
[Laravel 10] Explain eloquent mutators: Eloquent: Mutators & Casting

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

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

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Casts\Attribute;
    use Illuminate\Database\Eloquent\Model;

    class User extends Model
    {
        /**
         * Get the user's first name.
         */
        protected function firstName(): Attribute
        {
            return Attribute::make(
                get: fn (string $value) => ucfirst($value),
            );
        }
    }

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:

    use App\Models\User;

    $user = User::find(1);

    $firstName = $user->first_name;

> [!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 10] 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:

    use App\Models\User;

    $user = User::find(1);

    $user->address->lineOne = 'Updated Address Line 1 Value';
    $user->address->lineTwo = 'Updated Address Line 2 Value';

    $user->save();

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 10] Explain eloquent relationships: Eloquent: Relationships

- Introduction
- Defining Relationships
    - One to One
    - One to Many
    - One to Many (Inverse) / Belongs To
    - Has One of Many
    - Has One Through
    - Has Many Through
- 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
    - 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 10] 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 10] 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:

    $user->posts()->where('active', 1)->get();

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 10] Explain eloquent relationships: One to 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:

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\HasOne;

    class User extends Model
    {
        /**
         * Get the phone associated with the user.
         */
        public function phone(): HasOne
        {
            return $this->hasOne(Phone::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:

    $phone = User::find(1)->phone;

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:

    return $this->hasOne(Phone::class, 'foreign_key');

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:

    return $this->hasOne(Phone::class, 'foreign_key', 'local_key');

<a name="one-to-one-defining-the-inverse-of-the-relationship"></a>
[Laravel 10] 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:

    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\Relations\BelongsTo;

    class Phone extends Model
    {
        /**
         * Get the user that owns the phone.
         */
        public function user(): BelongsTo
        {
            return $this->belongsTo(User::class);
        }
    }

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:

    /**
     * Get the user that owns the phone.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'foreign_key');
    }

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:

    /**
     * Get the user that owns the phone.
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class, 'foreign_key', 'owner_key');
    }

<a name="one-to-many"></a>
[Laravel 10] 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 10] 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 10] 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 10] 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 10] 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 10] 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 10] 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
- Comparing Models
- Events
    - Using Closures
    - Observers
    - Muting Events

<a name="introduction"></a>
[Laravel 10] 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 10] 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 10] 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="using-the-encrypter"></a>