TITLE: Define Mass Assignable JSON Column Attributes DESCRIPTION: Shows how to specify a nested JSON attribute, such as 'options->enabled', as mass assignable within the `$fillable` array for Eloquent models. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_53 LANGUAGE: php CODE: ``` /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'options->enabled', ]; ``` ---------------------------------------- TITLE: Execute Code Without Dispatching Laravel Model Events DESCRIPTION: This PHP example uses the `withoutEvents` method to perform operations on Eloquent models within a closure, preventing any model events from being dispatched during its execution. This is useful for bulk operations or specific scenarios where event triggering is undesirable. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_109 LANGUAGE: php CODE: ``` use App\Models\User; $user = User::withoutEvents(function () { User::findOrFail(1)->delete(); return User::find(2); }); ``` ---------------------------------------- TITLE: Generate basic Eloquent model DESCRIPTION: Use the `make:model` Artisan command to create a new Eloquent model class, which typically resides in the `app\Models` directory and extends `Illuminate\Database\Eloquent\Model`. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_0 LANGUAGE: shell CODE: ``` php artisan make:model Flight ``` ---------------------------------------- TITLE: Define Database Table Structure for Laravel Has Many Through DESCRIPTION: Illustrates the necessary database table schema for implementing a 'has-many-through' relationship in Laravel, detailing the `applications`, `environments`, and `deployments` tables with their respective columns and relationships. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_35 LANGUAGE: text CODE: ``` applications id - integer name - string environments id - integer application_id - integer name - string deployments id - integer environment_id - integer commit_hash - string ``` ---------------------------------------- TITLE: Start Laravel Development Servers DESCRIPTION: These commands are executed within your newly created Laravel application directory. They first install frontend dependencies and build assets using npm, then initiate Laravel's local development server, queue worker, and Vite development server via a Composer script. Your application will typically be accessible at http://localhost:8000. SOURCE: https://github.com/laravel/docs/blob/12.x/installation.md#_snippet_4 LANGUAGE: shell CODE: ``` cd example-app npm install && npm run build composer run dev ``` ---------------------------------------- TITLE: Retrieving Single Eloquent Models by ID or Conditions DESCRIPTION: Shows common methods (`find`, `first`, `firstWhere`) to retrieve a single Eloquent model instance. These methods are used to fetch a specific record based on its primary key or the first record matching a set of query constraints, returning a single model object instead of a collection. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_35 LANGUAGE: php CODE: ``` use App\Models\Flight; // Retrieve a model by its primary key... $flight = Flight::find(1); // Retrieve the first model matching the query constraints... $flight = Flight::where('active', 1)->first(); // Alternative to retrieving the first model matching the query constraints... $flight = Flight::firstWhere('active', 1); ``` ---------------------------------------- TITLE: Insert New Eloquent Models using the create() Method DESCRIPTION: Understand how to use the `create()` method for a more concise way to insert new Eloquent models. This method returns the newly inserted model instance but requires either the `fillable` or `guarded` property to be set on the model to prevent mass assignment vulnerabilities. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_41 LANGUAGE: php CODE: ``` use App\Models\Flight; $flight = Flight::create([ 'name' => 'London to Paris', ]); ``` ---------------------------------------- TITLE: Override Foreign Key for BelongsTo Relationship in Laravel Eloquent DESCRIPTION: This example shows how to specify a custom foreign key when defining a 'belongsTo' relationship. This is useful when the foreign key on the current model (e.g., Phone) does not follow Eloquent's default naming conventions. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_6 LANGUAGE: php CODE: ``` /** * Get the user that owns the phone. */ public function user(): BelongsTo { return $this->belongsTo(User::class, 'foreign_key'); } ``` ---------------------------------------- TITLE: Laravel Validation: Performing Additional Validation with `after` Method DESCRIPTION: Details how to execute additional validation logic after the initial validation rules have been processed. This can be done by passing a closure or an array of callables (including invokable classes) to the validator's `after` method, allowing for dynamic error additions. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_38 LANGUAGE: PHP CODE: ``` use Illuminate\Support\Facades\Validator; $validator = Validator::make(/* ... */); $validator->after(function ($validator) { if ($this->somethingElseIsInvalid()) { $validator->errors()->add( 'field', 'Something is wrong with this field!' ); } }); if ($validator->fails()) { // ... } ``` LANGUAGE: PHP CODE: ``` use App\Validation\ValidateShippingTime; use App\Validation\ValidateUserStatus; $validator->after([ new ValidateUserStatus, new ValidateShippingTime, function ($validator) { // ... }, ]); ``` ---------------------------------------- TITLE: Define Laravel Console Command Options with Values and Defaults DESCRIPTION: Learn how to define console command options that expect a value using the `=` suffix. This section also demonstrates how to provide default values for options, which are used if the user does not specify a value. If no default is set and the option is not provided, its value will be `null`. SOURCE: https://github.com/laravel/docs/blob/12.x/artisan.md#_snippet_24 LANGUAGE: php CODE: ``` protected $signature = 'mail:send {user} {--queue=}'; ``` LANGUAGE: shell CODE: ``` php artisan mail:send 1 --queue=default ``` LANGUAGE: php CODE: ``` 'mail:send {user} {--queue=default}' ``` ---------------------------------------- TITLE: Retrieve or Create Eloquent Models with firstOrCreate and firstOrNew DESCRIPTION: Explore `firstOrCreate` to find a model by attributes or create and persist it if not found. Understand `firstOrNew` which retrieves a model or instantiates a new one without persisting it, requiring a manual `save()` call. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_38 LANGUAGE: php CODE: ``` use App\Models\Flight; // Retrieve flight by name or create it if it doesn't exist... $flight = Flight::firstOrCreate([ 'name' => 'London to Paris' ]); // Retrieve flight by name or create it with the name, delayed, and arrival_time attributes... $flight = Flight::firstOrCreate( ['name' => 'London to Paris'], ['delayed' => 1, 'arrival_time' => '11:30'] ); // Retrieve flight by name or instantiate a new Flight instance... $flight = Flight::firstOrNew([ 'name' => 'London to Paris' ]); // Retrieve flight by name or instantiate with the name, delayed, and arrival_time attributes... $flight = Flight::firstOrNew( ['name' => 'Tokyo to Sydney'], ['delayed' => 1, 'arrival_time' => '11:30'] ); ``` ---------------------------------------- TITLE: Fill Existing Model with Attributes DESCRIPTION: Illustrates how to use the `fill` method on an existing Eloquent model instance to populate it with an array of attributes, respecting mass assignment rules. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_52 LANGUAGE: php CODE: ``` $flight->fill(['name' => 'Amsterdam to Frankfurt']); ``` ---------------------------------------- TITLE: Interact with Eloquent Model Attributes Cast to Enums (PHP) DESCRIPTION: Once an attribute has been defined as an enum cast on your model, it will be automatically converted to and from an enum instance when you interact with it. This allows for type-safe comparisons and assignments using enum values. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-mutators.md#_snippet_27 LANGUAGE: PHP CODE: ``` if ($server->status == ServerStatus::Provisioned) { $server->status = ServerStatus::Ready; $server->save(); } ``` ---------------------------------------- TITLE: Authorize Update Action via `Gate` Facade `authorize` Method DESCRIPTION: This PHP snippet demonstrates authorizing an 'update' action on a `Post` model using the `Gate` facade's `authorize` method. If the action is not authorized, this method throws an `Illuminate\Auth\Access\AuthorizationException`, which Laravel's exception handler automatically converts into an HTTP 403 response. SOURCE: https://github.com/laravel/docs/blob/12.x/authorization.md#_snippet_31 LANGUAGE: php CODE: ``` can('create', Post::class); ``` ---------------------------------------- TITLE: Injecting Dependencies into Laravel Controller Constructor DESCRIPTION: This example demonstrates how to inject a service, such as `AppleMusic`, into a Laravel controller's constructor. This approach facilitates managing class dependencies and enables easy testing through mocking. The `PodcastController` uses the injected service to retrieve podcast information. SOURCE: https://github.com/laravel/docs/blob/12.x/container.md#_snippet_0 LANGUAGE: php CODE: ``` $this->apple->findPodcast($id) ]); } } ``` ---------------------------------------- TITLE: Define a Basic Eloquent Model in PHP DESCRIPTION: This snippet shows the basic structure of an Eloquent model class, extending `Illuminate\Database\Eloquent\Model`. By convention, Eloquent will infer the corresponding database table name (e.g., 'flights' for 'Flight' model) from the model's class name. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_4 LANGUAGE: php CODE: ``` 'Oakland', 'destination' => 'San Diego'], ['price' => 99, 'discounted' => 1] ); ``` ---------------------------------------- TITLE: Eager Load Multiple Nested Eloquent Relationships with Array Syntax DESCRIPTION: Illustrates an alternative array syntax for eager loading multiple nested relationships, providing a convenient way to specify complex eager loading paths. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_121 LANGUAGE: php CODE: ``` $books = Book::with([ 'author' => [ 'contacts', 'publisher', ], ])->get(); ``` ---------------------------------------- TITLE: Creating a Stripe Checkout Session for Subscriptions in Laravel DESCRIPTION: This PHP route demonstrates how to initiate a Stripe Checkout session for a new subscription. It uses Cashier's `newSubscription` method, allows for trial days and promotion codes, and specifies success and cancel redirection URLs. SOURCE: https://github.com/laravel/docs/blob/12.x/billing.md#_snippet_15 LANGUAGE: php CODE: ``` use Illuminate\Http\Request; Route::get('/subscription-checkout', function (Request $request) { return $request->user() ->newSubscription('default', 'price_basic_monthly') ->trialDays(5) ->allowPromotionCodes() ->checkout([ 'success_url' => route('your-success-route'), 'cancel_url' => route('your-cancel-route'), ]); }); ``` ---------------------------------------- TITLE: Dump Variables and Die in Laravel DESCRIPTION: The `dd` function dumps the given variables to the browser or console and then terminates the script's execution. It's a debugging utility. SOURCE: https://github.com/laravel/docs/blob/12.x/helpers.md#_snippet_119 LANGUAGE: php CODE: ``` dd($value); dd($value1, $value2, $value3, ...); ``` ---------------------------------------- TITLE: Laravel: Stopping Validation on First Failure with 'bail' Rule DESCRIPTION: Explains how to use the `bail` rule to stop running validation rules on an attribute immediately after the first validation failure for that attribute. Rules are processed in the order they are assigned. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_5 LANGUAGE: php CODE: ``` $request->validate([ 'title' => 'bail|required|unique:posts|max:255', 'body' => 'required', ]); ``` ---------------------------------------- TITLE: Using Laravel's `with()` Function DESCRIPTION: Demonstrates the usage of the `with()` helper function in Laravel, showing how it returns a value or executes a closure if provided, based on the input. It handles numeric and null values. SOURCE: https://github.com/laravel/docs/blob/12.x/helpers.md#_snippet_156 LANGUAGE: php CODE: ``` $callback = function (mixed $value) { return is_numeric($value) ? $value * 2 : 0; }; $result = with(5, $callback); // 10 $result = with(null, $callback); // 0 $result = with(5, null); // 5 ``` ---------------------------------------- TITLE: Perform Aggregate Queries on Eloquent Models in Laravel DESCRIPTION: Discover how to use Laravel's query builder aggregate methods like `count` and `max` directly on Eloquent models. These methods return scalar values, such as the total count or maximum value, instead of model instances. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_39 LANGUAGE: php CODE: ``` $count = Flight::where('active', 1)->count(); $max = Flight::where('active', 1)->max('price'); ``` ---------------------------------------- TITLE: Conditionally Include Single Attribute with `when` in Laravel Resource DESCRIPTION: This PHP example shows how to use the `when` method within a Laravel resource's `toArray` method to conditionally include an attribute. The 'secret' key is only added to the response if the authenticated user's `isAdmin()` method returns true, otherwise it's omitted. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-resources.md#_snippet_27 LANGUAGE: php CODE: ``` /** * Transform the resource into an array. * * @return array */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->name, 'email' => $this->email, 'secret' => $this->when($request->user()->isAdmin(), 'secret-value'), 'created_at' => $this->created_at, 'updated_at' => $this->updated_at, ]; } ``` ---------------------------------------- TITLE: Convert Eloquent Model Attributes Only to Array (PHP) DESCRIPTION: Shows how to convert only the attributes of an Eloquent model to an array, excluding its relationships, using the `attributesToArray()` method. This is useful when you only need the model's direct data. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-serialization.md#_snippet_1 LANGUAGE: php CODE: ``` $user = User::first(); return $user->attributesToArray(); ``` ---------------------------------------- TITLE: Access Casted Boolean Attribute in Laravel Eloquent DESCRIPTION: This PHP example shows how to access an attribute that has been cast to a boolean. The 'is_admin' attribute, previously defined with a boolean cast, can be directly used in conditional statements, abstracting the underlying integer storage. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-mutators.md#_snippet_10 LANGUAGE: php CODE: ``` $user = App\Models\User::find(1); if ($user->is_admin) { // ... } ``` ---------------------------------------- TITLE: Laravel Eloquent User Observer Class Example DESCRIPTION: This PHP class demonstrates the default structure of an Eloquent observer. It defines methods for common model events such as `created`, `updated`, `deleted`, `restored`, and `forceDeleted`, each receiving the affected model instance. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_105 LANGUAGE: php CODE: ``` roles as $role) { echo $role->pivot->created_at; } ``` ---------------------------------------- TITLE: Define Validation Rules in Laravel Form Request DESCRIPTION: The `rules` method within a form request class is responsible for returning the validation rules that should apply to the request's data. Dependencies can be type-hinted and will be resolved by the Laravel service container. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_16 LANGUAGE: php CODE: ``` /** * Get the validation rules that apply to the request. * * @return array|string> */ public function rules(): array { return [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]; } ``` ---------------------------------------- TITLE: Handle Data After Successful Laravel Validation DESCRIPTION: Utilize the `passedValidation` method to normalize or modify request data after validation has successfully completed. This method is called only when all validation rules pass, allowing for post-validation data manipulation. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_30 LANGUAGE: php CODE: ``` /** * Handle a passed validation attempt. */ protected function passedValidation(): void { $this->replace(['name' => 'Taylor']); } ``` ---------------------------------------- TITLE: Run Laravel Database Migrations DESCRIPTION: This Artisan command executes all pending database migrations, creating or updating the necessary tables in your configured database. It's a crucial step when setting up a new database or after defining new schema changes. SOURCE: https://github.com/laravel/docs/blob/12.x/installation.md#_snippet_6 LANGUAGE: shell CODE: ``` php artisan migrate ``` ---------------------------------------- TITLE: Laravel Form Request: Perform Additional Validation with Invokable Classes DESCRIPTION: Shows how to use invokable classes within the `after` method of a Laravel Form Request to perform additional validation. This allows for more organized and reusable validation logic. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_19 LANGUAGE: php CODE: ``` use App\Validation\ValidateShippingTime; use App\Validation\ValidateUserStatus; use Illuminate\Validation\Validator; /** * Get the "after" validation callables for the request. */ public function after(): array { return [ new ValidateUserStatus, new ValidateShippingTime, function (Validator $validator) { // } ]; } ``` ---------------------------------------- TITLE: Access One-to-One Relationship Data in Laravel Eloquent DESCRIPTION: After defining a 'hasOne' relationship, this example illustrates how to retrieve the related record using Eloquent's dynamic properties. This allows accessing relationship methods as if they were direct properties on the model. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_2 LANGUAGE: php CODE: ``` $phone = User::find(1)->phone; ``` ---------------------------------------- TITLE: Define a Custom HTTP Client Macro in Laravel DESCRIPTION: Illustrates how to define a custom macro for the Laravel HTTP client. Macros provide a fluent way to configure common request paths and headers, typically defined in `AppServiceProvider`'s `boot` method. SOURCE: https://github.com/laravel/docs/blob/12.x/http-client.md#_snippet_36 LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Http; /** * Bootstrap any application services. */ public function boot(): void { Http::macro('github', function () { return Http::withHeaders([ 'X-Example' => 'example', ])->baseUrl('https://github.com'); }); } ``` ---------------------------------------- TITLE: Add Bearer Tokens to Laravel HTTP Requests DESCRIPTION: Demonstrates how to quickly add a bearer token to the `Authorization` header of an HTTP request using Laravel's `withToken` method. This is a common pattern for API authentication. SOURCE: https://github.com/laravel/docs/blob/12.x/http-client.md#_snippet_13 LANGUAGE: php CODE: ``` $response = Http::withToken('token')->post(/* ... */); ``` ---------------------------------------- TITLE: Implementing Deferred Laravel Service Providers for Performance DESCRIPTION: Explains how to create a deferred service provider in Laravel by implementing the `\Illuminate\Contracts\Support\DeferrableProvider` interface and defining a `provides` method. Deferring providers improves application performance by loading them only when their registered bindings are actually needed. SOURCE: https://github.com/laravel/docs/blob/12.x/providers.md#_snippet_7 LANGUAGE: php CODE: ``` app->singleton(Connection::class, function (Application $app) { return new Connection($app['config']['riak']); }); } /** * Get the services provided by the provider. * * @return array */ public function provides(): array { return [Connection::class]; } } ``` ---------------------------------------- TITLE: Finding Models by Primary Key or Failing in Laravel Eloquent Collection (PHP) DESCRIPTION: The `findOrFail` method attempts to retrieve a model from an Eloquent collection by its primary key. If no matching model is found, it throws an `Illuminate\Database\Eloquent\ModelNotFoundException`. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-collections.md#_snippet_7 LANGUAGE: PHP CODE: ``` $users = User::all(); $user = $users->findOrFail(1); ``` ---------------------------------------- TITLE: Convert Has Many to Has One Relationship (Laravel PHP) DESCRIPTION: Explains how to convert an existing `HasMany` relationship into a `HasOne` relationship using the `one` method. This allows applying `ofMany` methods to an already defined 'has many' relationship for convenience. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_28 LANGUAGE: php CODE: ``` /** * Get the user's orders. */ public function orders(): HasMany { return $this->hasMany(Order::class); } ``` LANGUAGE: php CODE: ``` /** * Get the user's largest order. */ public function largestOrder(): HasOne { return $this->orders()->one()->ofMany('price', 'max'); } ``` ---------------------------------------- TITLE: Propagate Gate Response Message with Gate::authorize DESCRIPTION: Explains that when `Gate::authorize` is used with a gate that returns a detailed `Response::deny` message, this message is automatically propagated to the HTTP response if an `AuthorizationException` is thrown due to the action being unauthorized. SOURCE: https://github.com/laravel/docs/blob/12.x/authorization.md#_snippet_9 LANGUAGE: php CODE: ``` Gate::authorize('edit-settings'); // The action is authorized... ``` ---------------------------------------- TITLE: Implement Laravel Eloquent Global Scope Class DESCRIPTION: Provides an example of a global scope class that implements the `Illuminate\Database\Eloquent\Scope` interface, defining the `apply` method to add custom query constraints to an Eloquent builder. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_81 LANGUAGE: php CODE: ``` where('created_at', '<', now()->subYears(2000)); } } ``` ---------------------------------------- TITLE: Laravel Job Dispatching: Delaying Job Execution DESCRIPTION: Demonstrates how to delay job processing using the `delay` method when dispatching. This example sets a job to be available for processing 10 minutes after it has been dispatched, controlling its execution timing. SOURCE: https://github.com/laravel/docs/blob/12.x/queues.md#_snippet_38 LANGUAGE: php CODE: ``` delay(now()->addMinutes(10)); return redirect('/podcasts'); } } ``` ---------------------------------------- TITLE: Hide Eloquent Model Attributes from Serialization (PHP) DESCRIPTION: Demonstrates how to prevent specific attributes (like passwords) from being included in the serialized array or JSON representation of an Eloquent model by defining them in the `$hidden` property. This enhances security and data privacy. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-serialization.md#_snippet_6 LANGUAGE: php CODE: ``` */ protected $hidden = ['password']; } ``` ---------------------------------------- TITLE: Implement Pessimistic Locking within a Database Transaction in Laravel DESCRIPTION: This comprehensive example illustrates how to wrap pessimistic locks within a database transaction in Laravel. It ensures that multiple related database operations, such as a money transfer, are atomic and consistent. If any part of the transaction fails, all changes are rolled back, and locks are automatically released. SOURCE: https://github.com/laravel/docs/blob/12.x/queries.md#_snippet_85 LANGUAGE: php CODE: ``` DB::transaction(function () { $sender = DB::table('users') ->lockForUpdate() ->find(1); $receiver = DB::table('users') ->lockForUpdate() ->find(2); if ($sender->balance < 100) { throw new RuntimeException('Balance too low.'); } DB::table('users') ->where('id', $sender->id) ->update([ 'balance' => $sender->balance - 100 ]); DB::table('users') ->where('id', $receiver->id) ->update([ 'balance' => $receiver->balance + 100 ]); }); ``` ---------------------------------------- TITLE: Create Custom Laravel Many-to-Many Pivot Model Class DESCRIPTION: This code defines a custom pivot model, `RoleUser`, which extends `Illuminate\Database\Eloquent\Relations\Pivot`. Custom pivot models allow developers to add specific logic, attributes, or methods directly to the intermediate table records of a many-to-many relationship. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_59 LANGUAGE: php CODE: ``` app->isProduction()); } ``` ---------------------------------------- TITLE: Laravel Validation: Timezone Rule Examples DESCRIPTION: Demonstrates the 'timezone' validation rule in Laravel, which validates if a field's value is a valid timezone identifier according to the `DateTimeZone::listIdentifiers` method. It supports various arguments for filtering timezone lists. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_150 LANGUAGE: PHP CODE: ``` 'timezone' => 'required|timezone:all'; 'timezone' => 'required|timezone:Africa'; 'timezone' => 'required|timezone:per_country,US'; ``` ---------------------------------------- TITLE: Define Route Using Laravel Cache Helper Function DESCRIPTION: This PHP code defines a simple web route that retrieves a value from the Laravel cache using the global `cache()` helper function. It demonstrates helper function usage within a route closure. SOURCE: https://github.com/laravel/docs/blob/12.x/facades.md#_snippet_5 LANGUAGE: php CODE: ``` Route::get('/cache', function () { return cache('key'); }); ``` ---------------------------------------- TITLE: Extending Collection with a `toUpper` Macro DESCRIPTION: This example demonstrates how to extend the `Collection` class by adding a custom `toUpper` macro. The macro uses the `map` method to convert all string values in the collection to uppercase. Macros are typically declared in a service provider's `boot` method. SOURCE: https://github.com/laravel/docs/blob/12.x/collections.md#_snippet_2 LANGUAGE: php CODE: ``` use Illuminate\Support\Collection; use Illuminate\Support\Str; Collection::macro('toUpper', function () { return $this->map(function (string $value) { return Str::upper($value); }); }); $collection = collect(['first', 'second']); $upper = $collection->toUpper(); // ['FIRST', 'SECOND'] ``` ---------------------------------------- TITLE: Sync Many-to-Many Associations with Eloquent `sync` Method DESCRIPTION: The `sync` method manages many-to-many associations by accepting an array of IDs. It ensures that only the provided IDs exist in the intermediate table, detaching any missing IDs and attaching new ones. You can also include pivot data. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_154 LANGUAGE: php CODE: ``` $user->roles()->sync([1, 2, 3]); ``` LANGUAGE: php CODE: ``` $user->roles()->sync([1 => ['expires' => true], 2, 3]); ``` ---------------------------------------- TITLE: Invoking Object Methods with Automatic Dependency Injection using `App::call` DESCRIPTION: The `App::call` method allows invoking a method on an object instance while the container automatically injects that method's dependencies, simplifying method execution. SOURCE: https://github.com/laravel/docs/blob/12.x/container.md#_snippet_35 LANGUAGE: php CODE: ``` use App\PodcastStats; use Illuminate\Support\Facades\App; $stats = App::call([new PodcastStats, 'generate']); ``` ---------------------------------------- TITLE: Apply Constraints to Lazy Eager Loading Queries in Laravel DESCRIPTION: Shows how to add additional query constraints to a lazy eager loading operation by passing an array with relationship names mapped to closure instances. The closure receives the query builder instance. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_133 LANGUAGE: php CODE: ``` $author->load(['books' => function (Builder $query) { $query->orderBy('published_date', 'asc'); }]); ``` ---------------------------------------- TITLE: Enable Global Automatic Eager Loading in Laravel DESCRIPTION: Shows how to enable Laravel's beta feature for automatic eager loading globally by invoking `Model::automaticallyEagerLoadRelationships` within the `boot` method of `AppServiceProvider`. This can reduce N+1 query issues automatically. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_137 LANGUAGE: php CODE: ``` use Illuminate\Database\Eloquent\Model; /** * Bootstrap any application services. */ public function boot(): void { Model::automaticallyEagerLoadRelationships(); } ``` ---------------------------------------- TITLE: Laravel Controller Method Injection for HTTP Request DESCRIPTION: Illustrates injecting the Illuminate\Http\Request instance into a controller method. This common use-case allows direct access to incoming HTTP request data within the method. SOURCE: https://github.com/laravel/docs/blob/12.x/controllers.md#_snippet_37 LANGUAGE: php CODE: ``` name; // Store the user... return redirect('/users'); } } ``` ---------------------------------------- TITLE: Create Payment Intent with Specific Methods (Laravel Cashier) DESCRIPTION: Shows how to create a payment intent allowing only specific payment methods using the `payWith` method. This provides more control over the payment options presented to the customer. The amount should be specified in the lowest denominator of the currency (e.g., pennies for USD). SOURCE: https://github.com/laravel/docs/blob/12.x/billing.md#_snippet_154 LANGUAGE: php CODE: ``` use Illuminate\Http\Request; Route::post('/pay', function (Request $request) { $payment = $request->user()->payWith( $request->get('amount'), ['card', 'bancontact'] ); return $payment->client_secret; }); ``` ---------------------------------------- TITLE: Define Local Scopes in Laravel Eloquent Model DESCRIPTION: Example of defining `popular` and `active` local scopes within a Laravel Eloquent `User` model using the `#[Scope]` attribute. These scopes encapsulate common query constraints. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_90 LANGUAGE: php CODE: ``` where('votes', '>', 100); } /** * Scope a query to only include active users. */ #[Scope] protected function active(Builder $query): void { $query->where('active', 1); } } ``` ---------------------------------------- TITLE: Laravel Validation: Bail Rule and stopOnFirstFailure Method DESCRIPTION: The 'bail' rule stops validation for a specific field after the first failure. This snippet shows how to use the 'stopOnFirstFailure' method on the validator instance to halt validation across all attributes upon the first encountered failure. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_65 LANGUAGE: php CODE: ``` if ($validator->stopOnFirstFailure()->fails()) { // ... } ``` ---------------------------------------- TITLE: response() function DESCRIPTION: The `response` function is a versatile helper for creating HTTP response instances or obtaining an instance of the response factory. It allows for easy creation of various response types, including plain text and JSON, with custom status codes and headers. SOURCE: https://github.com/laravel/docs/blob/12.x/helpers.md#_snippet_144 LANGUAGE: php CODE: ``` return response('Hello World', 200, $headers); return response()->json(['foo' => 'bar'], 200, $headers); ``` ---------------------------------------- TITLE: Querying Polymorphic Relationships with `whereHasMorph` and `whereDoesntHaveMorph` in Laravel Eloquent DESCRIPTION: The `whereHasMorph` and `whereDoesntHaveMorph` methods are used to query the existence or absence of 'morph to' relationships. They accept the relationship name, an array of related model classes, and an optional closure to add custom constraints to the polymorphic query. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_99 LANGUAGE: php CODE: ``` use App\Models\Comment; use App\Models\Post; use App\Models\Video; use Illuminate\Database\Eloquent\Builder; // Retrieve comments associated to posts or videos with a title like code%... $comments = Comment::whereHasMorph( 'commentable', [Post::class, Video::class], function (Builder $query) { $query->where('title', 'like', 'code%'); } )->get(); ``` LANGUAGE: php CODE: ``` use App\Models\Comment; use App\Models\Post; use Illuminate\Database\Eloquent\Builder; // Retrieve comments associated to posts with a title not like code%... $comments = Comment::whereDoesntHaveMorph( 'commentable', Post::class, function (Builder $query) { $query->where('title', 'like', 'code%'); } )->get(); ``` ---------------------------------------- TITLE: Access All Validation Data in Laravel Custom Rule (DataAwareRule) DESCRIPTION: Implement the `Illuminate\Contracts\Validation\DataAwareRule` interface in your custom validation class to access all data being validated. This requires defining a `setData` method, which Laravel automatically invokes with the validation data before processing. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_196 LANGUAGE: php CODE: ``` */ protected $data = []; // ... /** * Set the data under validation. * * @param array $data */ public function setData(array $data): static { $this->data = $data; return $this; } } ``` ---------------------------------------- TITLE: Laravel Validation Rule: required_array_keys DESCRIPTION: The `required_array_keys` rule ensures the field under validation is an array and contains at least all of the specified keys (`_foo_`, `_bar_`, etc.). This is useful for validating the structure of an array input. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_145 LANGUAGE: APIDOC CODE: ``` required_array_keys:_foo_,_bar_,... ``` ---------------------------------------- TITLE: Define Many-to-Many Relationship in Laravel User Model DESCRIPTION: This PHP code defines a many-to-many relationship between the `User` and `Role` models using Eloquent's `belongsToMany` method. It sets up the `roles` method on the `User` model to return a `BelongsToMany` relationship, linking users to their associated roles. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_44 LANGUAGE: php CODE: ``` belongsToMany(Role::class); } } ``` ---------------------------------------- TITLE: Conditionally Include Pivot Data with Custom Accessor in Laravel Resources DESCRIPTION: Explains the use of the `whenPivotLoadedAs` method when the intermediate table uses a custom accessor (e.g., 'subscription') instead of the default 'pivot'. This method allows for the conditional inclusion of pivot data, ensuring the correct accessor is used to retrieve the information. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-resources.md#_snippet_38 LANGUAGE: PHP CODE: ``` /** * Transform the resource into an array. * * @return array */ public function toArray(Request $request): array { return [ 'id' => $this->id, 'name' => $this->name, 'expires_at' => $this->whenPivotLoadedAs('subscription', 'role_user', function () { return $this->subscription->expires_at; }), ]; } ``` ---------------------------------------- TITLE: Insert New Record with create Method DESCRIPTION: After defining mass assignable attributes, this snippet shows a concise way to insert a new record using the `create` method, returning the new model instance. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_51 LANGUAGE: php CODE: ``` $flight = Flight::create(['name' => 'London to Paris']); ``` ---------------------------------------- TITLE: Count Related Models on Morph To Relationships with morphWithCount DESCRIPTION: Eager load a 'morph to' relationship and related model counts for various entities that may be returned by that relationship, using the `with` method in combination with the `morphTo` relationship's `morphWithCount` method. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_113 LANGUAGE: php CODE: ``` use Illuminate\Database\Eloquent\Relations\MorphTo; $activities = ActivityFeed::with([ 'parentable' => function (MorphTo $morphTo) { $morphTo->morphWithCount([ Photo::class => ['tags'], Post::class => ['comments'], ]); }])->get(); ``` ---------------------------------------- TITLE: Dependency Injection in Laravel Service Provider Boot Method DESCRIPTION: Illustrates how to type-hint dependencies in the `boot` method of a Laravel service provider. The service container automatically injects required dependencies, enabling advanced functionalities like macro registration on framework contracts. SOURCE: https://github.com/laravel/docs/blob/12.x/providers.md#_snippet_4 LANGUAGE: php CODE: ``` use IlluminateContractsRoutingResponseFactory; /** * Bootstrap any application services. */ public function boot(ResponseFactory $response): void { $response->macro('serialized', function (mixed $value) { // ... }); } ``` ---------------------------------------- TITLE: Adding Constraints to an Eloquent Relationship Query DESCRIPTION: Demonstrates how to chain additional query builder constraints onto an Eloquent relationship. After retrieving a User model, the `posts()` method is called to get the relationship query builder, allowing a `where` clause to filter active posts before fetching them. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_85 LANGUAGE: php CODE: ``` use App\Models\User; $user = User::find(1); $user->posts()->where('active', 1)->get(); ``` ---------------------------------------- TITLE: Get Related Model by Custom Criteria (Laravel PHP) DESCRIPTION: Illustrates how to retrieve a single related model based on a custom sorting criterion using the `ofMany` method. This example finds the largest order by 'price' using the 'max' aggregate function. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_27 LANGUAGE: php CODE: ``` /** * Get the user's largest order. */ public function largestOrder(): HasOne { return $this->hasOne(Order::class)->ofMany('price', 'max'); } ``` ---------------------------------------- TITLE: Authorize Update Action via User Model `cannot` Method DESCRIPTION: This PHP code snippet demonstrates how to authorize an 'update' action on a `Post` model using the `cannot` method available on the authenticated user. It checks if the user is unauthorized to update the given post, and if so, aborts the request with a 403 HTTP status code. This method automatically calls the appropriate policy if registered for the model. SOURCE: https://github.com/laravel/docs/blob/12.x/authorization.md#_snippet_29 LANGUAGE: php CODE: ``` user()->cannot('update', $post)) { abort(403); } // Update the post... return redirect('/posts'); } } ``` ---------------------------------------- TITLE: Authorize Create Action (No Model) via User Model `cannot` Method DESCRIPTION: This PHP example shows how to authorize an action like 'create' that does not require a specific model instance. Instead of passing a model object, the `cannot` method receives the class name (`Post::class`). This determines which policy to use for authorization, aborting with a 403 if the user is unauthorized to create a post. SOURCE: https://github.com/laravel/docs/blob/12.x/authorization.md#_snippet_30 LANGUAGE: php CODE: ``` user()->cannot('create', Post::class)) { abort(403); } // Create the post... return redirect('/posts'); } } ``` ---------------------------------------- TITLE: Define Custom Policy Discovery Logic in Laravel DESCRIPTION: This snippet shows how to register a custom callback using `Gate::guessPolicyNamesUsing` to define your own logic for discovering policy names based on model classes. This method is typically called within the `boot` method of your application's `AppServiceProvider`. SOURCE: https://github.com/laravel/docs/blob/12.x/authorization.md#_snippet_17 LANGUAGE: php CODE: ``` use Illuminate\Support\Facades\Gate; Gate::guessPolicyNamesUsing(function (string $modelClass) { // Return the name of the policy class for the given model... }); ``` ---------------------------------------- TITLE: Retrieve Validated Data using `safe()` with `only`, `except`, `all` DESCRIPTION: Illustrates the use of the `safe()` method, which returns an `Illuminate\Support\ValidatedInput` instance. This object provides `only()`, `except()`, and `all()` methods to retrieve specific subsets or all of the validated data. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_40 LANGUAGE: php CODE: ``` $validated = $request->safe()->only(['name', 'email']); $validated = $request->safe()->except(['name', 'email']); $validated = $request->safe()->all(); ``` ---------------------------------------- TITLE: Configure Eloquent Lazy Loading Prevention DESCRIPTION: This snippet shows how to prevent lazy loading of relationships in Eloquent models using `Model::preventLazyLoading()`. It's typically called in `AppServiceProvider`'s `boot` method and can be conditionally applied based on the application environment (e.g., only in non-production) to help identify N+1 query issues during development. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_18 LANGUAGE: php CODE: ``` use Illuminate\Database\Eloquent\Model; /** * Bootstrap any application services. */ public function boot(): void { Model::preventLazyLoading(! $this->app->isProduction()); } ``` ---------------------------------------- TITLE: Assert Any of Multiple JSON Attributes Present DESCRIPTION: Demonstrates the `hasAny` method, which allows checking if at least one of a given list of attributes is present in the JSON response. SOURCE: https://github.com/laravel/docs/blob/12.x/http-tests.md#_snippet_21 LANGUAGE: php CODE: ``` $response->assertJson(fn (AssertableJson $json) => $json->has('status') ->hasAny('data', 'message', 'code') ); ``` ---------------------------------------- TITLE: Combine Eloquent Scopes with Higher-Order `orWhere` DESCRIPTION: Illustrates the use of Laravel's higher-order `orWhere` method for fluently chaining scopes together without explicit closures, simplifying `OR` conditions. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_93 LANGUAGE: php CODE: ``` $users = User::popular()->orWhere->active()->get(); ``` ---------------------------------------- TITLE: Automatic Redirection with Named Error Bags in Laravel Validation DESCRIPTION: Demonstrates using the `validateWithBag` method to store validation error messages in a specific named error bag when automatic redirection occurs after validation failure. This helps organize errors when multiple forms are on a single page. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_34 LANGUAGE: php CODE: ``` Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ])->validateWithBag('post'); ``` ---------------------------------------- TITLE: Load Relationship Count After Model Retrieval with loadCount DESCRIPTION: Use the `loadCount` method to load a relationship count after the parent model has already been retrieved. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_106 LANGUAGE: php CODE: ``` $book = Book::first(); $book->loadCount('genres'); ``` ---------------------------------------- TITLE: Retrieve All Error Messages for All Fields DESCRIPTION: Demonstrates how to get an array of all error messages across all validated fields using the `all()` method on the `MessageBag` instance. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_46 LANGUAGE: php CODE: ``` foreach ($errors->all() as $message) { // ... } ``` ---------------------------------------- TITLE: Automatically Hydrate Parent Models with Eloquent HasMany Chaperone in PHP DESCRIPTION: This PHP code shows how to automatically hydrate parent models onto their children by invoking the `chaperone` method when defining a `hasMany` relationship. This helps prevent 'N + 1' query problems by ensuring the parent `Post` model is available on each `Comment` without additional queries. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-relationships.md#_snippet_13 LANGUAGE: PHP CODE: ``` hasMany(Comment::class)->chaperone(); } } ``` ---------------------------------------- TITLE: Laravel Job Dispatching: Basic Job Execution DESCRIPTION: Shows how to dispatch a job using the `dispatch` method on the job class itself. Any arguments passed to `dispatch` will be provided to the job's constructor, initiating its background processing. SOURCE: https://github.com/laravel/docs/blob/12.x/queues.md#_snippet_36 LANGUAGE: php CODE: ``` morphTo(); } } ``` ---------------------------------------- TITLE: Attach File from Storage with Custom Name and MIME Type in Laravel Email DESCRIPTION: Shows how to attach a file from Laravel's storage, also allowing for the specification of a custom display name and MIME type for the attachment. SOURCE: https://github.com/laravel/docs/blob/12.x/mail.md#_snippet_37 LANGUAGE: php CODE: ``` /** * Get the attachments for the message. * * @return array */ public function attachments(): array { return [ Attachment::fromStorage('/path/to/file') ->as('name.pdf') ->withMime('application/pdf'), ]; } ``` ---------------------------------------- TITLE: Configure Redirect for Unauthenticated Users in Laravel DESCRIPTION: Explains how to customize the redirect destination for unauthenticated users detected by the `auth` middleware. By default, they are redirected to the `login` named route, but this behavior can be modified within your application's `bootstrap/app.php` file. SOURCE: https://github.com/laravel/docs/blob/12.x/authentication.md#_snippet_4 LANGUAGE: php CODE: ``` use Illuminate\Http\Request; ->withMiddleware(function (Middleware $middleware) { $middleware->redirectGuestsTo('/login'); // Using a closure... $middleware->redirectGuestsTo(fn (Request $request) => route('login')); }) ``` ---------------------------------------- TITLE: Filter Collection by Keys with Laravel `only()` Method DESCRIPTION: The `only` method returns a new collection containing only the items with the specified keys. This method's behavior can be modified when used with Eloquent Collections. SOURCE: https://github.com/laravel/docs/blob/12.x/collections.md#_snippet_76 LANGUAGE: php CODE: ``` $collection = collect([ 'product_id' => 1, 'name' => 'Desk', 'price' => 100, 'discount' => false ]); $filtered = $collection->only(['product_id', 'name']); $filtered->all(); // ['product_id' => 1, 'name' => 'Desk'] ``` ---------------------------------------- TITLE: Define Eloquent Model Accessor for Appending Values DESCRIPTION: Illustrates how to define an accessor method on an Eloquent model to generate a computed attribute that does not have a corresponding database column. This example defines an `isAdmin` accessor that returns 'yes'. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent-serialization.md#_snippet_9 LANGUAGE: php CODE: ``` 'yes', ); } } ``` ---------------------------------------- TITLE: API Documentation for 'json' Validation Rule DESCRIPTION: Specifies the 'json' validation rule, which ensures the field under validation is a valid JSON string. SOURCE: https://github.com/laravel/docs/blob/12.x/validation.md#_snippet_102 LANGUAGE: APIDOC CODE: ``` json ``` ---------------------------------------- TITLE: Configuring Queued Listener Dynamic Backoff - PHP DESCRIPTION: This code illustrates how to define a `backoff` method on a queued listener class to implement more complex logic for determining the retry delay. The method should return an integer representing the number of seconds to wait before retrying. SOURCE: https://github.com/laravel/docs/blob/12.x/events.md#_snippet_26 LANGUAGE: PHP CODE: ``` /** * Calculate the number of seconds to wait before retrying the queued listener. */ public function backoff(): int { return 3; } ``` ---------------------------------------- TITLE: Apply Conditional Query Clauses with `when` in Laravel DESCRIPTION: These examples illustrate the `when` method, which allows you to conditionally apply query clauses based on a given condition. You can provide a single closure that executes if the condition is true, or an additional 'else' closure for when the condition is false, enabling dynamic query construction based on input or other logic. SOURCE: https://github.com/laravel/docs/blob/12.x/queries.md#_snippet_71 LANGUAGE: php CODE: ``` $role = $request->input('role'); $users = DB::table('users') ->when($role, function (Builder $query, string $role) { $query->where('role_id', $role); }) ->get(); ``` LANGUAGE: php CODE: ``` $sortByVotes = $request->boolean('sort_by_votes'); $users = DB::table('users') ->when($sortByVotes, function (Builder $query, bool $sortByVotes) { $query->orderBy('votes'); }, function (Builder $query) { $query->orderBy('name'); }) ->get(); ``` ---------------------------------------- TITLE: Define Scope with Pending Attributes in Laravel Eloquent DESCRIPTION: Example of defining a `draft` scope in a `Post` model that uses `withAttributes` to add `where` conditions and set default attributes for models created via the scope. SOURCE: https://github.com/laravel/docs/blob/12.x/eloquent.md#_snippet_96 LANGUAGE: php CODE: ``` withAttributes([ 'hidden' => true, ]); } } ```