id
stringlengths 6
6
| text
stringlengths 20
17.2k
| title
stringclasses 1
value |
|---|---|---|
243222
|
## Configuration
Laravel's filesystem configuration file is located at `config/filesystems.php`. Within this file, you may configure all of your filesystem "disks". Each disk represents a particular storage driver and storage location. Example configurations for each supported driver are included in the configuration file so you can modify the configuration to reflect your storage preferences and credentials.
The `local` driver interacts with files stored locally on the server running the Laravel application while the `s3` driver is used to write to Amazon's S3 cloud storage service.
> [!NOTE]
> You may configure as many disks as you like and may even have multiple disks that use the same driver.
<a name="the-local-driver"></a>
### The Local Driver
When using the `local` driver, all file operations are relative to the `root` directory defined in your `filesystems` configuration file. By default, this value is set to the `storage/app` directory. Therefore, the following method would write to `storage/app/example.txt`:
use Illuminate\Support\Facades\Storage;
Storage::disk('local')->put('example.txt', 'Contents');
<a name="the-public-disk"></a>
### The Public Disk
The `public` disk included in your application's `filesystems` configuration file is intended for files that are going to be publicly accessible. By default, the `public` disk uses the `local` driver and stores its files in `storage/app/public`.
To make these files accessible from the web, you should create a symbolic link from `public/storage` to `storage/app/public`. Utilizing this folder convention will keep your publicly accessible files in one directory that can be easily shared across deployments when using zero down-time deployment systems like [Envoyer](https://envoyer.io).
To create the symbolic link, you may use the `storage:link` Artisan command:
```shell
php artisan storage:link
```
Once a file has been stored and the symbolic link has been created, you can create a URL to the files using the `asset` helper:
echo asset('storage/file.txt');
You may configure additional symbolic links in your `filesystems` configuration file. Each of the configured links will be created when you run the `storage:link` command:
'links' => [
public_path('storage') => storage_path('app/public'),
public_path('images') => storage_path('app/images'),
],
The `storage:unlink` command may be used to destroy your configured symbolic links:
```shell
php artisan storage:unlink
```
<a name="driver-prerequisites"></a>
### Driver Prerequisites
<a name="s3-driver-configuration"></a>
#### S3 Driver Configuration
Before using the S3 driver, you will need to install the Flysystem S3 package via the Composer package manager:
```shell
composer require league/flysystem-aws-s3-v3 "^3.0" --with-all-dependencies
```
An S3 disk configuration array is located in your `config/filesystems.php` configuration file. Typically, you should configure your S3 information and credentials using the following environment variables which are referenced by the `config/filesystems.php` configuration file:
```
AWS_ACCESS_KEY_ID=<your-key-id>
AWS_SECRET_ACCESS_KEY=<your-secret-access-key>
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=<your-bucket-name>
AWS_USE_PATH_STYLE_ENDPOINT=false
```
For convenience, these environment variables match the naming convention used by the AWS CLI.
<a name="ftp-driver-configuration"></a>
#### FTP Driver Configuration
Before using the FTP driver, you will need to install the Flysystem FTP package via the Composer package manager:
```shell
composer require league/flysystem-ftp "^3.0"
```
Laravel's Flysystem integrations work great with FTP; however, a sample configuration is not included with the framework's default `config/filesystems.php` configuration file. If you need to configure an FTP filesystem, you may use the configuration example below:
'ftp' => [
'driver' => 'ftp',
'host' => env('FTP_HOST'),
'username' => env('FTP_USERNAME'),
'password' => env('FTP_PASSWORD'),
// Optional FTP Settings...
// 'port' => env('FTP_PORT', 21),
// 'root' => env('FTP_ROOT'),
// 'passive' => true,
// 'ssl' => true,
// 'timeout' => 30,
],
<a name="sftp-driver-configuration"></a>
#### SFTP Driver Configuration
Before using the SFTP driver, you will need to install the Flysystem SFTP package via the Composer package manager:
```shell
composer require league/flysystem-sftp-v3 "^3.0"
```
Laravel's Flysystem integrations work great with SFTP; however, a sample configuration is not included with the framework's default `config/filesystems.php` configuration file. If you need to configure an SFTP filesystem, you may use the configuration example below:
'sftp' => [
'driver' => 'sftp',
'host' => env('SFTP_HOST'),
// Settings for basic authentication...
'username' => env('SFTP_USERNAME'),
'password' => env('SFTP_PASSWORD'),
// Settings for SSH key based authentication with encryption password...
'privateKey' => env('SFTP_PRIVATE_KEY'),
'passphrase' => env('SFTP_PASSPHRASE'),
// Settings for file / directory permissions...
'visibility' => 'private', // `private` = 0600, `public` = 0644
'directory_visibility' => 'private', // `private` = 0700, `public` = 0755
// Optional SFTP Settings...
// 'hostFingerprint' => env('SFTP_HOST_FINGERPRINT'),
// 'maxTries' => 4,
// 'passphrase' => env('SFTP_PASSPHRASE'),
// 'port' => env('SFTP_PORT', 22),
// 'root' => env('SFTP_ROOT', ''),
// 'timeout' => 30,
// 'useAgent' => true,
],
<a name="scoped-and-read-only-filesystems"></a>
### Scoped and Read-Only Filesystems
Scoped disks allow you to define a filesystem where all paths are automatically prefixed with a given path prefix. Before creating a scoped filesystem disk, you will need to install an additional Flysystem package via the Composer package manager:
```shell
composer require league/flysystem-path-prefixing "^3.0"
```
You may create a path scoped instance of any existing filesystem disk by defining a disk that utilizes the `scoped` driver. For example, you may create a disk which scopes your existing `s3` disk to a specific path prefix, and then every file operation using your scoped disk will utilize the specified prefix:
```php
's3-videos' => [
'driver' => 'scoped',
'disk' => 's3',
'prefix' => 'path/to/videos',
],
```
"Read-only" disks allow you to create filesystem disks that do not allow write operations. Before using the `read-only` configuration option, you will need to install an additional Flysystem package via the Composer package manager:
```shell
composer require league/flysystem-read-only "^3.0"
```
Next, you may include the `read-only` configuration option in one or more of your disk's configuration arrays:
```php
's3-videos' => [
'driver' => 's3',
// ...
'read-only' => true,
],
```
<a name="amazon-s3-compatible-filesystems"></a>
### Amazon S3 Compatible Filesystems
By default, your application's `filesystems` configuration file contains a disk configuration for the `s3` disk. In addition to using this disk to interact with Amazon S3, you may use it to interact with any S3 compatible file storage service such as [MinIO](https://github.com/minio/minio) or [DigitalOcean Spaces](https://www.digitalocean.com/products/spaces/).
Typically, after updating the disk's credentials to match the credentials of the service you are planning to use, you only need to update the value of the `endpoint` configuration option. This option's value is typically defined via the `AWS_ENDPOINT` environment variable:
'endpoint' => env('AWS_ENDPOINT', 'https://minio:9000'),
<a name="minio"></a>
#### MinIO
In order for Laravel's Flysystem integration to generate proper URLs when using MinIO, you should define the `AWS_URL` environment variable so that it matches your application's local URL and includes the bucket name in the URL path:
```ini
AWS_URL=http://localhost:9000/local
```
> [!WARNING]
> Generating temporary storage URLs via the `temporaryUrl` method may not work when using MinIO if the `endpoint` is not accessible by the client.
<a name="obtaining-disk-instances"></a>
| |
243223
|
## Obtaining Disk Instances
The `Storage` facade may be used to interact with any of your configured disks. For example, you may use the `put` method on the facade to store an avatar on the default disk. If you call methods on the `Storage` facade without first calling the `disk` method, the method will automatically be passed to the default disk:
use Illuminate\Support\Facades\Storage;
Storage::put('avatars/1', $content);
If your application interacts with multiple disks, you may use the `disk` method on the `Storage` facade to work with files on a particular disk:
Storage::disk('s3')->put('avatars/1', $content);
<a name="on-demand-disks"></a>
### On-Demand Disks
Sometimes you may wish to create a disk at runtime using a given configuration without that configuration actually being present in your application's `filesystems` configuration file. To accomplish this, you may pass a configuration array to the `Storage` facade's `build` method:
```php
use Illuminate\Support\Facades\Storage;
$disk = Storage::build([
'driver' => 'local',
'root' => '/path/to/root',
]);
$disk->put('image.jpg', $content);
```
<a name="retrieving-files"></a>
## Retrieving Files
The `get` method may be used to retrieve the contents of a file. The raw string contents of the file will be returned by the method. Remember, all file paths should be specified relative to the disk's "root" location:
$contents = Storage::get('file.jpg');
If the file you are retrieving contains JSON, you may use the `json` method to retrieve the file and decode its contents:
$orders = Storage::json('orders.json');
The `exists` method may be used to determine if a file exists on the disk:
if (Storage::disk('s3')->exists('file.jpg')) {
// ...
}
The `missing` method may be used to determine if a file is missing from the disk:
if (Storage::disk('s3')->missing('file.jpg')) {
// ...
}
<a name="downloading-files"></a>
### Downloading Files
The `download` method may be used to generate a response that forces the user's browser to download the file at the given path. The `download` method accepts a filename as the second argument to the method, which will determine the filename that is seen by the user downloading the file. Finally, you may pass an array of HTTP headers as the third argument to the method:
return Storage::download('file.jpg');
return Storage::download('file.jpg', $name, $headers);
<a name="file-urls"></a>
### File URLs
You may use the `url` method to get the URL for a given file. If you are using the `local` driver, this will typically just prepend `/storage` to the given path and return a relative URL to the file. If you are using the `s3` driver, the fully qualified remote URL will be returned:
use Illuminate\Support\Facades\Storage;
$url = Storage::url('file.jpg');
When using the `local` driver, all files that should be publicly accessible should be placed in the `storage/app/public` directory. Furthermore, you should [create a symbolic link](#the-public-disk) at `public/storage` which points to the `storage/app/public` directory.
> [!WARNING]
> When using the `local` driver, the return value of `url` is not URL encoded. For this reason, we recommend always storing your files using names that will create valid URLs.
<a name="url-host-customization"></a>
#### URL Host Customization
If you would like to modify the host for URLs generated using the `Storage` facade, you may add or change the `url` option in the disk's configuration array:
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => env('APP_URL').'/storage',
'visibility' => 'public',
'throw' => false,
],
<a name="temporary-urls"></a>
### Temporary URLs
Using the `temporaryUrl` method, you may create temporary URLs to files stored using the `local` and `s3` drivers. This method accepts a path and a `DateTime` instance specifying when the URL should expire:
use Illuminate\Support\Facades\Storage;
$url = Storage::temporaryUrl(
'file.jpg', now()->addMinutes(5)
);
<a name="enabling-local-temporary-urls"></a>
#### Enabling Local Temporary URLs
If you started developing your application before support for temporary URLs was introduced to the `local` driver, you may need to enable local temporary URLs. To do so, add the `serve` option to your `local` disk's configuration array within the `config/filesystems.php` configuration file:
```php
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true, // [tl! add]
'throw' => false,
],
```
<a name="s3-request-parameters"></a>
#### S3 Request Parameters
If you need to specify additional [S3 request parameters](https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectGET.html#RESTObjectGET-requests), you may pass the array of request parameters as the third argument to the `temporaryUrl` method:
$url = Storage::temporaryUrl(
'file.jpg',
now()->addMinutes(5),
[
'ResponseContentType' => 'application/octet-stream',
'ResponseContentDisposition' => 'attachment; filename=file2.jpg',
]
);
<a name="customizing-temporary-urls"></a>
#### Customizing Temporary URLs
If you need to customize how temporary URLs are created for a specific storage disk, you can use the `buildTemporaryUrlsUsing` method. For example, this can be useful if you have a controller that allows you to download files stored via a disk that doesn't typically support temporary URLs. Usually, this method should be called from the `boot` method of a service provider:
<?php
namespace App\Providers;
use DateTime;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Storage::disk('local')->buildTemporaryUrlsUsing(
function (string $path, DateTime $expiration, array $options) {
return URL::temporarySignedRoute(
'files.download',
$expiration,
array_merge($options, ['path' => $path])
);
}
);
}
}
<a name="temporary-upload-urls"></a>
#### Temporary Upload URLs
> [!WARNING]
> The ability to generate temporary upload URLs is only supported by the `s3` driver.
If you need to generate a temporary URL that can be used to upload a file directly from your client-side application, you may use the `temporaryUploadUrl` method. This method accepts a path and a `DateTime` instance specifying when the URL should expire. The `temporaryUploadUrl` method returns an associative array which may be destructured into the upload URL and the headers that should be included with the upload request:
use Illuminate\Support\Facades\Storage;
['url' => $url, 'headers' => $headers] = Storage::temporaryUploadUrl(
'file.jpg', now()->addMinutes(5)
);
This method is primarily useful in serverless environments that require the client-side application to directly upload files to a cloud storage system such as Amazon S3.
<a name="file-metadata"></a>
### File Metadata
In addition to reading and writing files, Laravel can also provide information about the files themselves. For example, the `size` method may be used to get the size of a file in bytes:
use Illuminate\Support\Facades\Storage;
$size = Storage::size('file.jpg');
The `lastModified` method returns the UNIX timestamp of the last time the file was modified:
$time = Storage::lastModified('file.jpg');
The MIME type of a given file may be obtained via the `mimeType` method:
$mime = Storage::mimeType('file.jpg');
<a name="file-paths"></a>
#### File Paths
You may use the `path` method to get the path for a given file. If you are using the `local` driver, this will return the absolute path to the file. If you are using the `s3` driver, this method will return the relative path to the file in the S3 bucket:
use Illuminate\Support\Facades\Storage;
$path = Storage::path('file.jpg');
<a name="storing-files"></a>
| |
243225
|
## Deleting Files
The `delete` method accepts a single filename or an array of files to delete:
use Illuminate\Support\Facades\Storage;
Storage::delete('file.jpg');
Storage::delete(['file.jpg', 'file2.jpg']);
If necessary, you may specify the disk that the file should be deleted from:
use Illuminate\Support\Facades\Storage;
Storage::disk('s3')->delete('path/file.jpg');
<a name="directories"></a>
## Directories
<a name="get-all-files-within-a-directory"></a>
#### Get All Files Within a Directory
The `files` method returns an array of all of the files in a given directory. If you would like to retrieve a list of all files within a given directory including all subdirectories, you may use the `allFiles` method:
use Illuminate\Support\Facades\Storage;
$files = Storage::files($directory);
$files = Storage::allFiles($directory);
<a name="get-all-directories-within-a-directory"></a>
#### Get All Directories Within a Directory
The `directories` method returns an array of all the directories within a given directory. Additionally, you may use the `allDirectories` method to get a list of all directories within a given directory and all of its subdirectories:
$directories = Storage::directories($directory);
$directories = Storage::allDirectories($directory);
<a name="create-a-directory"></a>
#### Create a Directory
The `makeDirectory` method will create the given directory, including any needed subdirectories:
Storage::makeDirectory($directory);
<a name="delete-a-directory"></a>
#### Delete a Directory
Finally, the `deleteDirectory` method may be used to remove a directory and all of its files:
Storage::deleteDirectory($directory);
<a name="testing"></a>
## Testing
The `Storage` facade's `fake` method allows you to easily generate a fake disk that, combined with the file generation utilities of the `Illuminate\Http\UploadedFile` class, greatly simplifies the testing of file uploads. For example:
```php tab=Pest
<?php
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
test('albums can be uploaded', function () {
Storage::fake('photos');
$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);
// Assert one or more files were stored...
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
// Assert one or more files were not stored...
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
// Assert that a given directory is empty...
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_albums_can_be_uploaded(): void
{
Storage::fake('photos');
$response = $this->json('POST', '/photos', [
UploadedFile::fake()->image('photo1.jpg'),
UploadedFile::fake()->image('photo2.jpg')
]);
// Assert one or more files were stored...
Storage::disk('photos')->assertExists('photo1.jpg');
Storage::disk('photos')->assertExists(['photo1.jpg', 'photo2.jpg']);
// Assert one or more files were not stored...
Storage::disk('photos')->assertMissing('missing.jpg');
Storage::disk('photos')->assertMissing(['missing.jpg', 'non-existing.jpg']);
// Assert that a given directory is empty...
Storage::disk('photos')->assertDirectoryEmpty('/wallpapers');
}
}
```
By default, the `fake` method will delete all files in its temporary directory. If you would like to keep these files, you may use the "persistentFake" method instead. For more information on testing file uploads, you may consult the [HTTP testing documentation's information on file uploads](/docs/{{version}}/http-tests#testing-file-uploads).
> [!WARNING]
> The `image` method requires the [GD extension](https://www.php.net/manual/en/book.image.php).
<a name="custom-filesystems"></a>
## Custom Filesystems
Laravel's Flysystem integration provides support for several "drivers" out of the box; however, Flysystem is not limited to these and has adapters for many other storage systems. You can create a custom driver if you want to use one of these additional adapters in your Laravel application.
In order to define a custom filesystem you will need a Flysystem adapter. Let's add a community maintained Dropbox adapter to our project:
```shell
composer require spatie/flysystem-dropbox
```
Next, you can register the driver within the `boot` method of one of your application's [service providers](/docs/{{version}}/providers). To accomplish this, you should use the `extend` method of the `Storage` facade:
<?php
namespace App\Providers;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\ServiceProvider;
use League\Flysystem\Filesystem;
use Spatie\Dropbox\Client as DropboxClient;
use Spatie\FlysystemDropbox\DropboxAdapter;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Storage::extend('dropbox', function (Application $app, array $config) {
$adapter = new DropboxAdapter(new DropboxClient(
$config['authorization_token']
));
return new FilesystemAdapter(
new Filesystem($adapter, $config),
$adapter,
$config
);
});
}
}
The first argument of the `extend` method is the name of the driver and the second is a closure that receives the `$app` and `$config` variables. The closure must return an instance of `Illuminate\Filesystem\FilesystemAdapter`. The `$config` variable contains the values defined in `config/filesystems.php` for the specified disk.
Once you have created and registered the extension's service provider, you may use the `dropbox` driver in your `config/filesystems.php` configuration file.
| |
243229
|
## Scope
<a name="specifying-the-scope"></a>
### Specifying the Scope
As discussed, features are typically checked against the currently authenticated user. However, this may not always suit your needs. Therefore, it is possible to specify the scope you would like to check a given feature against via the `Feature` facade's `for` method:
```php
return Feature::for($user)->active('new-api')
? $this->resolveNewApiResponse($request)
: $this->resolveLegacyApiResponse($request);
```
Of course, feature scopes are not limited to "users". Imagine you have built a new billing experience that you are rolling out to entire teams rather than individual users. Perhaps you would like the oldest teams to have a slower rollout than the newer teams. Your feature resolution closure might look something like the following:
```php
use App\Models\Team;
use Carbon\Carbon;
use Illuminate\Support\Lottery;
use Laravel\Pennant\Feature;
Feature::define('billing-v2', function (Team $team) {
if ($team->created_at->isAfter(new Carbon('1st Jan, 2023'))) {
return true;
}
if ($team->created_at->isAfter(new Carbon('1st Jan, 2019'))) {
return Lottery::odds(1 / 100);
}
return Lottery::odds(1 / 1000);
});
```
You will notice that the closure we have defined is not expecting a `User`, but is instead expecting a `Team` model. To determine if this feature is active for a user's team, you should pass the team to the `for` method offered by the `Feature` facade:
```php
if (Feature::for($user->team)->active('billing-v2')) {
return redirect('/billing/v2');
}
// ...
```
<a name="default-scope"></a>
### Default Scope
It is also possible to customize the default scope Pennant uses to check features. For example, maybe all of your features are checked against the currently authenticated user's team instead of the user. Instead of having to call `Feature::for($user->team)` every time you check a feature, you may instead specify the team as the default scope. Typically, this should be done in one of your application's service providers:
```php
<?php
namespace App\Providers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\ServiceProvider;
use Laravel\Pennant\Feature;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Feature::resolveScopeUsing(fn ($driver) => Auth::user()?->team);
// ...
}
}
```
If no scope is explicitly provided via the `for` method, the feature check will now use the currently authenticated user's team as the default scope:
```php
Feature::active('billing-v2');
// Is now equivalent to...
Feature::for($user->team)->active('billing-v2');
```
<a name="nullable-scope"></a>
### Nullable Scope
If the scope you provide when checking a feature is `null` and the feature's definition does not support `null` via a nullable type or by including `null` in a union type, Pennant will automatically return `false` as the feature's result value.
So, if the scope you are passing to a feature is potentially `null` and you want the feature's value resolver to be invoked, you should account for that in your feature's definition. A `null` scope may occur if you check a feature within an Artisan command, queued job, or unauthenticated route. Since there is usually not an authenticated user in these contexts, the default scope will be `null`.
If you do not always [explicitly specify your feature scope](#specifying-the-scope) then you should ensure the scope's type is "nullable" and handle the `null` scope value within your feature definition logic:
```php
use App\Models\User;
use Illuminate\Support\Lottery;
use Laravel\Pennant\Feature;
Feature::define('new-api', fn (User $user) => match (true) {// [tl! remove]
Feature::define('new-api', fn (User|null $user) => match (true) {// [tl! add]
$user === null => true,// [tl! add]
$user->isInternalTeamMember() => true,
$user->isHighTrafficCustomer() => false,
default => Lottery::odds(1 / 100),
});
```
<a name="identifying-scope"></a>
### Identifying Scope
Pennant's built-in `array` and `database` storage drivers know how to properly store scope identifiers for all PHP data types as well as Eloquent models. However, if your application utilizes a third-party Pennant driver, that driver may not know how to properly store an identifier for an Eloquent model or other custom types in your application.
In light of this, Pennant allows you to format scope values for storage by implementing the `FeatureScopeable` contract on the objects in your application that are used as Pennant scopes.
For example, imagine you are using two different feature drivers in a single application: the built-in `database` driver and a third-party "Flag Rocket" driver. The "Flag Rocket" driver does not know how to properly store an Eloquent model. Instead, it requires a `FlagRocketUser` instance. By implementing the `toFeatureIdentifier` defined by the `FeatureScopeable` contract, we can customize the storable scope value provided to each driver used by our application:
```php
<?php
namespace App\Models;
use FlagRocket\FlagRocketUser;
use Illuminate\Database\Eloquent\Model;
use Laravel\Pennant\Contracts\FeatureScopeable;
class User extends Model implements FeatureScopeable
{
/**
* Cast the object to a feature scope identifier for the given driver.
*/
public function toFeatureIdentifier(string $driver): mixed
{
return match($driver) {
'database' => $this,
'flag-rocket' => FlagRocketUser::fromId($this->flag_rocket_id),
};
}
}
```
<a name="serializing-scope"></a>
### Serializing Scope
By default, Pennant will use a fully qualified class name when storing a feature associated with an Eloquent model. If you are already using an [Eloquent morph map](/docs/{{version}}/eloquent-relationships#custom-polymorphic-types), you may choose to have Pennant also use the morph map to decouple the stored feature from your application structure.
To achieve this, after defining your Eloquent morph map in a service provider, you may invoke the `Feature` facade's `useMorphMap` method:
```php
use Illuminate\Database\Eloquent\Relations\Relation;
use Laravel\Pennant\Feature;
Relation::enforceMorphMap([
'post' => 'App\Models\Post',
'video' => 'App\Models\Video',
]);
Feature::useMorphMap();
```
<a name="rich-feature-values"></a>
## Rich Feature Values
Until now, we have primarily shown features as being in a binary state, meaning they are either "active" or "inactive", but Pennant also allows you to store rich values as well.
For example, imagine you are testing three new colors for the "Buy now" button of your application. Instead of returning `true` or `false` from the feature definition, you may instead return a string:
```php
use Illuminate\Support\Arr;
use Laravel\Pennant\Feature;
Feature::define('purchase-button', fn (User $user) => Arr::random([
'blue-sapphire',
'seafoam-green',
'tart-orange',
]));
```
You may retrieve the value of the `purchase-button` feature using the `value` method:
```php
$color = Feature::value('purchase-button');
```
Pennant's included Blade directive also makes it easy to conditionally render content based on the current value of the feature:
```blade
@feature('purchase-button', 'blue-sapphire')
<!-- 'blue-sapphire' is active -->
@elsefeature('purchase-button', 'seafoam-green')
<!-- 'seafoam-green' is active -->
@elsefeature('purchase-button', 'tart-orange')
<!-- 'tart-orange' is active -->
@endfeature
```
> [!NOTE]
> When using rich values, it is important to know that a feature is considered "active" when it has any value other than `false`.
When calling the [conditional `when`](#conditional-execution) method, the feature's rich value will be provided to the first closure:
Feature::when('purchase-button',
fn ($color) => /* ... */,
fn () => /* ... */,
);
Likewise, when calling the conditional `unless` method, the feature's rich value will be provided to the optional second closure:
Feature::unless('purchase-button',
fn () => /* ... */,
fn ($color) => /* ... */,
);
<a name="retrieving-multiple-features"></a>
| |
243232
|
# HTTP Tests
- [Introduction](#introduction)
- [Making Requests](#making-requests)
- [Customizing Request Headers](#customizing-request-headers)
- [Cookies](#cookies)
- [Session / Authentication](#session-and-authentication)
- [Debugging Responses](#debugging-responses)
- [Exception Handling](#exception-handling)
- [Testing JSON APIs](#testing-json-apis)
- [Fluent JSON Testing](#fluent-json-testing)
- [Testing File Uploads](#testing-file-uploads)
- [Testing Views](#testing-views)
- [Rendering Blade and Components](#rendering-blade-and-components)
- [Available Assertions](#available-assertions)
- [Response Assertions](#response-assertions)
- [Authentication Assertions](#authentication-assertions)
- [Validation Assertions](#validation-assertions)
<a name="introduction"></a>
## Introduction
Laravel provides a very fluent API for making HTTP requests to your application and examining the responses. For example, take a look at the feature test defined below:
```php tab=Pest
<?php
test('the application returns a successful response', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_the_application_returns_a_successful_response(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
```
The `get` method makes a `GET` request into the application, while the `assertStatus` method asserts that the returned response should have the given HTTP status code. In addition to this simple assertion, Laravel also contains a variety of assertions for inspecting the response headers, content, JSON structure, and more.
<a name="making-requests"></a>
## Making Requests
To make a request to your application, you may invoke the `get`, `post`, `put`, `patch`, or `delete` methods within your test. These methods do not actually issue a "real" HTTP request to your application. Instead, the entire network request is simulated internally.
Instead of returning an `Illuminate\Http\Response` instance, test request methods return an instance of `Illuminate\Testing\TestResponse`, which provides a [variety of helpful assertions](#available-assertions) that allow you to inspect your application's responses:
```php tab=Pest
<?php
test('basic request', function () {
$response = $this->get('/');
$response->assertStatus(200);
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_a_basic_request(): void
{
$response = $this->get('/');
$response->assertStatus(200);
}
}
```
In general, each of your tests should only make one request to your application. Unexpected behavior may occur if multiple requests are executed within a single test method.
> [!NOTE]
> For convenience, the CSRF middleware is automatically disabled when running tests.
<a name="customizing-request-headers"></a>
### Customizing Request Headers
You may use the `withHeaders` method to customize the request's headers before it is sent to the application. This method allows you to add any custom headers you would like to the request:
```php tab=Pest
<?php
test('interacting with headers', function () {
$response = $this->withHeaders([
'X-Header' => 'Value',
])->post('/user', ['name' => 'Sally']);
$response->assertStatus(201);
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic functional test example.
*/
public function test_interacting_with_headers(): void
{
$response = $this->withHeaders([
'X-Header' => 'Value',
])->post('/user', ['name' => 'Sally']);
$response->assertStatus(201);
}
}
```
<a name="cookies"></a>
### Cookies
You may use the `withCookie` or `withCookies` methods to set cookie values before making a request. The `withCookie` method accepts a cookie name and value as its two arguments, while the `withCookies` method accepts an array of name / value pairs:
```php tab=Pest
<?php
test('interacting with cookies', function () {
$response = $this->withCookie('color', 'blue')->get('/');
$response = $this->withCookies([
'color' => 'blue',
'name' => 'Taylor',
])->get('/');
//
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_interacting_with_cookies(): void
{
$response = $this->withCookie('color', 'blue')->get('/');
$response = $this->withCookies([
'color' => 'blue',
'name' => 'Taylor',
])->get('/');
//
}
}
```
<a name="session-and-authentication"></a>
### Session / Authentication
Laravel provides several helpers for interacting with the session during HTTP testing. First, you may set the session data to a given array using the `withSession` method. This is useful for loading the session with data before issuing a request to your application:
```php tab=Pest
<?php
test('interacting with the session', function () {
$response = $this->withSession(['banned' => false])->get('/');
//
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_interacting_with_the_session(): void
{
$response = $this->withSession(['banned' => false])->get('/');
//
}
}
```
Laravel's session is typically used to maintain state for the currently authenticated user. Therefore, the `actingAs` helper method provides a simple way to authenticate a given user as the current user. For example, we may use a [model factory](/docs/{{version}}/eloquent-factories) to generate and authenticate a user:
```php tab=Pest
<?php
use App\Models\User;
test('an action that requires authentication', function () {
$user = User::factory()->create();
$response = $this->actingAs($user)
->withSession(['banned' => false])
->get('/');
//
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use App\Models\User;
use Tests\TestCase;
class ExampleTest extends TestCase
{
public function test_an_action_that_requires_authentication(): void
{
$user = User::factory()->create();
$response = $this->actingAs($user)
->withSession(['banned' => false])
->get('/');
//
}
}
```
You may also specify which guard should be used to authenticate the given user by passing the guard name as the second argument to the `actingAs` method. The guard that is provided to the `actingAs` method will also become the default guard for the duration of the test:
$this->actingAs($user, 'web')
<a name="debugging-responses"></a>
### Debugging Responses
After making a test request to your application, the `dump`, `dumpHeaders`, and `dumpSession` methods may be used to examine and debug the response contents:
```php tab=Pest
<?php
test('basic test', function () {
$response = $this->get('/');
$response->dumpHeaders();
$response->dumpSession();
$response->dump();
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_basic_test(): void
{
$response = $this->get('/');
$response->dumpHeaders();
$response->dumpSession();
$response->dump();
}
}
```
Alternatively, you may use the `dd`, `ddHeaders`, and `ddSession` methods to dump information about the response and then stop execution:
```php tab=Pest
<?php
test('basic test', function () {
$response = $this->get('/');
$response->ddHeaders();
$response->ddSession();
$response->dd();
});
```
```php tab=PHPUnit
<?php
namespace Tests\Feature;
use Tests\TestCase;
class ExampleTest extends TestCase
{
/**
* A basic test example.
*/
public function test_basic_test(): void
{
$response = $this->get('/');
$response->ddHeaders();
$response->ddSession();
$response->dd();
}
}
```
<a name="exception-handling"></a>
| |
243241
|
## Running SQL Queries
Once you have configured your database connection, you may run queries using the `DB` facade. The `DB` facade provides methods for each type of query: `select`, `update`, `insert`, `delete`, and `statement`.
<a name="running-a-select-query"></a>
#### Running a Select Query
To run a basic SELECT query, you may use the `select` method on the `DB` facade:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class UserController extends Controller
{
/**
* Show a list of all of the application's users.
*/
public function index(): View
{
$users = DB::select('select * from users where active = ?', [1]);
return view('user.index', ['users' => $users]);
}
}
The first argument passed to the `select` method is the SQL query, while the second argument is any parameter bindings that need to be bound to the query. Typically, these are the values of the `where` clause constraints. Parameter binding provides protection against SQL injection.
The `select` method will always return an `array` of results. Each result within the array will be a PHP `stdClass` object representing a record from the database:
use Illuminate\Support\Facades\DB;
$users = DB::select('select * from users');
foreach ($users as $user) {
echo $user->name;
}
<a name="selecting-scalar-values"></a>
#### Selecting Scalar Values
Sometimes your database query may result in a single, scalar value. Instead of being required to retrieve the query's scalar result from a record object, Laravel allows you to retrieve this value directly using the `scalar` method:
$burgers = DB::scalar(
"select count(case when food = 'burger' then 1 end) as burgers from menu"
);
<a name="selecting-multiple-result-sets"></a>
#### Selecting Multiple Result Sets
If your application calls stored procedures that return multiple result sets, you may use the `selectResultSets` method to retrieve all of the result sets returned by the stored procedure:
[$options, $notifications] = DB::selectResultSets(
"CALL get_user_options_and_notifications(?)", $request->user()->id
);
<a name="using-named-bindings"></a>
#### Using Named Bindings
Instead of using `?` to represent your parameter bindings, you may execute a query using named bindings:
$results = DB::select('select * from users where id = :id', ['id' => 1]);
<a name="running-an-insert-statement"></a>
#### Running an Insert Statement
To execute an `insert` statement, you may use the `insert` method on the `DB` facade. Like `select`, this method accepts the SQL query as its first argument and bindings as its second argument:
use Illuminate\Support\Facades\DB;
DB::insert('insert into users (id, name) values (?, ?)', [1, 'Marc']);
<a name="running-an-update-statement"></a>
#### Running an Update Statement
The `update` method should be used to update existing records in the database. The number of rows affected by the statement is returned by the method:
use Illuminate\Support\Facades\DB;
$affected = DB::update(
'update users set votes = 100 where name = ?',
['Anita']
);
<a name="running-a-delete-statement"></a>
#### Running a Delete Statement
The `delete` method should be used to delete records from the database. Like `update`, the number of rows affected will be returned by the method:
use Illuminate\Support\Facades\DB;
$deleted = DB::delete('delete from users');
<a name="running-a-general-statement"></a>
#### Running a General Statement
Some database statements do not return any value. For these types of operations, you may use the `statement` method on the `DB` facade:
DB::statement('drop table users');
<a name="running-an-unprepared-statement"></a>
#### Running an Unprepared Statement
Sometimes you may want to execute an SQL statement without binding any values. You may use the `DB` facade's `unprepared` method to accomplish this:
DB::unprepared('update users set votes = 100 where name = "Dries"');
> [!WARNING]
> Since unprepared statements do not bind parameters, they may be vulnerable to SQL injection. You should never allow user controlled values within an unprepared statement.
<a name="implicit-commits-in-transactions"></a>
#### Implicit Commits
When using the `DB` facade's `statement` and `unprepared` methods within transactions you must be careful to avoid statements that cause [implicit commits](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html). These statements will cause the database engine to indirectly commit the entire transaction, leaving Laravel unaware of the database's transaction level. An example of such a statement is creating a database table:
DB::unprepared('create table a (col varchar(1) null)');
Please refer to the MySQL manual for [a list of all statements](https://dev.mysql.com/doc/refman/8.0/en/implicit-commit.html) that trigger implicit commits.
<a name="using-multiple-database-connections"></a>
### Using Multiple Database Connections
If your application defines multiple connections in your `config/database.php` configuration file, you may access each connection via the `connection` method provided by the `DB` facade. The connection name passed to the `connection` method should correspond to one of the connections listed in your `config/database.php` configuration file or configured at runtime using the `config` helper:
use Illuminate\Support\Facades\DB;
$users = DB::connection('sqlite')->select(/* ... */);
You may access the raw, underlying PDO instance of a connection using the `getPdo` method on a connection instance:
$pdo = DB::connection()->getPdo();
<a name="listening-for-query-events"></a>
### Listening for Query Events
If you would like to specify a closure that is invoked for each SQL query executed by your application, you may use the `DB` facade's `listen` method. This method can be useful for logging queries or debugging. You may register your query listener closure in the `boot` method of a [service provider](/docs/{{version}}/providers):
<?php
namespace App\Providers;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
DB::listen(function (QueryExecuted $query) {
// $query->sql;
// $query->bindings;
// $query->time;
// $query->toRawSql();
});
}
}
<a name="monitoring-cumulative-query-time"></a>
### Monitoring Cumulative Query Time
A common performance bottleneck of modern web applications is the amount of time they spend querying databases. Thankfully, Laravel can invoke a closure or callback of your choice when it spends too much time querying the database during a single request. To get started, provide a query time threshold (in milliseconds) and closure to the `whenQueryingForLongerThan` method. You may invoke this method in the `boot` method of a [service provider](/docs/{{version}}/providers):
<?php
namespace App\Providers;
use Illuminate\Database\Connection;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\ServiceProvider;
use Illuminate\Database\Events\QueryExecuted;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
// ...
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
DB::whenQueryingForLongerThan(500, function (Connection $connection, QueryExecuted $event) {
// Notify development team...
});
}
}
<a name="database-transactions"></a>
| |
243253
|
# Upgrade Guide
## Upgrading from Breeze 1.x to Breeze 2.x
#### Dependency Changes
Unlike other starter kits such as Jetstream, the Laravel Breeze dependency can be removed after you run the `breeze:install` Artisan command. Therefore, if you are in the process of upgrading to Laravel 11, we advise you to simply remove the `laravel/breeze` dependency from your application's `composer.json` file. Then, run the `composer update` command:
composer update
| |
243256
|
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
/**
* The root template that is loaded on the first page visit.
*
* @var string
*/
protected $rootView = 'app';
/**
* Determine the current asset version.
*/
public function version(Request $request): ?string
{
return parent::version($request);
}
/**
* Define the props that are shared by default.
*
* @return array<string, mixed>
*/
public function share(Request $request): array
{
return [
...parent::share($request),
'auth' => [
'user' => $request->user(),
],
];
}
}
| |
243265
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): Response
{
return Inertia::render('Auth/Register');
}
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => 'required|string|max:255',
'email' => 'required|string|lowercase|email|max:255|unique:'.User::class,
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('dashboard', absolute: false));
}
}
| |
243269
|
<?php
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\ConfirmablePasswordController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Auth\VerifyEmailController;
use Illuminate\Support\Facades\Route;
Route::middleware('guest')->group(function () {
Route::get('register', [RegisteredUserController::class, 'create'])
->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])
->name('password.request');
Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])
->name('password.email');
Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])
->name('password.reset');
Route::post('reset-password', [NewPasswordController::class, 'store'])
->name('password.store');
});
Route::middleware('auth')->group(function () {
Route::get('verify-email', EmailVerificationPromptController::class)
->name('verification.notice');
Route::get('verify-email/{id}/{hash}', VerifyEmailController::class)
->middleware(['signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware('throttle:6,1')
->name('verification.send');
Route::get('confirm-password', [ConfirmablePasswordController::class, 'show'])
->name('password.confirm');
Route::post('confirm-password', [ConfirmablePasswordController::class, 'store']);
Route::put('password', [PasswordController::class, 'update'])->name('password.update');
Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
});
| |
243270
|
<?php
use App\Http\Controllers\ProfileController;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Route;
use Inertia\Inertia;
Route::get('/', function () {
return Inertia::render('Welcome', [
'canLogin' => Route::has('login'),
'canRegister' => Route::has('register'),
'laravelVersion' => Application::VERSION,
'phpVersion' => PHP_VERSION,
]);
});
Route::get('/dashboard', function () {
return Inertia::render('Dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
require __DIR__.'/auth.php';
| |
243275
|
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Laravel</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,600&display=swap" rel="stylesheet" />
<!-- Styles -->
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="antialiased font-sans">
<div class="bg-gray-50 text-black/50 dark:bg-black dark:text-white/50">
<img id="background" class="absolute -left-20 top-0 max-w-[877px]" src="https://laravel.com/assets/img/welcome/background.svg" />
<div class="relative min-h-screen flex flex-col items-center justify-center selection:bg-[#FF2D20] selection:text-white">
<div class="relative w-full max-w-2xl px-6 lg:max-w-7xl">
<header class="grid grid-cols-2 items-center gap-2 py-10 lg:grid-cols-3">
<div class="flex lg:justify-center lg:col-start-2">
| |
243285
|
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="preconnect" href="https://fonts.bunny.net">
<link href="https://fonts.bunny.net/css?family=figtree:400,500,600&display=swap" rel="stylesheet" />
<!-- Scripts -->
@vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body class="font-sans antialiased">
<div class="min-h-screen bg-gray-100 dark:bg-gray-900">
<livewire:layout.navigation />
<!-- Page Heading -->
@if (isset($header))
<header class="bg-white dark:bg-gray-800 shadow">
<div class="max-w-7xl mx-auto py-6 px-4 sm:px-6 lg:px-8">
{{ $header }}
</div>
</header>
@endif
<!-- Page Content -->
<main>
{{ $slot }}
</main>
</div>
</body>
</html>
| |
243294
|
<?php
use Illuminate\Support\Facades\Route;
Route::view('/', 'welcome');
Route::view('dashboard', 'dashboard')
->middleware(['auth', 'verified'])
->name('dashboard');
Route::view('profile', 'profile')
->middleware(['auth'])
->name('profile');
require __DIR__.'/auth.php';
| |
243305
|
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
| |
243314
|
<script setup>
import { computed, onMounted, onUnmounted, ref } from 'vue';
const props = defineProps({
align: {
type: String,
default: 'right',
},
width: {
type: String,
default: '48',
},
contentClasses: {
type: String,
default: 'py-1 bg-white dark:bg-gray-700',
},
});
const closeOnEscape = (e) => {
if (open.value && e.key === 'Escape') {
open.value = false;
}
};
onMounted(() => document.addEventListener('keydown', closeOnEscape));
onUnmounted(() => document.removeEventListener('keydown', closeOnEscape));
const widthClass = computed(() => {
return {
48: 'w-48',
}[props.width.toString()];
});
const alignmentClasses = computed(() => {
if (props.align === 'left') {
return 'ltr:origin-top-left rtl:origin-top-right start-0';
} else if (props.align === 'right') {
return 'ltr:origin-top-right rtl:origin-top-left end-0';
} else {
return 'origin-top';
}
});
const open = ref(false);
</script>
<template>
<div class="relative">
<div @click="open = !open">
<slot name="trigger" />
</div>
<!-- Full Screen Dropdown Overlay -->
<div
v-show="open"
class="fixed inset-0 z-40"
@click="open = false"
></div>
<Transition
enter-active-class="transition ease-out duration-200"
enter-from-class="opacity-0 scale-95"
enter-to-class="opacity-100 scale-100"
leave-active-class="transition ease-in duration-75"
leave-from-class="opacity-100 scale-100"
leave-to-class="opacity-0 scale-95"
>
<div
v-show="open"
class="absolute z-50 mt-2 rounded-md shadow-lg"
:class="[widthClass, alignmentClasses]"
style="display: none"
@click="open = false"
>
<div
class="rounded-md ring-1 ring-black ring-opacity-5"
:class="contentClasses"
>
<slot name="content" />
</div>
</div>
</Transition>
</div>
</template>
| |
243318
|
<script setup>
import { computed } from 'vue';
const emit = defineEmits(['update:checked']);
const props = defineProps({
checked: {
type: [Array, Boolean],
required: true,
},
value: {
default: null,
},
});
const proxyChecked = computed({
get() {
return props.checked;
},
set(val) {
emit('update:checked', val);
},
});
</script>
<template>
<input
type="checkbox"
:value="value"
v-model="proxyChecked"
class="rounded border-gray-300 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:border-gray-700 dark:bg-gray-900 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800"
/>
</template>
| |
243322
|
<script setup>
import { ref } from 'vue';
import ApplicationLogo from '@/Components/ApplicationLogo.vue';
import Dropdown from '@/Components/Dropdown.vue';
import DropdownLink from '@/Components/DropdownLink.vue';
import NavLink from '@/Components/NavLink.vue';
import ResponsiveNavLink from '@/Components/ResponsiveNavLink.vue';
import { Link } from '@inertiajs/vue3';
const showingNavigationDropdown = ref(false);
</script>
<template>
<div>
<div class="min-h-screen bg-gray-100 dark:bg-gray-900">
<nav
class="border-b border-gray-100 bg-white dark:border-gray-700 dark:bg-gray-800"
>
<!-- Primary Navigation Menu -->
<div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div class="flex h-16 justify-between">
<div class="flex">
<!-- Logo -->
<div class="flex shrink-0 items-center">
<Link :href="route('dashboard')">
<ApplicationLogo
class="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200"
/>
</Link>
</div>
<!-- Navigation Links -->
<div
class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex"
>
<NavLink
:href="route('dashboard')"
:active="route().current('dashboard')"
>
Dashboard
</NavLink>
</div>
</div>
<div class="hidden sm:ms-6 sm:flex sm:items-center">
<!-- Settings Dropdown -->
<div class="relative ms-3">
<Dropdown align="right" width="48">
<template #trigger>
<span class="inline-flex rounded-md">
<button
type="button"
class="inline-flex items-center rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium leading-4 text-gray-500 transition duration-150 ease-in-out hover:text-gray-700 focus:outline-none dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300"
>
{{ $page.props.auth.user.name }}
<svg
class="-me-0.5 ms-2 h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clip-rule="evenodd"
/>
</svg>
</button>
</span>
</template>
<template #content>
<DropdownLink
:href="route('profile.edit')"
>
Profile
</DropdownLink>
<DropdownLink
:href="route('logout')"
method="post"
as="button"
>
Log Out
</DropdownLink>
</template>
</Dropdown>
</div>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button
@click="
showingNavigationDropdown =
!showingNavigationDropdown
"
class="inline-flex items-center justify-center rounded-md p-2 text-gray-400 transition duration-150 ease-in-out hover:bg-gray-100 hover:text-gray-500 focus:bg-gray-100 focus:text-gray-500 focus:outline-none dark:text-gray-500 dark:hover:bg-gray-900 dark:hover:text-gray-400 dark:focus:bg-gray-900 dark:focus:text-gray-400"
>
<svg
class="h-6 w-6"
stroke="currentColor"
fill="none"
viewBox="0 0 24 24"
>
<path
:class="{
hidden: showingNavigationDropdown,
'inline-flex':
!showingNavigationDropdown,
}"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 12h16M4 18h16"
/>
<path
:class="{
hidden: !showingNavigationDropdown,
'inline-flex':
showingNavigationDropdown,
}"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div
:class="{
block: showingNavigationDropdown,
hidden: !showingNavigationDropdown,
}"
class="sm:hidden"
>
<div class="space-y-1 pb-3 pt-2">
<ResponsiveNavLink
:href="route('dashboard')"
:active="route().current('dashboard')"
>
Dashboard
</ResponsiveNavLink>
</div>
<!-- Responsive Settings Options -->
<div
class="border-t border-gray-200 pb-1 pt-4 dark:border-gray-600"
>
<div class="px-4">
<div
class="text-base font-medium text-gray-800 dark:text-gray-200"
>
{{ $page.props.auth.user.name }}
</div>
<div class="text-sm font-medium text-gray-500">
{{ $page.props.auth.user.email }}
</div>
</div>
<div class="mt-3 space-y-1">
<ResponsiveNavLink :href="route('profile.edit')">
Profile
</ResponsiveNavLink>
<ResponsiveNavLink
:href="route('logout')"
method="post"
as="button"
>
Log Out
</ResponsiveNavLink>
</div>
</div>
</div>
</nav>
<!-- Page Heading -->
<header
class="bg-white shadow dark:bg-gray-800"
v-if="$slots.header"
>
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
<slot name="header" />
</div>
</header>
<!-- Page Content -->
<main>
<slot />
</main>
</div>
</div>
</template>
| |
243359
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*/
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
| |
243360
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): View
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('dashboard', absolute: false));
}
}
| |
243367
|
<x-guest-layout>
<form method="POST" action="{{ route('password.store') }}">
@csrf
<!-- Password Reset Token -->
<input type="hidden" name="token" value="{{ $request->route('token') }}">
<!-- Email Address -->
<div>
<x-input-label for="email" :value="__('Email')" />
<x-text-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email', $request->email)" required autofocus autocomplete="username" />
<x-input-error :messages="$errors->get('email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input id="password" class="block mt-1 w-full" type="password" name="password" required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password')" class="mt-2" />
</div>
<!-- Confirm Password -->
<div class="mt-4">
<x-input-label for="password_confirmation" :value="__('Confirm Password')" />
<x-text-input id="password_confirmation" class="block mt-1 w-full"
type="password"
name="password_confirmation" required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password_confirmation')" class="mt-2" />
</div>
<div class="flex items-center justify-end mt-4">
<x-primary-button>
{{ __('Reset Password') }}
</x-primary-button>
</div>
</form>
</x-guest-layout>
| |
243368
|
<x-guest-layout>
<form method="POST" action="{{ route('register') }}">
@csrf
<!-- Name -->
<div>
<x-input-label for="name" :value="__('Name')" />
<x-text-input id="name" class="block mt-1 w-full" type="text" name="name" :value="old('name')" required autofocus autocomplete="name" />
<x-input-error :messages="$errors->get('name')" class="mt-2" />
</div>
<!-- Email Address -->
<div class="mt-4">
<x-input-label for="email" :value="__('Email')" />
<x-text-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autocomplete="username" />
<x-input-error :messages="$errors->get('email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password')" class="mt-2" />
</div>
<!-- Confirm Password -->
<div class="mt-4">
<x-input-label for="password_confirmation" :value="__('Confirm Password')" />
<x-text-input id="password_confirmation" class="block mt-1 w-full"
type="password"
name="password_confirmation" required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password_confirmation')" class="mt-2" />
</div>
<div class="flex items-center justify-end mt-4">
<a class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800" href="{{ route('login') }}">
{{ __('Already registered?') }}
</a>
<x-primary-button class="ms-4">
{{ __('Register') }}
</x-primary-button>
</div>
</form>
</x-guest-layout>
| |
243372
|
<x-guest-layout>
<!-- Session Status -->
<x-auth-session-status class="mb-4" :status="session('status')" />
<form method="POST" action="{{ route('login') }}">
@csrf
<!-- Email Address -->
<div>
<x-input-label for="email" :value="__('Email')" />
<x-text-input id="email" class="block mt-1 w-full" type="email" name="email" :value="old('email')" required autofocus autocomplete="username" />
<x-input-error :messages="$errors->get('email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="current-password" />
<x-input-error :messages="$errors->get('password')" class="mt-2" />
</div>
<!-- Remember Me -->
<div class="block mt-4">
<label for="remember_me" class="inline-flex items-center">
<input id="remember_me" type="checkbox" class="rounded dark:bg-gray-900 border-gray-300 dark:border-gray-700 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800" name="remember">
<span class="ms-2 text-sm text-gray-600 dark:text-gray-400">{{ __('Remember me') }}</span>
</label>
</div>
<div class="flex items-center justify-end mt-4">
@if (Route::has('password.request'))
<a class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800" href="{{ route('password.request') }}">
{{ __('Forgot your password?') }}
</a>
@endif
<x-primary-button class="ms-3">
{{ __('Log in') }}
</x-primary-button>
</div>
</form>
</x-guest-layout>
| |
243373
|
<a {{ $attributes->merge(['class' => 'block w-full px-4 py-2 text-start text-sm leading-5 text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-800 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-800 transition duration-150 ease-in-out']) }}>{{ $slot }}</a>
| |
243381
|
@props(['align' => 'right', 'width' => '48', 'contentClasses' => 'py-1 bg-white dark:bg-gray-700'])
@php
$alignmentClasses = match ($align) {
'left' => 'ltr:origin-top-left rtl:origin-top-right start-0',
'top' => 'origin-top',
default => 'ltr:origin-top-right rtl:origin-top-left end-0',
};
$width = match ($width) {
'48' => 'w-48',
default => $width,
};
@endphp
<div class="relative" x-data="{ open: false }" @click.outside="open = false" @close.stop="open = false">
<div @click="open = ! open">
{{ $trigger }}
</div>
<div x-show="open"
x-transition:enter="transition ease-out duration-200"
x-transition:enter-start="opacity-0 scale-95"
x-transition:enter-end="opacity-100 scale-100"
x-transition:leave="transition ease-in duration-75"
x-transition:leave-start="opacity-100 scale-100"
x-transition:leave-end="opacity-0 scale-95"
class="absolute z-50 mt-2 {{ $width }} rounded-md shadow-lg {{ $alignmentClasses }}"
style="display: none;"
@click="open = false">
<div class="rounded-md ring-1 ring-black ring-opacity-5 {{ $contentClasses }}">
{{ $content }}
</div>
</div>
</div>
| |
243390
|
<nav x-data="{ open: false }" class="bg-white dark:bg-gray-800 border-b border-gray-100 dark:border-gray-700">
<!-- Primary Navigation Menu -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<!-- Logo -->
<div class="shrink-0 flex items-center">
<a href="{{ route('dashboard') }}">
<x-application-logo class="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200" />
</a>
</div>
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex">
<x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
{{ __('Dashboard') }}
</x-nav-link>
</div>
</div>
<!-- Settings Dropdown -->
<div class="hidden sm:flex sm:items-center sm:ms-6">
<x-dropdown align="right" width="48">
<x-slot name="trigger">
<button class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:text-gray-700 dark:hover:text-gray-300 focus:outline-none transition ease-in-out duration-150">
<div>{{ Auth::user()->name }}</div>
<div class="ms-1">
<svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</div>
</button>
</x-slot>
<x-slot name="content">
<x-dropdown-link :href="route('profile.edit')">
{{ __('Profile') }}
</x-dropdown-link>
<!-- Authentication -->
<form method="POST" action="{{ route('logout') }}">
@csrf
<x-dropdown-link :href="route('logout')"
onclick="event.preventDefault();
this.closest('form').submit();">
{{ __('Log Out') }}
</x-dropdown-link>
</form>
</x-slot>
</x-dropdown>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-900 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-500 dark:focus:text-gray-400 transition duration-150 ease-in-out">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
<path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
<div class="pt-2 pb-3 space-y-1">
<x-responsive-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')">
{{ __('Dashboard') }}
</x-responsive-nav-link>
</div>
<!-- Responsive Settings Options -->
<div class="pt-4 pb-1 border-t border-gray-200 dark:border-gray-600">
<div class="px-4">
<div class="font-medium text-base text-gray-800 dark:text-gray-200">{{ Auth::user()->name }}</div>
<div class="font-medium text-sm text-gray-500">{{ Auth::user()->email }}</div>
</div>
<div class="mt-3 space-y-1">
<x-responsive-nav-link :href="route('profile.edit')">
{{ __('Profile') }}
</x-responsive-nav-link>
<!-- Authentication -->
<form method="POST" action="{{ route('logout') }}">
@csrf
<x-responsive-nav-link :href="route('logout')"
onclick="event.preventDefault();
this.closest('form').submit();">
{{ __('Log Out') }}
</x-responsive-nav-link>
</form>
</div>
</div>
</div>
</nav>
| |
243400
|
<?php
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\ConfirmablePasswordController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\EmailVerificationPromptController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Auth\VerifyEmailController;
use Illuminate\Support\Facades\Route;
Route::middleware('guest')->group(function () {
Route::get('register', [RegisteredUserController::class, 'create'])
->name('register');
Route::post('register', [RegisteredUserController::class, 'store']);
Route::get('login', [AuthenticatedSessionController::class, 'create'])
->name('login');
Route::post('login', [AuthenticatedSessionController::class, 'store']);
Route::get('forgot-password', [PasswordResetLinkController::class, 'create'])
->name('password.request');
Route::post('forgot-password', [PasswordResetLinkController::class, 'store'])
->name('password.email');
Route::get('reset-password/{token}', [NewPasswordController::class, 'create'])
->name('password.reset');
Route::post('reset-password', [NewPasswordController::class, 'store'])
->name('password.store');
});
Route::middleware('auth')->group(function () {
Route::get('verify-email', EmailVerificationPromptController::class)
->name('verification.notice');
Route::get('verify-email/{id}/{hash}', VerifyEmailController::class)
->middleware(['signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware('throttle:6,1')
->name('verification.send');
Route::get('confirm-password', [ConfirmablePasswordController::class, 'show'])
->name('password.confirm');
Route::post('confirm-password', [ConfirmablePasswordController::class, 'store']);
Route::put('password', [PasswordController::class, 'update'])->name('password.update');
Route::post('logout', [AuthenticatedSessionController::class, 'destroy'])
->name('logout');
});
| |
243401
|
<?php
use App\Http\Controllers\ProfileController;
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Route::get('/dashboard', function () {
return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware('auth')->group(function () {
Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');
});
require __DIR__.'/auth.php';
| |
243412
|
<?php
use App\Livewire\Actions\Logout;
use Livewire\Volt\Component;
new class extends Component
{
/**
* Log the current user out of the application.
*/
public function logout(Logout $logout): void
{
$logout();
$this->redirect('/', navigate: true);
}
}; ?>
<nav x-data="{ open: false }" class="bg-white dark:bg-gray-800 border-b border-gray-100 dark:border-gray-700">
<!-- Primary Navigation Menu -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<!-- Logo -->
<div class="shrink-0 flex items-center">
<a href="{{ route('dashboard') }}" wire:navigate>
<x-application-logo class="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200" />
</a>
</div>
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex">
<x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')" wire:navigate>
{{ __('Dashboard') }}
</x-nav-link>
</div>
</div>
<!-- Settings Dropdown -->
<div class="hidden sm:flex sm:items-center sm:ms-6">
<x-dropdown align="right" width="48">
<x-slot name="trigger">
<button class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:text-gray-700 dark:hover:text-gray-300 focus:outline-none transition ease-in-out duration-150">
<div x-data="{{ json_encode(['name' => auth()->user()->name]) }}" x-text="name" x-on:profile-updated.window="name = $event.detail.name"></div>
<div class="ms-1">
<svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</div>
</button>
</x-slot>
<x-slot name="content">
<x-dropdown-link :href="route('profile')" wire:navigate>
{{ __('Profile') }}
</x-dropdown-link>
<!-- Authentication -->
<button wire:click="logout" class="w-full text-start">
<x-dropdown-link>
{{ __('Log Out') }}
</x-dropdown-link>
</button>
</x-slot>
</x-dropdown>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-900 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-500 dark:focus:text-gray-400 transition duration-150 ease-in-out">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
<path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
<div class="pt-2 pb-3 space-y-1">
<x-responsive-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')" wire:navigate>
{{ __('Dashboard') }}
</x-responsive-nav-link>
</div>
<!-- Responsive Settings Options -->
<div class="pt-4 pb-1 border-t border-gray-200 dark:border-gray-600">
<div class="px-4">
<div class="font-medium text-base text-gray-800 dark:text-gray-200" x-data="{{ json_encode(['name' => auth()->user()->name]) }}" x-text="name" x-on:profile-updated.window="name = $event.detail.name"></div>
<div class="font-medium text-sm text-gray-500">{{ auth()->user()->email }}</div>
</div>
<div class="mt-3 space-y-1">
<x-responsive-nav-link :href="route('profile')" wire:navigate>
{{ __('Profile') }}
</x-responsive-nav-link>
<!-- Authentication -->
<button wire:click="logout" class="w-full text-start">
<x-responsive-nav-link>
{{ __('Log Out') }}
</x-responsive-nav-link>
</button>
</div>
</div>
</div>
</nav>
| |
243418
|
<?php
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Livewire\Attributes\Layout;
use Livewire\Volt\Component;
new #[Layout('layouts.guest')] class extends Component
{
public string $name = '';
public string $email = '';
public string $password = '';
public string $password_confirmation = '';
/**
* Handle an incoming registration request.
*/
public function register(): void
{
$validated = $this->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
]);
$validated['password'] = Hash::make($validated['password']);
event(new Registered($user = User::create($validated)));
Auth::login($user);
$this->redirect(route('dashboard', absolute: false), navigate: true);
}
}; ?>
<div>
<form wire:submit="register">
<!-- Name -->
<div>
<x-input-label for="name" :value="__('Name')" />
<x-text-input wire:model="name" id="name" class="block mt-1 w-full" type="text" name="name" required autofocus autocomplete="name" />
<x-input-error :messages="$errors->get('name')" class="mt-2" />
</div>
<!-- Email Address -->
<div class="mt-4">
<x-input-label for="email" :value="__('Email')" />
<x-text-input wire:model="email" id="email" class="block mt-1 w-full" type="email" name="email" required autocomplete="username" />
<x-input-error :messages="$errors->get('email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input wire:model="password" id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password')" class="mt-2" />
</div>
<!-- Confirm Password -->
<div class="mt-4">
<x-input-label for="password_confirmation" :value="__('Confirm Password')" />
<x-text-input wire:model="password_confirmation" id="password_confirmation" class="block mt-1 w-full"
type="password"
name="password_confirmation" required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password_confirmation')" class="mt-2" />
</div>
<div class="flex items-center justify-end mt-4">
<a class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800" href="{{ route('login') }}" wire:navigate>
{{ __('Already registered?') }}
</a>
<x-primary-button class="ms-4">
{{ __('Register') }}
</x-primary-button>
</div>
</form>
</div>
| |
243422
|
<?php
use App\Livewire\Forms\LoginForm;
use Illuminate\Support\Facades\Session;
use Livewire\Attributes\Layout;
use Livewire\Volt\Component;
new #[Layout('layouts.guest')] class extends Component
{
public LoginForm $form;
/**
* Handle an incoming authentication request.
*/
public function login(): void
{
$this->validate();
$this->form->authenticate();
Session::regenerate();
$this->redirectIntended(default: route('dashboard', absolute: false), navigate: true);
}
}; ?>
<div>
<!-- Session Status -->
<x-auth-session-status class="mb-4" :status="session('status')" />
<form wire:submit="login">
<!-- Email Address -->
<div>
<x-input-label for="email" :value="__('Email')" />
<x-text-input wire:model="form.email" id="email" class="block mt-1 w-full" type="email" name="email" required autofocus autocomplete="username" />
<x-input-error :messages="$errors->get('form.email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input wire:model="form.password" id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="current-password" />
<x-input-error :messages="$errors->get('form.password')" class="mt-2" />
</div>
<!-- Remember Me -->
<div class="block mt-4">
<label for="remember" class="inline-flex items-center">
<input wire:model="form.remember" id="remember" type="checkbox" class="rounded dark:bg-gray-900 border-gray-300 dark:border-gray-700 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800" name="remember">
<span class="ms-2 text-sm text-gray-600 dark:text-gray-400">{{ __('Remember me') }}</span>
</label>
</div>
<div class="flex items-center justify-end mt-4">
@if (Route::has('password.request'))
<a class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800" href="{{ route('password.request') }}" wire:navigate>
{{ __('Forgot your password?') }}
</a>
@endif
<x-primary-button class="ms-3">
{{ __('Log in') }}
</x-primary-button>
</div>
</form>
</div>
| |
243433
|
import { Transition } from '@headlessui/react';
import { InertiaLinkProps, Link } from '@inertiajs/react';
import {
createContext,
Dispatch,
PropsWithChildren,
SetStateAction,
useContext,
useState,
} from 'react';
const DropDownContext = createContext<{
open: boolean;
setOpen: Dispatch<SetStateAction<boolean>>;
toggleOpen: () => void;
}>({
open: false,
setOpen: () => {},
toggleOpen: () => {},
});
const Dropdown = ({ children }: PropsWithChildren) => {
const [open, setOpen] = useState(false);
const toggleOpen = () => {
setOpen((previousState) => !previousState);
};
return (
<DropDownContext.Provider value={{ open, setOpen, toggleOpen }}>
<div className="relative">{children}</div>
</DropDownContext.Provider>
);
};
const Trigger = ({ children }: PropsWithChildren) => {
const { open, setOpen, toggleOpen } = useContext(DropDownContext);
return (
<>
<div onClick={toggleOpen}>{children}</div>
{open && (
<div
className="fixed inset-0 z-40"
onClick={() => setOpen(false)}
></div>
)}
</>
);
};
const Content = ({
align = 'right',
width = '48',
contentClasses = 'py-1 bg-white dark:bg-gray-700',
children,
}: PropsWithChildren<{
align?: 'left' | 'right';
width?: '48';
contentClasses?: string;
}>) => {
const { open, setOpen } = useContext(DropDownContext);
let alignmentClasses = 'origin-top';
if (align === 'left') {
alignmentClasses = 'ltr:origin-top-left rtl:origin-top-right start-0';
} else if (align === 'right') {
alignmentClasses = 'ltr:origin-top-right rtl:origin-top-left end-0';
}
let widthClasses = '';
if (width === '48') {
widthClasses = 'w-48';
}
return (
<>
<Transition
show={open}
enter="transition ease-out duration-200"
enterFrom="opacity-0 scale-95"
enterTo="opacity-100 scale-100"
leave="transition ease-in duration-75"
leaveFrom="opacity-100 scale-100"
leaveTo="opacity-0 scale-95"
>
<div
className={`absolute z-50 mt-2 rounded-md shadow-lg ${alignmentClasses} ${widthClasses}`}
onClick={() => setOpen(false)}
>
<div
className={
`rounded-md ring-1 ring-black ring-opacity-5 ` +
contentClasses
}
>
{children}
</div>
</div>
</Transition>
</>
);
};
const DropdownLink = ({
className = '',
children,
...props
}: InertiaLinkProps) => {
return (
<Link
{...props}
className={
'block w-full px-4 py-2 text-start text-sm leading-5 text-gray-700 transition duration-150 ease-in-out hover:bg-gray-100 focus:bg-gray-100 focus:outline-none dark:text-gray-300 dark:hover:bg-gray-800 dark:focus:bg-gray-800 ' +
className
}
>
{children}
</Link>
);
};
Dropdown.Trigger = Trigger;
Dropdown.Content = Content;
Dropdown.Link = DropdownLink;
export default Dropdown;
| |
243441
|
import ApplicationLogo from '@/Components/ApplicationLogo';
import Dropdown from '@/Components/Dropdown';
import NavLink from '@/Components/NavLink';
import ResponsiveNavLink from '@/Components/ResponsiveNavLink';
import { Link, usePage } from '@inertiajs/react';
import { PropsWithChildren, ReactNode, useState } from 'react';
export default function Authenticated({
header,
children,
}: PropsWithChildren<{ header?: ReactNode }>) {
const user = usePage().props.auth.user;
const [showingNavigationDropdown, setShowingNavigationDropdown] =
useState(false);
return (
<div className="min-h-screen bg-gray-100 dark:bg-gray-900">
<nav className="border-b border-gray-100 bg-white dark:border-gray-700 dark:bg-gray-800">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div className="flex h-16 justify-between">
<div className="flex">
<div className="flex shrink-0 items-center">
<Link href="/">
<ApplicationLogo className="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200" />
</Link>
</div>
<div className="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex">
<NavLink
href={route('dashboard')}
active={route().current('dashboard')}
>
Dashboard
</NavLink>
</div>
</div>
<div className="hidden sm:ms-6 sm:flex sm:items-center">
<div className="relative ms-3">
<Dropdown>
<Dropdown.Trigger>
<span className="inline-flex rounded-md">
<button
type="button"
className="inline-flex items-center rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium leading-4 text-gray-500 transition duration-150 ease-in-out hover:text-gray-700 focus:outline-none dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300"
>
{user.name}
<svg
className="-me-0.5 ms-2 h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fillRule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clipRule="evenodd"
/>
</svg>
</button>
</span>
</Dropdown.Trigger>
<Dropdown.Content>
<Dropdown.Link
href={route('profile.edit')}
>
Profile
</Dropdown.Link>
<Dropdown.Link
href={route('logout')}
method="post"
as="button"
>
Log Out
</Dropdown.Link>
</Dropdown.Content>
</Dropdown>
</div>
</div>
<div className="-me-2 flex items-center sm:hidden">
<button
onClick={() =>
setShowingNavigationDropdown(
(previousState) => !previousState,
)
}
className="inline-flex items-center justify-center rounded-md p-2 text-gray-400 transition duration-150 ease-in-out hover:bg-gray-100 hover:text-gray-500 focus:bg-gray-100 focus:text-gray-500 focus:outline-none dark:text-gray-500 dark:hover:bg-gray-900 dark:hover:text-gray-400 dark:focus:bg-gray-900 dark:focus:text-gray-400"
>
<svg
className="h-6 w-6"
stroke="currentColor"
fill="none"
viewBox="0 0 24 24"
>
<path
className={
!showingNavigationDropdown
? 'inline-flex'
: 'hidden'
}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M4 6h16M4 12h16M4 18h16"
/>
<path
className={
showingNavigationDropdown
? 'inline-flex'
: 'hidden'
}
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
</div>
</div>
<div
className={
(showingNavigationDropdown ? 'block' : 'hidden') +
' sm:hidden'
}
>
<div className="space-y-1 pb-3 pt-2">
<ResponsiveNavLink
href={route('dashboard')}
active={route().current('dashboard')}
>
Dashboard
</ResponsiveNavLink>
</div>
<div className="border-t border-gray-200 pb-1 pt-4 dark:border-gray-600">
<div className="px-4">
<div className="text-base font-medium text-gray-800 dark:text-gray-200">
{user.name}
</div>
<div className="text-sm font-medium text-gray-500">
{user.email}
</div>
</div>
<div className="mt-3 space-y-1">
<ResponsiveNavLink href={route('profile.edit')}>
Profile
</ResponsiveNavLink>
<ResponsiveNavLink
method="post"
href={route('logout')}
as="button"
>
Log Out
</ResponsiveNavLink>
</div>
</div>
</div>
</nav>
{header && (
<header className="bg-white shadow dark:bg-gray-800">
<div className="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
{header}
</div>
</header>
)}
<main>{children}</main>
</div>
);
}
| |
243470
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
class AuthenticatedSessionController extends Controller
{
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): Response
{
$request->authenticate();
$request->session()->regenerate();
return response()->noContent();
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): Response
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return response()->noContent();
}
}
| |
243471
|
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
class RegisteredUserController extends Controller
{
/**
* Handle an incoming registration request.
*
* @throws \Illuminate\Validation\ValidationException
*/
public function store(Request $request): Response
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->string('password')),
]);
event(new Registered($user));
Auth::login($user);
return response()->noContent();
}
}
| |
243472
|
<?php
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:3000,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
env('FRONTEND_URL') ? ','.parse_url(env('FRONTEND_URL'), PHP_URL_HOST) : ''
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => Laravel\Sanctum\Http\Middleware\AuthenticateSession::class,
'encrypt_cookies' => Illuminate\Cookie\Middleware\EncryptCookies::class,
'validate_csrf_token' => Illuminate\Foundation\Http\Middleware\ValidateCsrfToken::class,
],
];
| |
243473
|
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['*'],
'allowed_methods' => ['*'],
'allowed_origins' => [env('FRONTEND_URL', 'http://localhost:3000')],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
];
| |
243478
|
<?php
use App\Http\Controllers\Auth\AuthenticatedSessionController;
use App\Http\Controllers\Auth\EmailVerificationNotificationController;
use App\Http\Controllers\Auth\NewPasswordController;
use App\Http\Controllers\Auth\PasswordResetLinkController;
use App\Http\Controllers\Auth\RegisteredUserController;
use App\Http\Controllers\Auth\VerifyEmailController;
use Illuminate\Support\Facades\Route;
Route::post('/register', [RegisteredUserController::class, 'store'])
->middleware('guest')
->name('register');
Route::post('/login', [AuthenticatedSessionController::class, 'store'])
->middleware('guest')
->name('login');
Route::post('/forgot-password', [PasswordResetLinkController::class, 'store'])
->middleware('guest')
->name('password.email');
Route::post('/reset-password', [NewPasswordController::class, 'store'])
->middleware('guest')
->name('password.store');
Route::get('/verify-email/{id}/{hash}', VerifyEmailController::class)
->middleware(['auth', 'signed', 'throttle:6,1'])
->name('verification.verify');
Route::post('/email/verification-notification', [EmailVerificationNotificationController::class, 'store'])
->middleware(['auth', 'throttle:6,1'])
->name('verification.send');
Route::post('/logout', [AuthenticatedSessionController::class, 'destroy'])
->middleware('auth')
->name('logout');
| |
243479
|
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return ['Laravel' => app()->version()];
});
require __DIR__.'/auth.php';
| |
243480
|
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware(['auth:sanctum'])->get('/user', function (Request $request) {
return $request->user();
});
| |
243488
|
import '../css/app.css';
import './bootstrap';
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';
import { createApp, DefineComponent, h } from 'vue';
import { ZiggyVue } from '../../vendor/tightenco/ziggy';
const appName = import.meta.env.VITE_APP_NAME || 'Laravel';
createInertiaApp({
title: (title) => `${title} - ${appName}`,
resolve: (name) =>
resolvePageComponent(
`./Pages/${name}.vue`,
import.meta.glob<DefineComponent>('./Pages/**/*.vue'),
),
setup({ el, App, props, plugin }) {
createApp({ render: () => h(App, props) })
.use(plugin)
.use(ZiggyVue)
.mount(el);
},
progress: {
color: '#4B5563',
},
});
| |
243499
|
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue';
const props = withDefaults(
defineProps<{
align?: 'left' | 'right';
width?: '48';
contentClasses?: string;
}>(),
{
align: 'right',
width: '48',
contentClasses: 'py-1 bg-white dark:bg-gray-700',
},
);
const closeOnEscape = (e: KeyboardEvent) => {
if (open.value && e.key === 'Escape') {
open.value = false;
}
};
onMounted(() => document.addEventListener('keydown', closeOnEscape));
onUnmounted(() => document.removeEventListener('keydown', closeOnEscape));
const widthClass = computed(() => {
return {
48: 'w-48',
}[props.width.toString()];
});
const alignmentClasses = computed(() => {
if (props.align === 'left') {
return 'ltr:origin-top-left rtl:origin-top-right start-0';
} else if (props.align === 'right') {
return 'ltr:origin-top-right rtl:origin-top-left end-0';
} else {
return 'origin-top';
}
});
const open = ref(false);
</script>
<template>
<div class="relative">
<div @click="open = !open">
<slot name="trigger" />
</div>
<!-- Full Screen Dropdown Overlay -->
<div
v-show="open"
class="fixed inset-0 z-40"
@click="open = false"
></div>
<Transition
enter-active-class="transition ease-out duration-200"
enter-from-class="opacity-0 scale-95"
enter-to-class="opacity-100 scale-100"
leave-active-class="transition ease-in duration-75"
leave-from-class="opacity-100 scale-100"
leave-to-class="opacity-0 scale-95"
>
<div
v-show="open"
class="absolute z-50 mt-2 rounded-md shadow-lg"
:class="[widthClass, alignmentClasses]"
style="display: none"
@click="open = false"
>
<div
class="rounded-md ring-1 ring-black ring-opacity-5"
:class="contentClasses"
>
<slot name="content" />
</div>
</div>
</Transition>
</div>
</template>
| |
243507
|
<script setup lang="ts">
import { ref } from 'vue';
import ApplicationLogo from '@/Components/ApplicationLogo.vue';
import Dropdown from '@/Components/Dropdown.vue';
import DropdownLink from '@/Components/DropdownLink.vue';
import NavLink from '@/Components/NavLink.vue';
import ResponsiveNavLink from '@/Components/ResponsiveNavLink.vue';
import { Link } from '@inertiajs/vue3';
const showingNavigationDropdown = ref(false);
</script>
<template>
<div>
<div class="min-h-screen bg-gray-100 dark:bg-gray-900">
<nav
class="border-b border-gray-100 bg-white dark:border-gray-700 dark:bg-gray-800"
>
<!-- Primary Navigation Menu -->
<div class="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div class="flex h-16 justify-between">
<div class="flex">
<!-- Logo -->
<div class="flex shrink-0 items-center">
<Link :href="route('dashboard')">
<ApplicationLogo
class="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200"
/>
</Link>
</div>
<!-- Navigation Links -->
<div
class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex"
>
<NavLink
:href="route('dashboard')"
:active="route().current('dashboard')"
>
Dashboard
</NavLink>
</div>
</div>
<div class="hidden sm:ms-6 sm:flex sm:items-center">
<!-- Settings Dropdown -->
<div class="relative ms-3">
<Dropdown align="right" width="48">
<template #trigger>
<span class="inline-flex rounded-md">
<button
type="button"
class="inline-flex items-center rounded-md border border-transparent bg-white px-3 py-2 text-sm font-medium leading-4 text-gray-500 transition duration-150 ease-in-out hover:text-gray-700 focus:outline-none dark:bg-gray-800 dark:text-gray-400 dark:hover:text-gray-300"
>
{{ $page.props.auth.user.name }}
<svg
class="-me-0.5 ms-2 h-4 w-4"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
>
<path
fill-rule="evenodd"
d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z"
clip-rule="evenodd"
/>
</svg>
</button>
</span>
</template>
<template #content>
<DropdownLink
:href="route('profile.edit')"
>
Profile
</DropdownLink>
<DropdownLink
:href="route('logout')"
method="post"
as="button"
>
Log Out
</DropdownLink>
</template>
</Dropdown>
</div>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button
@click="
showingNavigationDropdown =
!showingNavigationDropdown
"
class="inline-flex items-center justify-center rounded-md p-2 text-gray-400 transition duration-150 ease-in-out hover:bg-gray-100 hover:text-gray-500 focus:bg-gray-100 focus:text-gray-500 focus:outline-none dark:text-gray-500 dark:hover:bg-gray-900 dark:hover:text-gray-400 dark:focus:bg-gray-900 dark:focus:text-gray-400"
>
<svg
class="h-6 w-6"
stroke="currentColor"
fill="none"
viewBox="0 0 24 24"
>
<path
:class="{
hidden: showingNavigationDropdown,
'inline-flex':
!showingNavigationDropdown,
}"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M4 6h16M4 12h16M4 18h16"
/>
<path
:class="{
hidden: !showingNavigationDropdown,
'inline-flex':
showingNavigationDropdown,
}"
stroke-linecap="round"
stroke-linejoin="round"
stroke-width="2"
d="M6 18L18 6M6 6l12 12"
/>
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div
:class="{
block: showingNavigationDropdown,
hidden: !showingNavigationDropdown,
}"
class="sm:hidden"
>
<div class="space-y-1 pb-3 pt-2">
<ResponsiveNavLink
:href="route('dashboard')"
:active="route().current('dashboard')"
>
Dashboard
</ResponsiveNavLink>
</div>
<!-- Responsive Settings Options -->
<div
class="border-t border-gray-200 pb-1 pt-4 dark:border-gray-600"
>
<div class="px-4">
<div
class="text-base font-medium text-gray-800 dark:text-gray-200"
>
{{ $page.props.auth.user.name }}
</div>
<div class="text-sm font-medium text-gray-500">
{{ $page.props.auth.user.email }}
</div>
</div>
<div class="mt-3 space-y-1">
<ResponsiveNavLink :href="route('profile.edit')">
Profile
</ResponsiveNavLink>
<ResponsiveNavLink
:href="route('logout')"
method="post"
as="button"
>
Log Out
</ResponsiveNavLink>
</div>
</div>
</div>
</nav>
<!-- Page Heading -->
<header
class="bg-white shadow dark:bg-gray-800"
v-if="$slots.header"
>
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 lg:px-8">
<slot name="header" />
</div>
</header>
<!-- Page Content -->
<main>
<slot />
</main>
</div>
</div>
</template>
| |
243529
|
<?php
use App\Livewire\Actions\Logout;
$logout = function (Logout $logout) {
$logout();
$this->redirect('/', navigate: true);
};
?>
<nav x-data="{ open: false }" class="bg-white dark:bg-gray-800 border-b border-gray-100 dark:border-gray-700">
<!-- Primary Navigation Menu -->
<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div class="flex justify-between h-16">
<div class="flex">
<!-- Logo -->
<div class="shrink-0 flex items-center">
<a href="{{ route('dashboard') }}" wire:navigate>
<x-application-logo class="block h-9 w-auto fill-current text-gray-800 dark:text-gray-200" />
</a>
</div>
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ms-10 sm:flex">
<x-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')" wire:navigate>
{{ __('Dashboard') }}
</x-nav-link>
</div>
</div>
<!-- Settings Dropdown -->
<div class="hidden sm:flex sm:items-center sm:ms-6">
<x-dropdown align="right" width="48">
<x-slot name="trigger">
<button class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:text-gray-700 dark:hover:text-gray-300 focus:outline-none transition ease-in-out duration-150">
<div x-data="{{ json_encode(['name' => auth()->user()->name]) }}" x-text="name" x-on:profile-updated.window="name = $event.detail.name"></div>
<div class="ms-1">
<svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</div>
</button>
</x-slot>
<x-slot name="content">
<x-dropdown-link :href="route('profile')" wire:navigate>
{{ __('Profile') }}
</x-dropdown-link>
<!-- Authentication -->
<button wire:click="logout" class="w-full text-start">
<x-dropdown-link>
{{ __('Log Out') }}
</x-dropdown-link>
</button>
</x-slot>
</x-dropdown>
</div>
<!-- Hamburger -->
<div class="-me-2 flex items-center sm:hidden">
<button @click="open = ! open" class="inline-flex items-center justify-center p-2 rounded-md text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-900 focus:outline-none focus:bg-gray-100 dark:focus:bg-gray-900 focus:text-gray-500 dark:focus:text-gray-400 transition duration-150 ease-in-out">
<svg class="h-6 w-6" stroke="currentColor" fill="none" viewBox="0 0 24 24">
<path :class="{'hidden': open, 'inline-flex': ! open }" class="inline-flex" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
<path :class="{'hidden': ! open, 'inline-flex': open }" class="hidden" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
</div>
</div>
</div>
<!-- Responsive Navigation Menu -->
<div :class="{'block': open, 'hidden': ! open}" class="hidden sm:hidden">
<div class="pt-2 pb-3 space-y-1">
<x-responsive-nav-link :href="route('dashboard')" :active="request()->routeIs('dashboard')" wire:navigate>
{{ __('Dashboard') }}
</x-responsive-nav-link>
</div>
<!-- Responsive Settings Options -->
<div class="pt-4 pb-1 border-t border-gray-200 dark:border-gray-600">
<div class="px-4">
<div class="font-medium text-base text-gray-800 dark:text-gray-200" x-data="{{ json_encode(['name' => auth()->user()->name]) }}" x-text="name" x-on:profile-updated.window="name = $event.detail.name"></div>
<div class="font-medium text-sm text-gray-500">{{ auth()->user()->email }}</div>
</div>
<div class="mt-3 space-y-1">
<x-responsive-nav-link :href="route('profile')" wire:navigate>
{{ __('Profile') }}
</x-responsive-nav-link>
<!-- Authentication -->
<button wire:click="logout" class="w-full text-start">
<x-responsive-nav-link>
{{ __('Log Out') }}
</x-responsive-nav-link>
</button>
</div>
</div>
</div>
</nav>
| |
243535
|
<?php
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use function Livewire\Volt\layout;
use function Livewire\Volt\rules;
use function Livewire\Volt\state;
layout('layouts.guest');
state([
'name' => '',
'email' => '',
'password' => '',
'password_confirmation' => ''
]);
rules([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'string', 'confirmed', Rules\Password::defaults()],
]);
$register = function () {
$validated = $this->validate();
$validated['password'] = Hash::make($validated['password']);
event(new Registered($user = User::create($validated)));
Auth::login($user);
$this->redirect(route('dashboard', absolute: false), navigate: true);
};
?>
<div>
<form wire:submit="register">
<!-- Name -->
<div>
<x-input-label for="name" :value="__('Name')" />
<x-text-input wire:model="name" id="name" class="block mt-1 w-full" type="text" name="name" required autofocus autocomplete="name" />
<x-input-error :messages="$errors->get('name')" class="mt-2" />
</div>
<!-- Email Address -->
<div class="mt-4">
<x-input-label for="email" :value="__('Email')" />
<x-text-input wire:model="email" id="email" class="block mt-1 w-full" type="email" name="email" required autocomplete="username" />
<x-input-error :messages="$errors->get('email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input wire:model="password" id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password')" class="mt-2" />
</div>
<!-- Confirm Password -->
<div class="mt-4">
<x-input-label for="password_confirmation" :value="__('Confirm Password')" />
<x-text-input wire:model="password_confirmation" id="password_confirmation" class="block mt-1 w-full"
type="password"
name="password_confirmation" required autocomplete="new-password" />
<x-input-error :messages="$errors->get('password_confirmation')" class="mt-2" />
</div>
<div class="flex items-center justify-end mt-4">
<a class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800" href="{{ route('login') }}" wire:navigate>
{{ __('Already registered?') }}
</a>
<x-primary-button class="ms-4">
{{ __('Register') }}
</x-primary-button>
</div>
</form>
</div>
| |
243539
|
<?php
use App\Livewire\Forms\LoginForm;
use Illuminate\Support\Facades\Session;
use function Livewire\Volt\form;
use function Livewire\Volt\layout;
layout('layouts.guest');
form(LoginForm::class);
$login = function () {
$this->validate();
$this->form->authenticate();
Session::regenerate();
$this->redirectIntended(default: route('dashboard', absolute: false), navigate: true);
};
?>
<div>
<!-- Session Status -->
<x-auth-session-status class="mb-4" :status="session('status')" />
<form wire:submit="login">
<!-- Email Address -->
<div>
<x-input-label for="email" :value="__('Email')" />
<x-text-input wire:model="form.email" id="email" class="block mt-1 w-full" type="email" name="email" required autofocus autocomplete="username" />
<x-input-error :messages="$errors->get('form.email')" class="mt-2" />
</div>
<!-- Password -->
<div class="mt-4">
<x-input-label for="password" :value="__('Password')" />
<x-text-input wire:model="form.password" id="password" class="block mt-1 w-full"
type="password"
name="password"
required autocomplete="current-password" />
<x-input-error :messages="$errors->get('form.password')" class="mt-2" />
</div>
<!-- Remember Me -->
<div class="block mt-4">
<label for="remember" class="inline-flex items-center">
<input wire:model="form.remember" id="remember" type="checkbox" class="rounded dark:bg-gray-900 border-gray-300 dark:border-gray-700 text-indigo-600 shadow-sm focus:ring-indigo-500 dark:focus:ring-indigo-600 dark:focus:ring-offset-gray-800" name="remember">
<span class="ms-2 text-sm text-gray-600 dark:text-gray-400">{{ __('Remember me') }}</span>
</label>
</div>
<div class="flex items-center justify-end mt-4">
@if (Route::has('password.request'))
<a class="underline text-sm text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-offset-gray-800" href="{{ route('password.request') }}" wire:navigate>
{{ __('Forgot your password?') }}
</a>
@endif
<x-primary-button class="ms-3">
{{ __('Log in') }}
</x-primary-button>
</div>
</form>
</div>
| |
243553
|
#[AsCommand(name: 'breeze:install')]
class InstallCommand extends Command implements PromptsForMissingInput
{
use InstallsApiStack, InstallsBladeStack, InstallsInertiaStacks, InstallsLivewireStack;
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'breeze:install {stack : The development stack that should be installed (blade,livewire,livewire-functional,react,vue,api)}
{--dark : Indicate that dark mode support should be installed}
{--pest : Indicate that Pest should be installed}
{--ssr : Indicates if Inertia SSR support should be installed}
{--typescript : Indicates if TypeScript is preferred for the Inertia stack}
{--eslint : Indicates if ESLint with Prettier should be installed}
{--composer=global : Absolute path to the Composer binary which should be used to install packages}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Install the Breeze controllers and resources';
/**
* Execute the console command.
*
* @return int|null
*/
public function handle()
{
if ($this->argument('stack') === 'vue') {
return $this->installInertiaVueStack();
} elseif ($this->argument('stack') === 'react') {
return $this->installInertiaReactStack();
} elseif ($this->argument('stack') === 'api') {
return $this->installApiStack();
} elseif ($this->argument('stack') === 'blade') {
return $this->installBladeStack();
} elseif ($this->argument('stack') === 'livewire') {
return $this->installLivewireStack();
} elseif ($this->argument('stack') === 'livewire-functional') {
return $this->installLivewireStack(true);
}
$this->components->error('Invalid stack. Supported stacks are [blade], [livewire], [livewire-functional], [react], [vue], and [api].');
return 1;
}
/**
* Install Breeze's tests.
*
* @return bool
*/
protected function installTests()
{
(new Filesystem)->ensureDirectoryExists(base_path('tests/Feature'));
$stubStack = match ($this->argument('stack')) {
'api' => 'api',
'livewire' => 'livewire-common',
'livewire-functional' => 'livewire-common',
default => 'default',
};
if ($this->option('pest') || $this->isUsingPest()) {
if ($this->hasComposerPackage('phpunit/phpunit')) {
$this->removeComposerPackages(['phpunit/phpunit'], true);
}
if (! $this->requireComposerPackages(['pestphp/pest', 'pestphp/pest-plugin-laravel'], true)) {
return false;
}
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/'.$stubStack.'/pest-tests/Feature', base_path('tests/Feature'));
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/'.$stubStack.'/pest-tests/Unit', base_path('tests/Unit'));
(new Filesystem)->copy(__DIR__.'/../../stubs/'.$stubStack.'/pest-tests/Pest.php', base_path('tests/Pest.php'));
} else {
(new Filesystem)->copyDirectory(__DIR__.'/../../stubs/'.$stubStack.'/tests/Feature', base_path('tests/Feature'));
}
return true;
}
/**
* Install the given middleware names into the application.
*
* @param array|string $name
* @param string $group
* @param string $modifier
* @return void
*/
protected function installMiddleware($names, $group = 'web', $modifier = 'append')
{
$bootstrapApp = file_get_contents(base_path('bootstrap/app.php'));
$names = collect(Arr::wrap($names))
->filter(fn ($name) => ! Str::contains($bootstrapApp, $name))
->whenNotEmpty(function ($names) use ($bootstrapApp, $group, $modifier) {
$names = $names->map(fn ($name) => "$name")->implode(','.PHP_EOL.' ');
$bootstrapApp = str_replace(
'->withMiddleware(function (Middleware $middleware) {',
'->withMiddleware(function (Middleware $middleware) {'
.PHP_EOL." \$middleware->$group($modifier: ["
.PHP_EOL." $names,"
.PHP_EOL.' ]);'
.PHP_EOL,
$bootstrapApp,
);
file_put_contents(base_path('bootstrap/app.php'), $bootstrapApp);
});
}
/**
* Install the given middleware aliases into the application.
*
* @param array $aliases
* @return void
*/
protected function installMiddlewareAliases($aliases)
{
$bootstrapApp = file_get_contents(base_path('bootstrap/app.php'));
$aliases = collect($aliases)
->filter(fn ($alias) => ! Str::contains($bootstrapApp, $alias))
->whenNotEmpty(function ($aliases) use ($bootstrapApp) {
$aliases = $aliases->map(fn ($name, $alias) => "'$alias' => $name")->implode(','.PHP_EOL.' ');
$bootstrapApp = str_replace(
'->withMiddleware(function (Middleware $middleware) {',
'->withMiddleware(function (Middleware $middleware) {'
.PHP_EOL.' $middleware->alias(['
.PHP_EOL." $aliases,"
.PHP_EOL.' ]);'
.PHP_EOL,
$bootstrapApp,
);
file_put_contents(base_path('bootstrap/app.php'), $bootstrapApp);
});
}
/**
* Determine if the given Composer package is installed.
*
* @param string $package
* @return bool
*/
protected function hasComposerPackage($package)
{
$packages = json_decode(file_get_contents(base_path('composer.json')), true);
return array_key_exists($package, $packages['require'] ?? [])
|| array_key_exists($package, $packages['require-dev'] ?? []);
}
/**
* Installs the given Composer Packages into the application.
*
* @param bool $asDev
* @return bool
*/
protected function requireComposerPackages(array $packages, $asDev = false)
{
$composer = $this->option('composer');
if ($composer !== 'global') {
$command = ['php', $composer, 'require'];
}
$command = array_merge(
$command ?? ['composer', 'require'],
$packages,
$asDev ? ['--dev'] : [],
);
return (new Process($command, base_path(), ['COMPOSER_MEMORY_LIMIT' => '-1']))
->setTimeout(null)
->run(function ($type, $output) {
$this->output->write($output);
}) === 0;
}
/**
* Removes the given Composer Packages from the application.
*
* @param bool $asDev
* @return bool
*/
protected function removeComposerPackages(array $packages, $asDev = false)
{
$composer = $this->option('composer');
if ($composer !== 'global') {
$command = ['php', $composer, 'remove'];
}
$command = array_merge(
$command ?? ['composer', 'remove'],
$packages,
$asDev ? ['--dev'] : [],
);
return (new Process($command, base_path(), ['COMPOSER_MEMORY_LIMIT' => '-1']))
->setTimeout(null)
->run(function ($type, $output) {
$this->output->write($output);
}) === 0;
}
/**
* Update the dependencies in the "package.json" file.
*
* @param bool $dev
* @return void
*/
protected static function updateNodePackages(callable $callback, $dev = true)
{
if (! file_exists(base_path('package.json'))) {
return;
}
$configurationKey = $dev ? 'devDependencies' : 'dependencies';
$packages = json_decode(file_get_contents(base_path('package.json')), true);
$packages[$configurationKey] = $callback(
array_key_exists($configurationKey, $packages) ? $packages[$configurationKey] : [],
$configurationKey
);
ksort($packages[$configurationKey]);
file_put_contents(
base_path('package.json'),
json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL
);
}
/**
* Update the scripts in the "package.json" file.
*
* @return void
*/
| |
243564
|
<?php
namespace LegacyTests;
use Illuminate\Foundation\Http\Kernel;
class HttpKernel extends Kernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\Illuminate\Cookie\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \Orchestra\Testbench\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
];
/**
* The priority-sorted list of middleware.
*
* This forces non-global middleware to always be in the given order.
*
* @var array
*/
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Illuminate\Auth\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
}
| |
243568
|
<?php
namespace LegacyTests\Unit;
use Orchestra\Testbench\TestCase as BaseTestCase;
use Livewire\LivewireServiceProvider;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
class TestCase extends BaseTestCase
{
public function setUp(): void
{
$this->afterApplicationCreated(function () {
$this->makeACleanSlate();
});
$this->beforeApplicationDestroyed(function () {
$this->makeACleanSlate();
});
parent::setUp();
}
public function makeACleanSlate()
{
Artisan::call('view:clear');
File::deleteDirectory($this->livewireViewsPath());
File::deleteDirectory($this->livewireClassesPath());
File::deleteDirectory($this->livewireTestsPath());
File::delete(app()->bootstrapPath('cache/livewire-components.php'));
}
protected function getPackageProviders($app)
{
return [
LivewireServiceProvider::class,
];
}
protected function getEnvironmentSetUp($app)
{
$app['config']->set('view.paths', [
__DIR__.'/views',
resource_path('views'),
]);
$app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8=');
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$app['config']->set('filesystems.disks.unit-downloads', [
'driver' => 'local',
'root' => __DIR__.'/fixtures',
]);
}
protected function resolveApplicationHttpKernel($app)
{
$app->singleton('Illuminate\Contracts\Http\Kernel', 'LegacyTests\HttpKernel');
}
protected function livewireClassesPath($path = '')
{
return app_path('Livewire'.($path ? '/'.$path : ''));
}
protected function livewireViewsPath($path = '')
{
return resource_path('views').'/livewire'.($path ? '/'.$path : '');
}
protected function livewireTestsPath($path = '')
{
return base_path('tests/Feature/Livewire'.($path ? '/'.$path : ''));
}
}
| |
243570
|
<div>
@if (session('status'))
<div class="alert-success mb-" role="alert">
{{ session('status') }}
</div>
@endif
</div>
| |
243571
|
<div>
@foreach ($models as $model)
{{ $model->title }}
@endforeach
</div>
| |
243610
|
class TestCase extends BaseTestCase
{
use SupportsSafari;
public static $useSafari = false;
public static $useAlpineV3 = false;
function visitLivewireComponent($browser, $classes, $queryString = '')
{
$classes = (array) $classes;
$this->registerComponentForNextTest($classes);
$url = '/livewire-dusk/'.urlencode(head($classes)).$queryString;
return $browser->visit($url)->waitForLivewireToLoad();
}
function registerComponentForNextTest($components)
{
$tmp = __DIR__ . '/_runtime_components.json';
file_put_contents($tmp, json_encode($components, JSON_PRETTY_PRINT));
}
function wipeRuntimeComponentRegistration()
{
$tmp = __DIR__ . '/_runtime_components.json';
file_exists($tmp) && unlink($tmp);
}
public function setUp(): void
{
if (isset($_SERVER['CI'])) {
DuskOptions::withoutUI();
}
Browser::mixin(new \Livewire\Features\SupportTesting\DuskBrowserMacros);
$this->afterApplicationCreated(function () {
$this->makeACleanSlate();
});
$this->beforeApplicationDestroyed(function () {
$this->makeACleanSlate();
});
parent::setUp();
// $thing = get_class($this);
$isUsingAlpineV3 = static::$useAlpineV3;
$this->tweakApplication(function () use ($isUsingAlpineV3) {
$tmp = __DIR__ . '/_runtime_components.json';
if (file_exists($tmp)) {
// We can't just "require" this file because of race conditions...
$components = json_decode(file_get_contents($tmp));
foreach ($components as $name => $class) {
if (is_numeric($name)) {
app('livewire')->component($class);
} else {
app('livewire')->component($name, $class);
}
}
}
// // Autoload all Livewire components in this test suite.
// collect(File::allFiles(__DIR__))
// ->map(function ($file) {
// return 'Tests\\Browser\\'.str($file->getRelativePathname())->before('.php')->replace('/', '\\');
// })
// ->filter(function ($computedClassName) {
// return class_exists($computedClassName);
// })
// ->filter(function ($class) {
// return is_subclass_of($class, Component::class);
// })->each(function ($componentClass) {
// app('livewire')->component($componentClass);
// });
// Route::get(
// '/livewire-dusk/tests/browser/sync-history-without-mount/{id}',
// \LegacyTests\Browser\SyncHistory\ComponentWithMount::class
// )->middleware('web')->name('sync-history-without-mount');
// // This needs to be registered for Dusk to test the route-parameter binding
// // See: \LegacyTests\Browser\SyncHistory\Test.php
// Route::get(
// '/livewire-dusk/tests/browser/sync-history/{step}',
// \LegacyTests\Browser\SyncHistory\Component::class
// )->middleware('web')->name('sync-history');
// Route::get(
// '/livewire-dusk/tests/browser/sync-history-without-query-string/{step}',
// \LegacyTests\Browser\SyncHistory\ComponentWithoutQueryString::class
// )->middleware('web')->name('sync-history-without-query-string');
// Route::get(
// '/livewire-dusk/tests/browser/sync-history-with-optional-parameter/{step?}',
// \LegacyTests\Browser\SyncHistory\ComponentWithOptionalParameter::class
// )->middleware('web')->name('sync-history-with-optional-parameter');
// // The following two routes belong together. The first one serves a view which in return
// // loads and renders a component dynamically. There may not be a POST route for the first one.
// Route::get('/livewire-dusk/tests/browser/load-dynamic-component', function () {
// return View::file(__DIR__ . '/DynamicComponentLoading/view-load-dynamic-component.blade.php');
// })->middleware('web')->name('load-dynamic-component');
// Route::post('/livewire-dusk/tests/browser/dynamic-component', function () {
// return View::file(__DIR__ . '/DynamicComponentLoading/view-dynamic-component.blade.php');
// })->middleware('web')->name('dynamic-component');
Route::get('/livewire-dusk/{component}', ShowDuskComponent::class)->middleware('web');
Route::middleware('web')->get('/entangle-turbo', function () {
return view('turbo', [
'link' => '/livewire-dusk/' . urlencode(\LegacyTests\Browser\Alpine\Entangle\ToggleEntangledTurbo::class),
]);
})->name('entangle-turbo');
// app('session')->put('_token', 'this-is-a-hack-because-something-about-validating-the-csrf-token-is-broken');
// app('config')->set('view.paths', [
// __DIR__.'/views',
// resource_path('views'),
// ]);
config()->set('app.debug', true);
});
}
protected function tearDown(): void
{
$this->wipeRuntimeComponentRegistration();
$this->removeApplicationTweaks();
parent::tearDown();
}
// We don't want to deal with screenshots or console logs.
protected function storeConsoleLogsFor($browsers) {}
protected function captureFailuresFor($browsers) {}
public function makeACleanSlate()
{
Artisan::call('view:clear');
File::deleteDirectory($this->livewireViewsPath());
File::cleanDirectory(__DIR__.'/downloads');
File::deleteDirectory($this->livewireClassesPath());
File::delete(app()->bootstrapPath('cache/livewire-components.php'));
}
protected function getPackageProviders($app)
{
return [
LivewireServiceProvider::class,
];
}
protected function getEnvironmentSetUp($app)
{
$app['config']->set('view.paths', [
__DIR__.'/views',
resource_path('views'),
]);
$app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8=');
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$app['config']->set('auth.providers.users.model', User::class);
$app['config']->set('filesystems.disks.dusk-downloads', [
'driver' => 'local',
'root' => __DIR__.'/downloads',
]);
}
protected function resolveApplicationHttpKernel($app)
{
$app->singleton('Illuminate\Contracts\Http\Kernel', 'LegacyTests\HttpKernel');
}
protected function livewireClassesPath($path = '')
{
return app_path('Livewire'.($path ? '/'.$path : ''));
}
protected function livewireViewsPath($path = '')
{
return resource_path('views').'/livewire'.($path ? '/'.$path : '');
}
protected function driver(): RemoteWebDriver
{
$options = DuskOptions::getChromeOptions();
$options->setExperimentalOption('prefs', [
'download.default_directory' => __DIR__.'/downloads',
]);
// $options->addArguments([
// 'auto-open-devtools-for-tabs',
// ]);
return static::$useSafari
? RemoteWebDriver::create(
'http://localhost:9515', DesiredCapabilities::safari()
)
: RemoteWebDriver::create(
'http://localhost:9515',
DesiredCapabilities::chrome()->setCapability(
ChromeOptions::CAPABILITY,
$options
)
);
}
public function browse(Closure $callback)
{
parent::browse(function (...$browsers) use ($callback) {
try {
$callback(...$browsers);
} catch (Exception|Throwable $e) {
if (DuskOptions::hasUI()) $this->breakIntoATinkerShell($browsers, $e);
throw $e;
}
});
}
public function breakIntoATinkerShell($browsers, $e)
{
$sh = new Shell();
$sh->add(new DuskCommand($this, $e));
$sh->setScopeVariables([
'browsers' => $browsers,
]);
$sh->addInput('dusk');
$sh->setBoundObject($this);
$sh->run();
return $sh->getScopeVariables(false);
}
}
| |
243669
|
<div>
<input dusk="foo.bar" type="radio" wire:model="foo" value="bar" name="foo">
<input dusk="foo.baz" type="radio" wire:model="foo" value="baz" name="foo">
</div>
| |
243690
|
<div>
<button wire:click="$refresh" dusk="refresh">Refresh</button>
<button wire:click="flashMessage" dusk="flash">Flash</button>
<button wire:click="redirectWithFlash" dusk="redirect-with-flash">Redirect With Flash</button>
<button wire:click="redirectPage" dusk="redirect.button">Redirect Page</button>
<span dusk="redirect.blade.output">{{ $message }}</span>
<span x-data="{ message: @entangle('message') }" x-text="message" dusk="redirect.alpine.output"></span>
<button wire:click="redirectPageWithModel" dusk="redirect-with-model.button">Redirect PageWithModel</button>
<span dusk="redirect.blade.model-output">{{ $foo }}</span>
<span x-data="{ message: @entangle('foo') }" x-text="message" dusk="redirect.alpine.model-output"></span>
<div>
@if (session()->has('message'))
<h1 dusk="flash.message">{{ session()->get('message') }}</h1>
@endif
</div>
</div>
| |
243711
|
<div>
<span dusk="baz-output">{{ $baz }}</span>
<input wire:model.live="baz" type="text" dusk="baz-input">
</div>
| |
243719
|
<div>
<input wire:model.live="search" type="text" dusk="search">
@foreach ($posts as $post)
<h1 wire:key="post-{{ $post->id }}">{{ $post->title }}</h1>
@endforeach
{{ $posts->links() }}
</div>
| |
243721
|
<div>
{{-- <div x-data="{ count: $queryString(1) }">
<input type="text" x-model="count">
<span x-text="count"></span>
</div>
<br>
<br>
<br> --}}
<span dusk="output">{{ $foo }}</span>
<span dusk="bar-output">{{ $bar }}</span>
<span dusk="qux.hyphen">{{ $qux['hyphen'] }}</span>
<span dusk="qux.comma">{{ $qux['comma'] }}</span>
<span dusk="qux.ampersand">{{ $qux['ampersand'] }}</span>
<span dusk="qux.space">{{ $qux['space'] }}</span>
<span dusk="qux.array">{{ json_encode($qux['array']) }}</span>
<input wire:model.live="foo" type="text" dusk="input">
<input wire:model.live="bar" type="text" dusk="bar-input">
<button wire:click="$set('showNestedComponent', true)" dusk="show-nested">Show Nested Component</button>
<button wire:click="modifyBob" dusk="bob.modify">Modify Bob (Array Property)</button>
<span dusk="bob.output">@json($bob)</span>
@if ($showNestedComponent)
@livewire('nested')
@endif
</div>
| |
243753
|
<div>
<input wire:model.live="foo" dusk="foo.input">
<button wire:click="changeFoo" dusk="foo.button">Change Foo</button>
<input wire:model.live="bar.baz" dusk="bar.input">
<button wire:click="resetBar" dusk="bar.button">Change BarBaz</button>
</div>
| |
243757
|
<div>
<input type="text" wire:model.live="foo" dusk="foo"><span dusk="foo.output">{{ $foo }}</span>
<button wire:click="updateFooTo('changed')" dusk="foo.change">Change Foo</button>
<input type="text" wire:model.live="bar.baz.bob" dusk="bar"><span dusk="bar.output">@json($bar)</span>
<input type="text" wire:model.lazy="baz" dusk="baz"><span dusk="baz.output">{{ $baz }}</span>
<input type="text" wire:model="bob" dusk="bob"><span dusk="bob.output">{{ $bob }}</span>
<button type="button" wire:click="$refresh" dusk="refresh">Refresh</button>
</div>
| |
243760
|
<div>
<textarea wire:model.live="foo" dusk="foo" class="{{ $showFooClass ? 'foo' : '' }}"></textarea><span dusk="foo.output">{{ $foo }}</span>
<button wire:click="updateFooTo('changed')" dusk="foo.change">Change Foo</button>
<button wire:click="$set('showFooClass', true)" dusk="foo.add-class">Add Class</button>
<textarea wire:model.blur="baz" dusk="baz"></textarea><span dusk="baz.output">{{ $baz }}</span>
<textarea wire:model="bob" dusk="bob"></textarea><span dusk="bob.output">{{ $bob }}</span>
<button type="button" wire:click="$refresh" dusk="refresh">Refresh</button>
</div>
| |
243765
|
<?php
namespace LegacyTests\Browser\DataBinding\Lazy;
use Livewire\Component as BaseComponent;
class LazyInputsWithUpdatesDisplayedComponent extends BaseComponent
{
public $name;
public $description;
public $is_active = false;
public $updates = [];
public function updated()
{
$this->updateUpdates();
}
public function submit()
{
$this->updateUpdates();
}
function updateUpdates()
{
// To keep the test from V2, I'm going to massage the V3 schema update data
// back into the V2 schema here...
$this->updates = [];
foreach (request('components.0.updates') as $key => $value) {
$this->updates[] = ['type' => 'syncInput', 'payload' => ['name' => $key]];
}
foreach (request('components.0.calls') as $call) {
$this->updates[] = ['type' => 'callMethod', 'payload' => ['method' => $call['method']]];
}
}
public function render()
{
return
<<<'HTML'
<div>
<input dusk="name" wire:model.lazy="name">
<input dusk="description" wire:model.lazy="description">
<input dusk="is_active" type="checkbox" wire:model.live="is_active">
<div dusk="totalNumberUpdates">{{ count($updates) }}</div>
<div dusk="updatesList">
@foreach($updates as $update)
<div>
@if($update['type'] == 'syncInput')
{{ $update['type'] . ' - ' . $update['payload']['name'] }}
@elseif($update['type'] == 'callMethod')
{{ $update['type'] . ' - ' . $update['payload']['method'] }}
@endif
</div>
@endforeach
</div>
<button dusk="submit" type="button" wire:click="submit">Submit</button>
</div>
HTML;
}
}
| |
243785
|
<html>
<head>
@livewireStyles
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $slot }}
@livewireScripts
<script type="module">
import hotwiredTurbo from 'https://cdn.skypack.dev/@hotwired/turbo';
</script>
<script src="https://cdn.jsdelivr.net/gh/livewire/turbolinks@v0.1.4/dist/livewire-turbolinks.js" data-turbolinks-eval="false" data-turbo-eval="false"></script>
<script data-turbo-eval="false">
document.addEventListener('turbo:before-render', () => {
let permanents = document.querySelectorAll('[data-turbo-permanent]')
let undos = Array.from(permanents).map(el => {
el._x_ignore = true
return () => {
delete el._x_ignore
}
})
document.addEventListener('turbo:render', function handler() {
while(undos.length) undos.shift()()
document.removeEventListener('turbo:render', handler)
})
})
</script>
@stack('scripts')
</body>
</html>
| |
243786
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
243787
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
@yield('content')
@stack('scripts')
</body>
</html>
| |
243788
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
243794
|
var UploadManager = class {
constructor(component) {
this.component = component;
this.uploadBag = new MessageBag();
this.removeBag = new MessageBag();
}
registerListeners() {
this.component.$wire.$on("upload:generatedSignedUrl", ({ name, url }) => {
setUploadLoading(this.component, name);
this.handleSignedUrl(name, url);
});
this.component.$wire.$on("upload:generatedSignedUrlForS3", ({ name, payload }) => {
setUploadLoading(this.component, name);
this.handleS3PreSignedUrl(name, payload);
});
this.component.$wire.$on("upload:finished", ({ name, tmpFilenames }) => this.markUploadFinished(name, tmpFilenames));
this.component.$wire.$on("upload:errored", ({ name }) => this.markUploadErrored(name));
this.component.$wire.$on("upload:removed", ({ name, tmpFilename }) => this.removeBag.shift(name).finishCallback(tmpFilename));
}
upload(name, file, finishCallback, errorCallback, progressCallback, cancelledCallback) {
this.setUpload(name, {
files: [file],
multiple: false,
finishCallback,
errorCallback,
progressCallback,
cancelledCallback
});
}
uploadMultiple(name, files, finishCallback, errorCallback, progressCallback, cancelledCallback) {
this.setUpload(name, {
files: Array.from(files),
multiple: true,
finishCallback,
errorCallback,
progressCallback,
cancelledCallback
});
}
removeUpload(name, tmpFilename, finishCallback) {
this.removeBag.push(name, {
tmpFilename,
finishCallback
});
this.component.$wire.call("_removeUpload", name, tmpFilename);
}
setUpload(name, uploadObject) {
this.uploadBag.add(name, uploadObject);
if (this.uploadBag.get(name).length === 1) {
this.startUpload(name, uploadObject);
}
}
handleSignedUrl(name, url) {
let formData = new FormData();
Array.from(this.uploadBag.first(name).files).forEach((file) => formData.append("files[]", file, file.name));
let headers = {
"Accept": "application/json"
};
let csrfToken = getCsrfToken();
if (csrfToken)
headers["X-CSRF-TOKEN"] = csrfToken;
this.makeRequest(name, formData, "post", url, headers, (response) => {
return response.paths;
});
}
handleS3PreSignedUrl(name, payload) {
let formData = this.uploadBag.first(name).files[0];
let headers = payload.headers;
if ("Host" in headers)
delete headers.Host;
let url = payload.url;
this.makeRequest(name, formData, "put", url, headers, (response) => {
return [payload.path];
});
}
makeRequest(name, formData, method, url, headers, retrievePaths) {
let request = new XMLHttpRequest();
request.open(method, url);
Object.entries(headers).forEach(([key, value]) => {
request.setRequestHeader(key, value);
});
request.upload.addEventListener("progress", (e) => {
e.detail = {};
e.detail.progress = Math.floor(e.loaded * 100 / e.total);
this.uploadBag.first(name).progressCallback(e);
});
request.addEventListener("load", () => {
if ((request.status + "")[0] === "2") {
let paths = retrievePaths(request.response && JSON.parse(request.response));
this.component.$wire.call("_finishUpload", name, paths, this.uploadBag.first(name).multiple);
return;
}
let errors = null;
if (request.status === 422) {
errors = request.response;
}
this.component.$wire.call("_uploadErrored", name, errors, this.uploadBag.first(name).multiple);
});
this.uploadBag.first(name).request = request;
request.send(formData);
}
startUpload(name, uploadObject) {
let fileInfos = uploadObject.files.map((file) => {
return { name: file.name, size: file.size, type: file.type };
});
this.component.$wire.call("_startUpload", name, fileInfos, uploadObject.multiple);
setUploadLoading(this.component, name);
}
markUploadFinished(name, tmpFilenames) {
unsetUploadLoading(this.component);
let uploadObject = this.uploadBag.shift(name);
uploadObject.finishCallback(uploadObject.multiple ? tmpFilenames : tmpFilenames[0]);
if (this.uploadBag.get(name).length > 0)
this.startUpload(name, this.uploadBag.last(name));
}
markUploadErrored(name) {
unsetUploadLoading(this.component);
this.uploadBag.shift(name).errorCallback();
if (this.uploadBag.get(name).length > 0)
this.startUpload(name, this.uploadBag.last(name));
}
cancelUpload(name, cancelledCallback = null) {
unsetUploadLoading(this.component);
let uploadItem = this.uploadBag.first(name);
if (uploadItem) {
if (uploadItem.request) {
uploadItem.request.abort();
}
this.uploadBag.shift(name).cancelledCallback();
if (cancelledCallback)
cancelledCallback();
}
}
};
var MessageBag = class {
constructor() {
this.bag = {};
}
add(name, thing) {
if (!this.bag[name]) {
this.bag[name] = [];
}
this.bag[name].push(thing);
}
push(name, thing) {
this.add(name, thing);
}
first(name) {
if (!this.bag[name])
return null;
return this.bag[name][0];
}
last(name) {
return this.bag[name].slice(-1)[0];
}
get(name) {
return this.bag[name];
}
shift(name) {
return this.bag[name].shift();
}
call(name, ...params) {
(this.listeners[name] || []).forEach((callback) => {
callback(...params);
});
}
has(name) {
return Object.keys(this.listeners).includes(name);
}
};
function setUploadLoading() {
}
function unsetUploadLoading() {
}
function upload(component, name, file, finishCallback = () => {
}, errorCallback = () => {
}, progressCallback = () => {
}, cancelledCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.upload(name, file, finishCallback, errorCallback, progressCallback, cancelledCallback);
}
function uploadMultiple(component, name, files, finishCallback = () => {
}, errorCallback = () => {
}, progressCallback = () => {
}, cancelledCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.uploadMultiple(name, files, finishCallback, errorCallback, progressCallback, cancelledCallback);
}
function removeUpload(component, name, tmpFilename, finishCallback = () => {
}, errorCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.removeUpload(name, tmpFilename, finishCallback, errorCallback);
}
function cancelUpload(component, name, cancelledCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.cancelUpload(name, cancelledCallback);
}
// ../alpine/packages/alpinejs/dist/module.esm.js
var flushPending = false;
var flushing = false;
var queue = [];
var lastFlushedIndex = -1;
function scheduler(callback) {
queueJob(callback);
}
function queueJob(job) {
if (!queue.includes(job))
queue.push(job);
queueFlush();
}
function dequeueJob(job) {
let index = queue.indexOf(job);
if (index !== -1 && index > lastFlushedIndex)
queue.splice(index, 1);
}
function queueFlush() {
if (!flushing && !flushPending) {
flushPending = true;
queueMicrotask(flushJobs);
}
}
function flushJobs() {
flushPending = false;
flushing = true;
for (let i = 0; i < queue.length; i++) {
queue[i]();
lastFlushedIndex = i;
}
queue.length = 0;
lastFlushedIndex = -1;
flushing = false;
}
var reactive;
var effect;
var release;
var raw;
var shouldSchedule = true;
function disableEffectScheduling(callback) {
shouldSchedule = false;
callback();
shouldSchedule = true;
}
function setReactivityEngine(engine) {
reactive = engine.reactive;
release = engine.release;
effect = (callback) => engine.effect(callback, { scheduler: (task) => {
if (shouldSchedule) {
scheduler(task);
} else {
task();
}
} });
raw = engine.raw;
}
function overrideEffect(override) {
effect = override;
}
| |
243828
|
function track2(name, initialSeedValue, alwaysShow = false, except = null) {
let { has: has2, get: get3, set: set3, remove } = queryStringUtils();
let url = new URL(window.location.href);
let isInitiallyPresentInUrl = has2(url, name);
let initialValue = isInitiallyPresentInUrl ? get3(url, name) : initialSeedValue;
let initialValueMemo = JSON.stringify(initialValue);
let exceptValueMemo = [false, null, void 0].includes(except) ? initialSeedValue : JSON.stringify(except);
let hasReturnedToInitialValue = (newValue) => JSON.stringify(newValue) === initialValueMemo;
let hasReturnedToExceptValue = (newValue) => JSON.stringify(newValue) === exceptValueMemo;
if (alwaysShow)
url = set3(url, name, initialValue);
replace(url, name, { value: initialValue });
let lock = false;
let update = (strategy, newValue) => {
if (lock)
return;
let url2 = new URL(window.location.href);
if (!alwaysShow && !isInitiallyPresentInUrl && hasReturnedToInitialValue(newValue)) {
url2 = remove(url2, name);
} else if (newValue === void 0) {
url2 = remove(url2, name);
} else if (!alwaysShow && hasReturnedToExceptValue(newValue)) {
url2 = remove(url2, name);
} else {
url2 = set3(url2, name, newValue);
}
strategy(url2, name, { value: newValue });
};
return {
initial: initialValue,
replace(newValue) {
update(replace, newValue);
},
push(newValue) {
update(push, newValue);
},
pop(receiver) {
let handler4 = (e) => {
if (!e.state || !e.state.alpine)
return;
Object.entries(e.state.alpine).forEach(([iName, { value: newValue }]) => {
if (iName !== name)
return;
lock = true;
let result = receiver(newValue);
if (result instanceof Promise) {
result.finally(() => lock = false);
} else {
lock = false;
}
});
};
window.addEventListener("popstate", handler4);
return () => window.removeEventListener("popstate", handler4);
}
};
}
function replace(url, key, object) {
let state = window.history.state || {};
if (!state.alpine)
state.alpine = {};
state.alpine[key] = unwrap(object);
window.history.replaceState(state, "", url.toString());
}
function push(url, key, object) {
let state = window.history.state || {};
if (!state.alpine)
state.alpine = {};
state = { alpine: { ...state.alpine, ...{ [key]: unwrap(object) } } };
window.history.pushState(state, "", url.toString());
}
function unwrap(object) {
if (object === void 0)
return void 0;
return JSON.parse(JSON.stringify(object));
}
function queryStringUtils() {
return {
has(url, key) {
let search = url.search;
if (!search)
return false;
let data2 = fromQueryString(search);
return Object.keys(data2).includes(key);
},
get(url, key) {
let search = url.search;
if (!search)
return false;
let data2 = fromQueryString(search);
return data2[key];
},
set(url, key, value) {
let data2 = fromQueryString(url.search);
data2[key] = stripNulls(unwrap(value));
url.search = toQueryString(data2);
return url;
},
remove(url, key) {
let data2 = fromQueryString(url.search);
delete data2[key];
url.search = toQueryString(data2);
return url;
}
};
}
function stripNulls(value) {
if (!isObjecty(value))
return value;
for (let key in value) {
if (value[key] === null)
delete value[key];
else
value[key] = stripNulls(value[key]);
}
return value;
}
function toQueryString(data2) {
let isObjecty2 = (subject) => typeof subject === "object" && subject !== null;
let buildQueryStringEntries = (data3, entries2 = {}, baseKey = "") => {
Object.entries(data3).forEach(([iKey, iValue]) => {
let key = baseKey === "" ? iKey : `${baseKey}[${iKey}]`;
if (iValue === null) {
entries2[key] = "";
} else if (!isObjecty2(iValue)) {
entries2[key] = encodeURIComponent(iValue).replaceAll("%20", "+").replaceAll("%2C", ",");
} else {
entries2 = { ...entries2, ...buildQueryStringEntries(iValue, entries2, key) };
}
});
return entries2;
};
let entries = buildQueryStringEntries(data2);
return Object.entries(entries).map(([key, value]) => `${key}=${value}`).join("&");
}
function fromQueryString(search) {
search = search.replace("?", "");
if (search === "")
return {};
let insertDotNotatedValueIntoData = (key, value, data3) => {
let [first2, second, ...rest] = key.split(".");
if (!second)
return data3[key] = value;
if (data3[first2] === void 0) {
data3[first2] = isNaN(second) ? {} : [];
}
insertDotNotatedValueIntoData([second, ...rest].join("."), value, data3[first2]);
};
let entries = search.split("&").map((i) => i.split("="));
let data2 = /* @__PURE__ */ Object.create(null);
entries.forEach(([key, value]) => {
if (typeof value == "undefined")
return;
value = decodeURIComponent(value.replaceAll("+", "%20"));
if (!key.includes("[")) {
data2[key] = value;
} else {
let dotNotatedKey = key.replaceAll("[", ".").replaceAll("]", "");
insertDotNotatedValueIntoData(dotNotatedKey, value, data2);
}
});
return data2;
}
// ../alpine/packages/morph/dist/module.esm.js
function morph(from, toHtml, options)
| |
243838
|
function ye(e){let t=ci(e)?e[0]:e,r=ci(e)?e[1]:void 0;return St(t)&&Object.entries(t).forEach(([n,i])=>{t[n]=ye(i)}),t}function ci(e){return Array.isArray(e)&&e.length===2&&typeof e[1]=="object"&&Object.keys(e[1]).includes("s")}function Et(){if(document.querySelector('meta[name="csrf-token"]'))return document.querySelector('meta[name="csrf-token"]').getAttribute("content");if(document.querySelector("[data-csrf]"))return document.querySelector("[data-csrf]").getAttribute("data-csrf");if(window.livewireScriptConfig.csrf??!1)return window.livewireScriptConfig.csrf;throw"Livewire: No CSRF token detected"}var Ie;function fi(){if(Ie)return Ie;if(window.livewireScriptConfig&&(window.livewireScriptConfig.nonce??!1))return Ie=window.livewireScriptConfig.nonce,Ie;let e=document.querySelector("style[data-livewire-style][nonce]");return e?(Ie=e.nonce,Ie):null}function di(){return document.querySelector("[data-update-uri]")?.getAttribute("data-update-uri")??window.livewireScriptConfig.uri??null}function At(e){return!!e.match(/<script>Sfdump\(".+"\)<\/script>/)}function pi(e){let t=e.match(/.*<script>Sfdump\(".+"\)<\/script>/s);return[t,e.replace(t,"")]}var yr=new WeakMap;function tt(e){if(!yr.has(e)){let t=new xr(e);yr.set(e,t),t.registerListeners()}return yr.get(e)}function hi(e,t,r,n){let i=tt(r),o=()=>e.dispatchEvent(new CustomEvent("livewire-upload-start",{bubbles:!0,detail:{id:r.id,property:t}})),s=()=>e.dispatchEvent(new CustomEvent("livewire-upload-finish",{bubbles:!0,detail:{id:r.id,property:t}})),a=()=>e.dispatchEvent(new CustomEvent("livewire-upload-error",{bubbles:!0,detail:{id:r.id,property:t}})),l=()=>e.dispatchEvent(new CustomEvent("livewire-upload-cancel",{bubbles:!0,detail:{id:r.id,property:t}})),u=c=>{var d=Math.round(c.loaded*100/c.total);e.dispatchEvent(new CustomEvent("livewire-upload-progress",{bubbles:!0,detail:{progress:d}}))},f=c=>{c.target.files.length!==0&&(o(),c.target.multiple?i.uploadMultiple(t,c.target.files,s,a,u,l):i.upload(t,c.target.files[0],s,a,u,l))};e.addEventListener("change",f),r.$wire.$watch(t,c=>{!e.isConnected||(c===null||c==="")&&(e.value="")});let p=()=>{e.value=null};e.addEventListener("click",p),e.addEventListener("livewire-upload-cancel",p),n(()=>{e.removeEventListener("change",f),e.removeEventListener("click",p)})}var xr=class{constructor(t){this.component=t,this.uploadBag=new et,this.removeBag=new et}registerListeners(){this.component.$wire.$on("upload:generatedSignedUrl",({name:t,url:r})=>{this.component,this.handleSignedUrl(t,r)}),this.component.$wire.$on("upload:generatedSignedUrlForS3",({name:t,payload:r})=>{this.component,this.handleS3PreSignedUrl(t,r)}),this.component.$wire.$on("upload:finished",({name:t,tmpFilenames:r})=>this.markUploadFinished(t,r)),this.component.$wire.$on("upload:errored",({name:t})=>this.markUploadErrored(t)),this.component.$wire.$on("upload:removed",({name:t,tmpFilename:r})=>this.removeBag.shift(t).finishCallback(r))}upload(t,r,n,i,o,s){this.setUpload(t,{files:[r],multiple:!1,finishCallback:n,errorCallback:i,progressCallback:o,cancelledCallback:s})}uploadMultiple(t,r,n,i,o,s){this.setUpload(t,{files:Array.from(r),multiple:!0,finishCallback:n,errorCallback:i,progressCallback:o,cancelledCallback:s})}removeUpload(t,r,n){this.removeBag.push(t,{tmpFilename:r,finishCallback:n}),this.component.$wire.call("_removeUpload",t,r)}setUpload(t,r){this.uploadBag.add(t,r),this.uploadBag.get(t).length===1&&this.startUpload(t,r)}handleSignedUrl(t,r){let n=new FormData;Array.from(this.uploadBag.first(t).files).forEach(s=>n.append("files[]",s,s.name));let i={Accept:"application/json"},o=Et();o&&(i["X-CSRF-TOKEN"]=o),this.makeRequest(t,n,"post",r,i,s=>s.paths)}handleS3PreSignedUrl(t,r){let n=this.uploadBag.first(t).files[0],i=r.headers;"Host"in i&&delete i.Host;let o=r.url;this.makeRequest(t,n,"put",o,i,s=>[r.path])}makeRequest(t,r,n,i,o,s){let a=new XMLHttpRequest;a.open(n,i),Object.entries(o).forEach(([l,u])=>{a.setRequestHeader(l,u)}),a.upload.addEventListener("progress",l=>{l.detail={},l.detail.progress=Math.floor(l.loaded*100/l.total),this.uploadBag.first(t).progressCallback(l)}),a.addEventListener("load",()=>{if((a.status+"")[0]==="2"){let u=s(a.response&&JSON.parse(a.response));this.component.$wire.call("_finishUpload",t,u,this.uploadBag.first(t).multiple);return}let l=null;a.status===422&&(l=a.response),this.component.$wire.call("_uploadErrored",t,l,this.uploadBag.first(t).multiple)}),this.uploadBag.first(t).request=a,a.send(r)}startUpload(t,r){let n=r.files.map(i=>({name:i.name,size:i.size,type:i.type}));this.component.$wire.call("_startUpload",t,n,r.multiple),this.component}markUploadFinished(t,r){this.component;let n=this.uploadBag.shift(t);n.finishCallback(n.multiple?r:r[0]),this.uploadBag.get(t).length>0&&this.startUpload(t,this.uploadBag.last(t))}markUploadErrored(t){this.component,this.uploadBag.shift(t).errorCallback(),this.uploadBag.get(t).length>0&&this.startUpload(t,this.uploadBag.last(t))}cancelUpload(t,r=null){this.component;let n=this.uploadBag.first(t);n&&(n.request&&n.request.abort(),this.uploadBag.shift(t).cancelledCallback(),r&&r())}},et=class{constructor(){this.bag={}}add(t,r){this.bag[t]||(this.bag[t]=[]),this.bag[t].push(r)}push(t,r){this.add(t,r)}first(t){return this.bag[t]?this.bag[t][0]:null}last(t){return this.bag[t].slice(-1)[0]}get(t){return this.bag[t]}shift(t){return this.bag[t].shift()}call(t,...r){(this.listeners[t]||[]).forEach(n=>{n(...r)})}has(t){return Object.keys(this.listeners).includes(t)}};function mi(e,t,r,n=()=>{},i=()=>{},o=()=>{},s=()=>{}){tt(e).upload(t,r,n,i,o,s)}function gi(e,t,r,n=()=>{},i=()=>{},o=()=>{},s=()=>{}){tt(e).uploadMultiple(t,r,n,i,o,s)}function vi(e,t,r,n=()=>{},i=()=>{}){tt(e).removeUpload(t,r,n,i)}function bi(e,t,r=()=>{}){tt(e).cancelUpload(t,r)}var Or=!1,Tr=!1,Se=[],kr=-1;function ml(e){gl(e)}function gl(e){Se.includes(e)||Se.push(e),bl()}function vl(e){let t=Se.indexOf(e);t!==-1&&t>kr&&Se.splice(t,1)}function bl(){!Tr&&!Or&&(Or=!0,queueMicrotask(wl))}function wl(){Or=!1,Tr=!0;for(let e=0;e<Se.length;e++)Se[e](),kr=e;Se.length=0,kr=-1,Tr=!1}var Be,Te,Ue,Ri,Lr=!0;function yl(e){Lr=!1,e(),Lr=!0}function xl(e){Be=e.reactive,Ue=e.release,Te=t=>e.effect(t,{scheduler:r=>{Lr?ml(r):r()}}),Ri=e.raw}function wi(e){Te=e}function _l(e){let t=()=>{};return[n=>{let i=Te(n);return e._x_effects||(e._x_effects=new Set,e._x_runEffects=()=>{e._x_effects.forEach(o=>o())}),e._x_effects.add(i),t=()=>{i!==void 0&&(e._x_effects.delete(i),Ue(i))},i},()=>{t()}]}
| |
243846
|
zo.inline=(e,{value:t,modifiers:r,expression:n})=>{!t||(e._x_inlineBindings||(e._x_inlineBindings={}),e._x_inlineBindings[t]={expression:n,extract:!1})};$("bind",zo);function wc(e,t){e._x_keyExpression=t}ao(()=>`[${He("data")}]`);$("data",(e,{expression:t},{cleanup:r})=>{if(yc(e))return;t=t===""?"{}":t;let n={};Pr(n,e);let i={};Su(i,n);let o=Ee(e,t,{scope:i});(o===void 0||o===!0)&&(o={}),Pr(o,e);let s=Be(o);qi(s);let a=ut(e,s);s.init&&Ee(e,s.init),r(()=>{s.destroy&&Ee(e,s.destroy),a()})});Bt((e,t)=>{e._x_dataStack&&(t._x_dataStack=e._x_dataStack,t.setAttribute("data-has-alpine-state",!0))});function yc(e){return de?Br?!0:e.hasAttribute("data-has-alpine-state"):!1}$("show",(e,{modifiers:t,expression:r},{effect:n})=>{let i=H(e,r);e._x_doHide||(e._x_doHide=()=>{F(()=>{e.style.setProperty("display","none",t.includes("important")?"important":void 0)})}),e._x_doShow||(e._x_doShow=()=>{F(()=>{e.style.length===1&&e.style.display==="none"?e.removeAttribute("style"):e.style.removeProperty("display")})});let o=()=>{e._x_doHide(),e._x_isShown=!1},s=()=>{e._x_doShow(),e._x_isShown=!0},a=()=>setTimeout(s),l=$r(p=>p?s():o(),p=>{typeof e._x_toggleAndCascadeWithTransitions=="function"?e._x_toggleAndCascadeWithTransitions(e,p,s,o):p?a():o()}),u,f=!0;n(()=>i(p=>{!f&&p===u||(t.includes("immediate")&&(p?a():o()),l(p),u=p,f=!1)}))});$("for",(e,{expression:t},{effect:r,cleanup:n})=>{let i=_c(t),o=H(e,i.items),s=H(e,e._x_keyExpression||"index");e._x_prevKeys=[],e._x_lookup={},r(()=>xc(e,i,o,s)),n(()=>{Object.values(e._x_lookup).forEach(a=>F(()=>{je(a),a.remove()})),delete e._x_prevKeys,delete e._x_lookup})});function xc(e,t,r,n){let i=s=>typeof s=="object"&&!Array.isArray(s),o=e;r(s=>{Sc(s)&&s>=0&&(s=Array.from(Array(s).keys(),g=>g+1)),s===void 0&&(s=[]);let a=e._x_lookup,l=e._x_prevKeys,u=[],f=[];if(i(s))s=Object.entries(s).map(([g,y])=>{let v=Pi(t,y,g,s);n(_=>{f.includes(_)&&V("Duplicate key on x-for",e),f.push(_)},{scope:{index:g,...v}}),u.push(v)});else for(let g=0;g<s.length;g++){let y=Pi(t,s[g],g,s);n(v=>{f.includes(v)&&V("Duplicate key on x-for",e),f.push(v)},{scope:{index:g,...y}}),u.push(y)}let p=[],c=[],d=[],m=[];for(let g=0;g<l.length;g++){let y=l[g];f.indexOf(y)===-1&&d.push(y)}l=l.filter(g=>!d.includes(g));let b="template";for(let g=0;g<f.length;g++){let y=f[g],v=l.indexOf(y);if(v===-1)l.splice(g,0,y),p.push([b,g]);else if(v!==g){let _=l.splice(g,1)[0],T=l.splice(v-1,1)[0];l.splice(g,0,T),l.splice(v,0,_),c.push([_,T])}else m.push(y);b=y}for(let g=0;g<d.length;g++){let y=d[g];y in a&&(F(()=>{je(a[y]),a[y].remove()}),delete a[y])}for(let g=0;g<c.length;g++){let[y,v]=c[g],_=a[y],T=a[v],A=document.createElement("div");F(()=>{T||V('x-for ":key" is undefined or invalid',o,v,a),T.after(A),_.after(T),T._x_currentIfEl&&T.after(T._x_currentIfEl),A.before(_),_._x_currentIfEl&&_.after(_._x_currentIfEl),A.remove()}),T._x_refreshXForScope(u[f.indexOf(v)])}for(let g=0;g<p.length;g++){let[y,v]=p[g],_=y==="template"?o:a[y];_._x_currentIfEl&&(_=_._x_currentIfEl);let T=u[v],A=f[v],w=document.importNode(o.content,!0).firstElementChild,h=Be(T);ut(w,h,o),w._x_refreshXForScope=x=>{Object.entries(x).forEach(([O,L])=>{h[O]=L})},F(()=>{_.after(w),he(()=>ie(w))()}),typeof A=="object"&&V("x-for key cannot be an object, it must be a string or an integer",o),a[A]=w}for(let g=0;g<m.length;g++)a[m[g]]._x_refreshXForScope(u[f.indexOf(m[g])]);o._x_prevKeys=f})}function _c(e){let t=/,([^,\}\]]*)(?:,([^,\}\]]*))?$/,r=/^\s*\(|\)\s*$/g,n=/([\s\S]*?)\s+(?:in|of)\s+([\s\S]*)/,i=e.match(n);if(!i)return;let o={};o.items=i[2].trim();let s=i[1].replace(r,"").trim(),a=s.match(t);return a?(o.item=s.replace(t,"").trim(),o.index=a[1].trim(),a[2]&&(o.collection=a[2].trim())):o.item=s,o}function Pi(e,t,r,n){let i={};return/^\[.*\]$/.test(e.item)&&Array.isArray(t)?e.item.replace("[","").replace("]","").split(",").map(s=>s.trim()).forEach((s,a)=>{i[s]=t[a]}):/^\{.*\}$/.test(e.item)&&!Array.isArray(t)&&typeof t=="object"?e.item.replace("{","").replace("}","").split(",").map(s=>s.trim()).forEach(s=>{i[s]=t[s]}):i[e.item]=t,e.index&&(i[e.index]=r),e.collection&&(i[e.collection]=n),i}function Sc(e){return!Array.isArray(e)&&!isNaN(e)}function Ko(){}Ko.inline=(e,{expression:t},{cleanup:r})=>{let n=$t(e);n._x_refs||(n._x_refs={}),n._x_refs[t]=e,r(()=>delete n._x_refs[t])};$("ref",Ko);$("if",(e,{expression:t},{effect:r,cleanup:n})=>{e.tagName.toLowerCase()!=="template"&&V("x-if can only be used on a <template> tag",e);let i=H(e,t),o=()=>{if(e._x_currentIfEl)return e._x_currentIfEl;let a=e.content.cloneNode(!0).firstElementChild;return ut(a,{},e),F(()=>{e.after(a),he(()=>ie(a))()}),e._x_currentIfEl=a,e._x_undoIf=()=>{F(()=>{je(a),a.remove()}),delete e._x_currentIfEl},a},s=()=>{!e._x_undoIf||(e._x_undoIf(),delete e._x_undoIf)};r(()=>i(a=>{a?o():s()})),n(()=>e._x_undoIf&&e._x_undoIf())});$("id",(e,{expression:t},{evaluate:r})=>{r(t).forEach(i=>uc(e,i))});Bt((e,t)=>{e._x_ids&&(t._x_ids=e._x_ids)});Qr(Qi("@",Zi(He("on:"))));$("on",he((e,{value:t,modifiers:r,expression:n},{cleanup:i})=>{let o=n?H(e,n):()=>{};e.tagName.toLowerCase()==="template"&&(e._x_forwardEvents||(e._x_forwardEvents=[]),e._x_forwardEvents.includes(t)||e._x_forwardEvents.push(t));let s=qr(e,t,r,a=>{o(()=>{},{scope:{$event:a},params:[a]})});i(()=>s())}));Wt("Collapse","collapse","collapse");
| |
243857
|
function ya(e){return(Aa(e)?e.src:e.href).split("?")}function xa(e){return e.tagName.toLowerCase()==="link"&&e.getAttribute("rel").toLowerCase()==="stylesheet"||e.tagName.toLowerCase()==="style"||e.tagName.toLowerCase()==="script"}function Aa(e){return e.tagName.toLowerCase()==="script"}function Ca(e){return e.split("").reduce((t,r)=>(t=(t<<5)-t+r.charCodeAt(0),t&t),0)}function Oa(e,t){let r=e;return t.forEach(n=>{let i=new RegExp(`${n}="[^"]*"|${n}='[^']*'`,"g");r=r.replace(i,"")}),r=r.replaceAll(" ",""),r.trim()}var hr=!0,Jn=!0,Kf=!0,Ta=!1;function Pa(e){e.navigate=r=>{let n=ve(r);ue("alpine:navigate",{url:n,history:!1,cached:!1})||t(n)},e.navigate.disableProgressBar=()=>{Jn=!1},e.addInitSelector(()=>`[${e.prefixed("navigate")}]`),e.directive("navigate",(r,{modifiers:n})=>{n.includes("hover")&&ca(r,60,()=>{let o=Nn(r);!o||Rn(o,(s,a)=>{Mn(s,o,a)})}),ua(r,o=>{let s=Nn(r);!s||(Rn(s,(a,l)=>{Mn(a,s,l)}),o(()=>{ue("alpine:navigate",{url:s,history:!1,cached:!1})||t(s)}))})});function t(r,n=!0){Jn&&va(),Vf(r,(i,o)=>{ue("alpine:navigating"),Kf&&Dn(),Jn&&ba(),Jf(),ia(),ka(e,s=>{hr&&Un(a=>{In(a),Wn(a)}),n?aa(i,o):Ln(o,i),Vn(i,a=>{Fn(document.body),hr&&Hn((l,u)=>{$n(l),zn(l)}),Bn(),a(()=>{s(()=>{setTimeout(()=>{Ta&&Na()}),La(e),ue("alpine:navigated")})})})})})}sa(r=>{r(n=>{let i=ve(n);if(ue("alpine:navigate",{url:i,history:!0,cached:!1}))return;t(i,!1)})},(r,n,i,o)=>{let s=ve(n);ue("alpine:navigate",{url:s,history:!0,cached:!0})||(Dn(),ue("alpine:navigating"),oa(i,o),ka(e,l=>{hr&&Un(u=>{In(u),Wn(u)}),Vn(r,()=>{wa(),Fn(document.body),hr&&Hn((u,f)=>{$n(u),zn(u)}),Bn(),l(()=>{Ta&&Na(),La(e),ue("alpine:navigated")})})}))}),setTimeout(()=>{ue("alpine:navigated")})}function Vf(e,t){da(e,t,()=>{fa(e,t)})}function ka(e,t){e.stopObservingMutations(),t(r=>{e.startObservingMutations(),queueMicrotask(()=>{r()})})}function ue(e,t){let r=new CustomEvent(e,{cancelable:!0,bubbles:!0,detail:t});return document.dispatchEvent(r),r.defaultPrevented}function La(e){e.initTree(document.body,void 0,(t,r)=>{t._x_wasPersisted&&r()})}function Na(){document.querySelector("[autofocus]")&&document.querySelector("[autofocus]").focus()}function Jf(){let e=function(t,r){Alpine.walk(t,(n,i)=>{ha(n)&&i(),pa(n)?i():r(n,i)})};Alpine.destroyTree(document.body,e)}function Gn(e){e.magic("queryString",(t,{interceptor:r})=>{let n,i=!1,o=!1;return r((s,a,l,u,f)=>{let p=n||u,{initial:c,replace:d,push:m,pop:b}=gr(p,s,i);return l(c),o?(e.effect(()=>m(a())),b(async g=>{l(g),await(()=>Promise.resolve())()})):e.effect(()=>d(a())),c},s=>{s.alwaysShow=()=>(i=!0,s),s.usePush=()=>(o=!0,s),s.as=a=>(n=a,s)})}),e.history={track:gr}}function gr(e,t,r=!1,n=null){let{has:i,get:o,set:s,remove:a}=Xf(),l=new URL(window.location.href),u=i(l,e),f=u?o(l,e):t,p=JSON.stringify(f),c=[!1,null,void 0].includes(n)?t:JSON.stringify(n),d=y=>JSON.stringify(y)===p,m=y=>JSON.stringify(y)===c;r&&(l=s(l,e,f)),Ra(l,e,{value:f});let b=!1,g=(y,v)=>{if(b)return;let _=new URL(window.location.href);!r&&!u&&d(v)||v===void 0||!r&&m(v)?_=a(_,e):_=s(_,e,v),y(_,e,{value:v})};return{initial:f,replace(y){g(Ra,y)},push(y){g(Gf,y)},pop(y){let v=_=>{!_.state||!_.state.alpine||Object.entries(_.state.alpine).forEach(([T,{value:A}])=>{if(T!==e)return;b=!0;let w=y(A);w instanceof Promise?w.finally(()=>b=!1):b=!1})};return window.addEventListener("popstate",v),()=>window.removeEventListener("popstate",v)}}}function Ra(e,t,r){let n=window.history.state||{};n.alpine||(n.alpine={}),n.alpine[t]=Xn(r),window.history.replaceState(n,"",e.toString())}function Gf(e,t,r){let n=window.history.state||{};n.alpine||(n.alpine={}),n={alpine:{...n.alpine,[t]:Xn(r)}},window.history.pushState(n,"",e.toString())}function Xn(e){if(e!==void 0)return JSON.parse(JSON.stringify(e))}function Xf(){return{has(e,t){let r=e.search;if(!r)return!1;let n=mr(r);return Object.keys(n).includes(t)},get(e,t){let r=e.search;return r?mr(r)[t]:!1},set(e,t,r){let n=mr(e.search);return n[t]=Ia(Xn(r)),e.search=Ma(n),e},remove(e,t){let r=mr(e.search);return delete r[t],e.search=Ma(r),e}}}function Ia(e){if(!St(e))return e;for(let t in e)e[t]===null?delete e[t]:e[t]=Ia(e[t]);return e}function Ma(e){let t=i=>typeof i=="object"&&i!==null,r=(i,o={},s="")=>(Object.entries(i).forEach(([a,l])=>{let u=s===""?a:`${s}[${a}]`;l===null?o[u]="":t(l)?o={...o,...r(l,o,u)}:o[u]=encodeURIComponent(l).replaceAll("%20","+").replaceAll("%2C",",")}),o),n=r(e);return Object.entries(n).map(([i,o])=>`${i}=${o}`).join("&")}function mr(e){if(e=e.replace("?",""),e==="")return{};let t=(i,o,s)=>{let[a,l,...u]=i.split(".");if(!l)return s[i]=o;s[a]===void 0&&(s[a]=isNaN(l)?{}:[]),t([l,...u].join("."),o,s[a])},r=e.split("&").map(i=>i.split("=")),n=Object.create(null);return r.forEach(([i,o])=>{if(!(typeof o>"u"))if(o=decodeURIComponent(o.replaceAll("+","%20")),!i.includes("["))n[i]=o;else{let s=i.replaceAll("[",".").replaceAll("]","");t(s,o,n)}}),n}
| |
243902
|
var UploadManager = class {
constructor(component) {
this.component = component;
this.uploadBag = new MessageBag();
this.removeBag = new MessageBag();
}
registerListeners() {
this.component.$wire.$on("upload:generatedSignedUrl", ({ name, url }) => {
setUploadLoading(this.component, name);
this.handleSignedUrl(name, url);
});
this.component.$wire.$on("upload:generatedSignedUrlForS3", ({ name, payload }) => {
setUploadLoading(this.component, name);
this.handleS3PreSignedUrl(name, payload);
});
this.component.$wire.$on("upload:finished", ({ name, tmpFilenames }) => this.markUploadFinished(name, tmpFilenames));
this.component.$wire.$on("upload:errored", ({ name }) => this.markUploadErrored(name));
this.component.$wire.$on("upload:removed", ({ name, tmpFilename }) => this.removeBag.shift(name).finishCallback(tmpFilename));
}
upload(name, file, finishCallback, errorCallback, progressCallback, cancelledCallback) {
this.setUpload(name, {
files: [file],
multiple: false,
finishCallback,
errorCallback,
progressCallback,
cancelledCallback
});
}
uploadMultiple(name, files, finishCallback, errorCallback, progressCallback, cancelledCallback) {
this.setUpload(name, {
files: Array.from(files),
multiple: true,
finishCallback,
errorCallback,
progressCallback,
cancelledCallback
});
}
removeUpload(name, tmpFilename, finishCallback) {
this.removeBag.push(name, {
tmpFilename,
finishCallback
});
this.component.$wire.call("_removeUpload", name, tmpFilename);
}
setUpload(name, uploadObject) {
this.uploadBag.add(name, uploadObject);
if (this.uploadBag.get(name).length === 1) {
this.startUpload(name, uploadObject);
}
}
handleSignedUrl(name, url) {
let formData = new FormData();
Array.from(this.uploadBag.first(name).files).forEach((file) => formData.append("files[]", file, file.name));
let headers = {
"Accept": "application/json"
};
let csrfToken = getCsrfToken();
if (csrfToken)
headers["X-CSRF-TOKEN"] = csrfToken;
this.makeRequest(name, formData, "post", url, headers, (response) => {
return response.paths;
});
}
handleS3PreSignedUrl(name, payload) {
let formData = this.uploadBag.first(name).files[0];
let headers = payload.headers;
if ("Host" in headers)
delete headers.Host;
let url = payload.url;
this.makeRequest(name, formData, "put", url, headers, (response) => {
return [payload.path];
});
}
makeRequest(name, formData, method, url, headers, retrievePaths) {
let request = new XMLHttpRequest();
request.open(method, url);
Object.entries(headers).forEach(([key, value]) => {
request.setRequestHeader(key, value);
});
request.upload.addEventListener("progress", (e) => {
e.detail = {};
e.detail.progress = Math.floor(e.loaded * 100 / e.total);
this.uploadBag.first(name).progressCallback(e);
});
request.addEventListener("load", () => {
if ((request.status + "")[0] === "2") {
let paths = retrievePaths(request.response && JSON.parse(request.response));
this.component.$wire.call("_finishUpload", name, paths, this.uploadBag.first(name).multiple);
return;
}
let errors = null;
if (request.status === 422) {
errors = request.response;
}
this.component.$wire.call("_uploadErrored", name, errors, this.uploadBag.first(name).multiple);
});
this.uploadBag.first(name).request = request;
request.send(formData);
}
startUpload(name, uploadObject) {
let fileInfos = uploadObject.files.map((file) => {
return { name: file.name, size: file.size, type: file.type };
});
this.component.$wire.call("_startUpload", name, fileInfos, uploadObject.multiple);
setUploadLoading(this.component, name);
}
markUploadFinished(name, tmpFilenames) {
unsetUploadLoading(this.component);
let uploadObject = this.uploadBag.shift(name);
uploadObject.finishCallback(uploadObject.multiple ? tmpFilenames : tmpFilenames[0]);
if (this.uploadBag.get(name).length > 0)
this.startUpload(name, this.uploadBag.last(name));
}
markUploadErrored(name) {
unsetUploadLoading(this.component);
this.uploadBag.shift(name).errorCallback();
if (this.uploadBag.get(name).length > 0)
this.startUpload(name, this.uploadBag.last(name));
}
cancelUpload(name, cancelledCallback = null) {
unsetUploadLoading(this.component);
let uploadItem = this.uploadBag.first(name);
if (uploadItem) {
if (uploadItem.request) {
uploadItem.request.abort();
}
this.uploadBag.shift(name).cancelledCallback();
if (cancelledCallback)
cancelledCallback();
}
}
};
var MessageBag = class {
constructor() {
this.bag = {};
}
add(name, thing) {
if (!this.bag[name]) {
this.bag[name] = [];
}
this.bag[name].push(thing);
}
push(name, thing) {
this.add(name, thing);
}
first(name) {
if (!this.bag[name])
return null;
return this.bag[name][0];
}
last(name) {
return this.bag[name].slice(-1)[0];
}
get(name) {
return this.bag[name];
}
shift(name) {
return this.bag[name].shift();
}
call(name, ...params) {
(this.listeners[name] || []).forEach((callback) => {
callback(...params);
});
}
has(name) {
return Object.keys(this.listeners).includes(name);
}
};
function setUploadLoading() {
}
function unsetUploadLoading() {
}
function upload(component, name, file, finishCallback = () => {
}, errorCallback = () => {
}, progressCallback = () => {
}, cancelledCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.upload(name, file, finishCallback, errorCallback, progressCallback, cancelledCallback);
}
function uploadMultiple(component, name, files, finishCallback = () => {
}, errorCallback = () => {
}, progressCallback = () => {
}, cancelledCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.uploadMultiple(name, files, finishCallback, errorCallback, progressCallback, cancelledCallback);
}
function removeUpload(component, name, tmpFilename, finishCallback = () => {
}, errorCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.removeUpload(name, tmpFilename, finishCallback, errorCallback);
}
function cancelUpload(component, name, cancelledCallback = () => {
}) {
let uploadManager = getUploadManager(component);
uploadManager.cancelUpload(name, cancelledCallback);
}
// js/features/supportEntangle.js
var import_alpinejs = __toESM(require_module_cjs());
function generateEntangleFunction(component, cleanup) {
if (!cleanup)
cleanup = () => {
};
return (name, live = false) => {
let isLive = live;
let livewireProperty = name;
let livewireComponent = component.$wire;
let livewirePropertyValue = livewireComponent.get(livewireProperty);
let interceptor = import_alpinejs.default.interceptor((initialValue, getter, setter, path, key) => {
if (typeof livewirePropertyValue === "undefined") {
console.error(`Livewire Entangle Error: Livewire property ['${livewireProperty}'] cannot be found on component: ['${component.name}']`);
return;
}
let release = import_alpinejs.default.entangle({
get() {
return livewireComponent.get(name);
},
set(value) {
livewireComponent.set(name, value, isLive);
}
}, {
get() {
return getter();
},
set(value) {
setter(value);
}
});
cleanup(() => release());
return cloneIfObject(livewireComponent.get(name));
}, (obj) => {
Object.defineProperty(obj, "live", {
get() {
isLive = true;
return obj;
}
});
});
return interceptor(livewirePropertyValue);
};
}
function cloneIfObject(value) {
return typeof value === "object" ? JSON.parse(JSON.stringify(value)) : value;
}
// js/hooks.js
var listeners = [];
function on(name, callback) {
if (!listeners[name])
listeners[name] = [];
listeners[name].push(callback);
return () => {
listeners[name] = listeners[name].filter((i) => i !== callback);
};
}
| |
243910
|
function track(name, initialSeedValue, alwaysShow = false, except = null) {
let { has, get, set, remove } = queryStringUtils();
let url = new URL(window.location.href);
let isInitiallyPresentInUrl = has(url, name);
let initialValue = isInitiallyPresentInUrl ? get(url, name) : initialSeedValue;
let initialValueMemo = JSON.stringify(initialValue);
let exceptValueMemo = [false, null, void 0].includes(except) ? initialSeedValue : JSON.stringify(except);
let hasReturnedToInitialValue = (newValue) => JSON.stringify(newValue) === initialValueMemo;
let hasReturnedToExceptValue = (newValue) => JSON.stringify(newValue) === exceptValueMemo;
if (alwaysShow)
url = set(url, name, initialValue);
replace(url, name, { value: initialValue });
let lock = false;
let update = (strategy, newValue) => {
if (lock)
return;
let url2 = new URL(window.location.href);
if (!alwaysShow && !isInitiallyPresentInUrl && hasReturnedToInitialValue(newValue)) {
url2 = remove(url2, name);
} else if (newValue === void 0) {
url2 = remove(url2, name);
} else if (!alwaysShow && hasReturnedToExceptValue(newValue)) {
url2 = remove(url2, name);
} else {
url2 = set(url2, name, newValue);
}
strategy(url2, name, { value: newValue });
};
return {
initial: initialValue,
replace(newValue) {
update(replace, newValue);
},
push(newValue) {
update(push, newValue);
},
pop(receiver) {
let handler = (e) => {
if (!e.state || !e.state.alpine)
return;
Object.entries(e.state.alpine).forEach(([iName, { value: newValue }]) => {
if (iName !== name)
return;
lock = true;
let result = receiver(newValue);
if (result instanceof Promise) {
result.finally(() => lock = false);
} else {
lock = false;
}
});
};
window.addEventListener("popstate", handler);
return () => window.removeEventListener("popstate", handler);
}
};
}
function replace(url, key, object) {
let state = window.history.state || {};
if (!state.alpine)
state.alpine = {};
state.alpine[key] = unwrap(object);
window.history.replaceState(state, "", url.toString());
}
function push(url, key, object) {
let state = window.history.state || {};
if (!state.alpine)
state.alpine = {};
state = { alpine: { ...state.alpine, ...{ [key]: unwrap(object) } } };
window.history.pushState(state, "", url.toString());
}
function unwrap(object) {
if (object === void 0)
return void 0;
return JSON.parse(JSON.stringify(object));
}
function queryStringUtils() {
return {
has(url, key) {
let search = url.search;
if (!search)
return false;
let data = fromQueryString(search);
return Object.keys(data).includes(key);
},
get(url, key) {
let search = url.search;
if (!search)
return false;
let data = fromQueryString(search);
return data[key];
},
set(url, key, value) {
let data = fromQueryString(url.search);
data[key] = stripNulls(unwrap(value));
url.search = toQueryString(data);
return url;
},
remove(url, key) {
let data = fromQueryString(url.search);
delete data[key];
url.search = toQueryString(data);
return url;
}
};
}
function stripNulls(value) {
if (!isObjecty(value))
return value;
for (let key in value) {
if (value[key] === null)
delete value[key];
else
value[key] = stripNulls(value[key]);
}
return value;
}
function toQueryString(data) {
let isObjecty2 = (subject) => typeof subject === "object" && subject !== null;
let buildQueryStringEntries = (data2, entries2 = {}, baseKey = "") => {
Object.entries(data2).forEach(([iKey, iValue]) => {
let key = baseKey === "" ? iKey : `${baseKey}[${iKey}]`;
if (iValue === null) {
entries2[key] = "";
} else if (!isObjecty2(iValue)) {
entries2[key] = encodeURIComponent(iValue).replaceAll("%20", "+").replaceAll("%2C", ",");
} else {
entries2 = { ...entries2, ...buildQueryStringEntries(iValue, entries2, key) };
}
});
return entries2;
};
let entries = buildQueryStringEntries(data);
return Object.entries(entries).map(([key, value]) => `${key}=${value}`).join("&");
}
function fromQueryString(search) {
search = search.replace("?", "");
if (search === "")
return {};
let insertDotNotatedValueIntoData = (key, value, data2) => {
let [first2, second, ...rest] = key.split(".");
if (!second)
return data2[key] = value;
if (data2[first2] === void 0) {
data2[first2] = isNaN(second) ? {} : [];
}
insertDotNotatedValueIntoData([second, ...rest].join("."), value, data2[first2]);
};
let entries = search.split("&").map((i) => i.split("="));
let data = /* @__PURE__ */ Object.create(null);
entries.forEach(([key, value]) => {
if (typeof value == "undefined")
return;
value = decodeURIComponent(value.replaceAll("+", "%20"));
if (!key.includes("[")) {
data[key] = value;
} else {
let dotNotatedKey = key.replaceAll("[", ".").replaceAll("]", "");
insertDotNotatedValueIntoData(dotNotatedKey, value, data);
}
});
return data;
}
// js/lifecycle.js
var import_morph = __toESM(require_module_cjs8());
var import_mask = __toESM(require_module_cjs9());
var import_alpinejs5 = __toESM(require_module_cjs());
function start() {
setTimeout(() => ensureLivewireScriptIsntMisplaced());
dispatch(document, "livewire:init");
dispatch(document, "livewire:initializing");
import_alpinejs5.default.plugin(import_morph.default);
import_alpinejs5.default.plugin(history2);
import_alpinejs5.default.plugin(import_intersect.default);
import_alpinejs5.default.plugin(import_resize.default);
import_alpinejs5.default.plugin(import_collapse.default);
import_alpinejs5.default.plugin(import_anchor.default);
import_alpinejs5.default.plugin(import_focus.default);
import_alpinejs5.default.plugin(import_persist2.default);
import_alpinejs5.default.plugin(navigate_default);
import_alpinejs5.default.plugin(import_mask.default);
import_alpinejs5.default.addRootSelector(() => "[wire\\:id]");
import_alpinejs5.default.onAttributesAdded((el, attributes) => {
if (!Array.from(attributes).some((attribute) => matchesForLivewireDirective(attribute.name)))
return;
let component = closestComponent(el, false);
if (!component)
return;
attributes.forEach((attribute) => {
if (!matchesForLivewireDirective(attribute.name))
return;
let directive2 = extractDirective(el, attribute.name);
trigger("directive.init", { el, component, directive: directive2, cleanup: (callback) => {
import_alpinejs5.default.onAttributeRemoved(el, directive2.raw, callback);
} });
});
});
import_alpinejs5.default.interceptInit(import_alpinejs5.default.skipDuringClone((el) => {
if (!Array.from(el.attributes).some((attribute) => matchesForLivewireDirective(attribute.name)))
return;
if (el.hasAttribute("wire:id")) {
let component2 = initComponent(el);
import_alpinejs5.default.onAttributeRemoved(el, "wire:id", () => {
destroyComponent(component2.id);
});
}
let component = closestComponent(el, false);
if (component) {
trigger("element.init", { el, component });
let directives = Array.from(el.getAttributeNames()).filter((name) => matchesForLivewireDirective(name)).map((name) => extractDirective(el, name));
directives.forEach((directive2) => {
trigger("directive.init", { el, component, directive: directive2, cleanup: (callback) => {
import_alpinejs5.default.onAttributeRemoved(el, directive2.raw, callback);
} });
});
}
}));
import_alpinejs5.default.start();
setTimeout(() => window.Livewire.initialRenderIsFinished = true);
dispatch(document, "livewire:initialized");
}
| |
243917
|
<?php
return [
/*
|---------------------------------------------------------------------------
| Class Namespace
|---------------------------------------------------------------------------
|
| This value sets the root class namespace for Livewire component classes in
| your application. This value will change where component auto-discovery
| finds components. It's also referenced by the file creation commands.
|
*/
'class_namespace' => 'App\\Livewire',
/*
|---------------------------------------------------------------------------
| View Path
|---------------------------------------------------------------------------
|
| This value is used to specify where Livewire component Blade templates are
| stored when running file creation commands like `artisan make:livewire`.
| It is also used if you choose to omit a component's render() method.
|
*/
'view_path' => resource_path('views/livewire'),
/*
|---------------------------------------------------------------------------
| Layout
|---------------------------------------------------------------------------
| The view that will be used as the layout when rendering a single component
| as an entire page via `Route::get('/post/create', CreatePost::class);`.
| In this case, the view returned by CreatePost will render into $slot.
|
*/
'layout' => 'components.layouts.app',
/*
|---------------------------------------------------------------------------
| Lazy Loading Placeholder
|---------------------------------------------------------------------------
| Livewire allows you to lazy load components that would otherwise slow down
| the initial page load. Every component can have a custom placeholder or
| you can define the default placeholder view for all components below.
|
*/
'lazy_placeholder' => null,
/*
|---------------------------------------------------------------------------
| Temporary File Uploads
|---------------------------------------------------------------------------
|
| Livewire handles file uploads by storing uploads in a temporary directory
| before the file is stored permanently. All file uploads are directed to
| a global endpoint for temporary storage. You may configure this below:
|
*/
'temporary_file_upload' => [
'disk' => null, // Example: 'local', 's3' | Default: 'default'
'rules' => null, // Example: ['file', 'mimes:png,jpg'] | Default: ['required', 'file', 'max:12288'] (12MB)
'directory' => null, // Example: 'tmp' | Default: 'livewire-tmp'
'middleware' => null, // Example: 'throttle:5,1' | Default: 'throttle:60,1'
'preview_mimes' => [ // Supported file types for temporary pre-signed file URLs...
'png', 'gif', 'bmp', 'svg', 'wav', 'mp4',
'mov', 'avi', 'wmv', 'mp3', 'm4a',
'jpg', 'jpeg', 'mpga', 'webp', 'wma',
],
'max_upload_time' => 5, // Max duration (in minutes) before an upload is invalidated...
'cleanup' => true, // Should cleanup temporary uploads older than 24 hrs...
],
/*
|---------------------------------------------------------------------------
| Render On Redirect
|---------------------------------------------------------------------------
|
| This value determines if Livewire will run a component's `render()` method
| after a redirect has been triggered using something like `redirect(...)`
| Setting this to true will render the view once more before redirecting
|
*/
'render_on_redirect' => false,
/*
|---------------------------------------------------------------------------
| Eloquent Model Binding
|---------------------------------------------------------------------------
|
| Previous versions of Livewire supported binding directly to eloquent model
| properties using wire:model by default. However, this behavior has been
| deemed too "magical" and has therefore been put under a feature flag.
|
*/
'legacy_model_binding' => false,
/*
|---------------------------------------------------------------------------
| Auto-inject Frontend Assets
|---------------------------------------------------------------------------
|
| By default, Livewire automatically injects its JavaScript and CSS into the
| <head> and <body> of pages containing Livewire components. By disabling
| this behavior, you need to use @livewireStyles and @livewireScripts.
|
*/
'inject_assets' => true,
/*
|---------------------------------------------------------------------------
| Navigate (SPA mode)
|---------------------------------------------------------------------------
|
| By adding `wire:navigate` to links in your Livewire application, Livewire
| will prevent the default link handling and instead request those pages
| via AJAX, creating an SPA-like effect. Configure this behavior here.
|
*/
'navigate' => [
'show_progress_bar' => true,
'progress_bar_color' => '#2299dd',
],
/*
|---------------------------------------------------------------------------
| HTML Morph Markers
|---------------------------------------------------------------------------
|
| Livewire intelligently "morphs" existing HTML into the newly rendered HTML
| after each update. To make this process more reliable, Livewire injects
| "markers" into the rendered Blade surrounding @if, @class & @foreach.
|
*/
'inject_morph_markers' => true,
/*
|---------------------------------------------------------------------------
| Pagination Theme
|---------------------------------------------------------------------------
|
| When enabling Livewire's pagination feature by using the `WithPagination`
| trait, Livewire will use Tailwind templates to render pagination views
| on the page. If you want Bootstrap CSS, you can specify: "bootstrap"
|
*/
'pagination_theme' => 'tailwind',
];
| |
243956
|
import { isObjecty } from "@/utils"
export default function history(Alpine) {
Alpine.magic('queryString', (el, { interceptor }) => {
let alias
let alwaysShow = false
let usePush = false
return interceptor((initialSeedValue, getter, setter, path, key) => {
let queryKey = alias || path
let { initial, replace, push, pop } = track(queryKey, initialSeedValue, alwaysShow)
setter(initial)
if (! usePush) {
Alpine.effect(() => replace(getter()))
} else {
Alpine.effect(() => push(getter()))
pop(async newValue => {
setter(newValue)
let tillTheEndOfTheMicrotaskQueue = () => Promise.resolve()
await tillTheEndOfTheMicrotaskQueue() // ...so that we preserve the internal lock...
})
}
return initial
}, func => {
func.alwaysShow = () => { alwaysShow = true; return func }
func.usePush = () => { usePush = true; return func }
func.as = key => { alias = key; return func }
})
})
Alpine.history = { track }
}
export function track(name, initialSeedValue, alwaysShow = false, except = null) {
let { has, get, set, remove } = queryStringUtils()
let url = new URL(window.location.href)
let isInitiallyPresentInUrl = has(url, name)
let initialValue = isInitiallyPresentInUrl ? get(url, name) : initialSeedValue
let initialValueMemo = JSON.stringify(initialValue)
let exceptValueMemo = [false, null, undefined].includes(except) ? initialSeedValue : JSON.stringify(except)
let hasReturnedToInitialValue = (newValue) => JSON.stringify(newValue) === initialValueMemo
let hasReturnedToExceptValue = (newValue) => JSON.stringify(newValue) === exceptValueMemo
if (alwaysShow) url = set(url, name, initialValue)
replace(url, name, { value: initialValue })
let lock = false
let update = (strategy, newValue) => {
if (lock) return
let url = new URL(window.location.href)
// This block of code is what needs to be changed for this failing test to pass:
if (! alwaysShow && ! isInitiallyPresentInUrl && hasReturnedToInitialValue(newValue)) {
url = remove(url, name)
// This is so that when deeply nested values are tracked, but their parent array/object
// is removed, we can handle it gracefully by removing the entry from the URL instead
// of letting it get set to `?someKey=undefined` which causes issues on refresh...
} else if (newValue === undefined) {
url = remove(url, name)
} else if (! alwaysShow && hasReturnedToExceptValue(newValue)) {
url = remove(url, name)
} else {
url = set(url, name, newValue)
}
// Right now, the above block, checks a few conditions and updates/removes an entry from the query string.
// The new strategy needs to be something like:
// - If "alwaysShow" is toggled on, then just "set" the whole thing with no deep diff
// - Otherwise, run a deep comparison callback (given the original value and new value).
// - The callback recieves two params (leaf name and value)
// - Check leaf name and value for existance in the original URL from page load. If it's there, just call "set"
// - Check leaf name and value for equivelance to original name and value, if equal, call "remove", otherwise, "set"
// That code will look something like this:
// if (alwaysShow) {
// set(url, name, newValue)
// } else {
// deepCompare(name, newValue, originalValue, (leafName, leafValue) => {
// // ....
// })
// }
strategy(url, name, { value: newValue})
}
return {
initial: initialValue,
replace(newValue) { // Update via replaceState...
update(replace, newValue)
},
push(newValue) { // Update via pushState...
update(push, newValue)
},
pop(receiver) { // "popstate" handler...
let handler = (e) => {
if (! e.state || ! e.state.alpine) return
Object.entries(e.state.alpine).forEach(([iName, { value: newValue }]) => {
if (iName !== name) return
lock = true
// Allow the "receiver" to be an async function in case a non-syncronous
// operation (like an ajax) requests needs to happen while preserving
// the "locking" mechanism ("lock = true" in this case)...
let result = receiver(newValue)
if (result instanceof Promise) {
result.finally(() => lock = false)
} else {
lock = false
}
})
}
window.addEventListener('popstate', handler)
return () => window.removeEventListener('popstate', handler)
}
}
}
function replace(url, key, object) {
let state = window.history.state || {}
if (! state.alpine) state.alpine = {}
state.alpine[key] = unwrap(object)
window.history.replaceState(state, '', url.toString())
}
function push(url, key, object) {
let state = window.history.state || {}
if (! state.alpine) state.alpine = {}
state = { alpine: {...state.alpine, ...{[key]: unwrap(object)}} }
window.history.pushState(state, '', url.toString())
}
function unwrap(object) {
if (object === undefined) return undefined
return JSON.parse(JSON.stringify(object))
}
function queryStringUtils() {
return {
has(url, key) {
let search = url.search
if (! search) return false
let data = fromQueryString(search)
return Object.keys(data).includes(key)
},
get(url, key) {
let search = url.search
if (! search) return false
let data = fromQueryString(search)
return data[key]
},
set(url, key, value) {
let data = fromQueryString(url.search)
data[key] = stripNulls(unwrap(value))
url.search = toQueryString(data)
return url
},
remove(url, key) {
let data = fromQueryString(url.search)
delete data[key]
url.search = toQueryString(data)
return url
},
}
}
function stripNulls(value) {
if (! isObjecty(value)) return value
for (let key in value) {
if (value[key] === null) delete value[key]
else value[key] = stripNulls(value[key])
}
return value
}
// This function converts JavaScript data to bracketed query string notation...
// { items: [['foo']] } -> "items[0][0]=foo"
function toQueryString(data) {
let isObjecty = (subject) => typeof subject === 'object' && subject !== null
let buildQueryStringEntries = (data, entries = {}, baseKey = '') => {
Object.entries(data).forEach(([iKey, iValue]) => {
let key = baseKey === '' ? iKey : `${baseKey}[${iKey}]`
if (iValue === null) {
entries[key] = '';
} else if (! isObjecty(iValue)) {
entries[key] = encodeURIComponent(iValue)
.replaceAll('%20', '+') // Conform to RFC1738
.replaceAll('%2C', ',')
} else {
entries = {...entries, ...buildQueryStringEntries(iValue, entries, key)}
}
})
return entries
}
let entries = buildQueryStringEntries(data)
return Object.entries(entries).map(([key, value]) => `${key}=${value}`).join('&')
}
// This function converts bracketed query string notation back to JS data...
// "items[0][0]=foo" -> { items: [['foo']] }
| |
243957
|
function fromQueryString(search) {
search = search.replace('?', '')
if (search === '') return {}
let insertDotNotatedValueIntoData = (key, value, data) => {
let [first, second, ...rest] = key.split('.')
// We're at a leaf node, let's make the assigment...
if (! second) return data[key] = value
// This is where we fill in empty arrays/objects allong the way to the assigment...
if (data[first] === undefined) {
data[first] = isNaN(second) ? {} : []
}
// Keep deferring assignment until the full key is built up...
insertDotNotatedValueIntoData([second, ...rest].join('.'), value, data[first])
}
let entries = search.split('&').map(i => i.split('='))
// let data = {} creates a security (XSS) vulnerability here. We need to use
// Object.create(null) instead so that we have a "pure" object that doesnt
// inherit Object.prototype and expose the js internals to manipulation.
let data = Object.create(null)
entries.forEach(([key, value]) => {
// Query string params don't always have values... (`?foo=`)
if ( typeof value == 'undefined' ) return;
value = decodeURIComponent(value.replaceAll('+', '%20'))
if (! key.includes('[')) {
data[key] = value
} else {
// Convert to dot notation because it's easier...
let dotNotatedKey = key.replaceAll('[', '.').replaceAll(']', '')
insertDotNotatedValueIntoData(dotNotatedKey, value, data)
}
})
return data
}
| |
243958
|
export function hasQueryParam(param) {
let queryParams = new URLSearchParams(window.location.search);
return queryParams.has(param)
}
export function getQueryParam(param) {
let queryParams = new URLSearchParams(window.location.search);
return queryParams.get(param)
}
export function setQueryParam(param, value) {
let queryParams = new URLSearchParams(window.location.search);
queryParams.set(param, value)
let url = urlFromQueryParams(queryParams)
history.replaceState(history.state, '', url)
}
function urlFromParams(params = {}) {
let queryParams = new URLSearchParams(window.location.search);
Object.entries(params).forEach(([key, value]) => {
queryParams.set(key, value)
})
let queryString = Array.from(queryParams.entries()).length > 0
? '?'+params.toString()
: ''
return window.location.origin + window.location.pathname + '?'+queryString + window.location.hash
}
| |
243988
|
<?php
namespace Tests;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Artisan;
class TestCase extends \Orchestra\Testbench\Dusk\TestCase
{
public function setUp(): void
{
$this->afterApplicationCreated(function () {
$this->makeACleanSlate();
});
$this->beforeApplicationDestroyed(function () {
$this->makeACleanSlate();
});
parent::setUp();
}
public function makeACleanSlate()
{
Artisan::call('view:clear');
File::deleteDirectory($this->livewireViewsPath());
File::deleteDirectory($this->livewireClassesPath());
File::deleteDirectory($this->livewireTestsPath());
File::delete(app()->bootstrapPath('cache/livewire-components.php'));
}
protected function getPackageProviders($app)
{
return [
\Livewire\LivewireServiceProvider::class,
];
}
protected function defineEnvironment($app)
{
$app['config']->set('view.paths', [
__DIR__.'/views',
resource_path('views'),
]);
$app['config']->set('app.key', 'base64:Hupx3yAySikrM2/edkZQNQHslgDWYfiBfCuSThJ5SK8=');
$app['config']->set('database.default', 'testbench');
$app['config']->set('database.connections.testbench', [
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$app['config']->set('filesystems.disks.unit-downloads', [
'driver' => 'local',
'root' => __DIR__.'/fixtures',
]);
}
protected function livewireClassesPath($path = '')
{
return app_path('Livewire'.($path ? '/'.$path : ''));
}
protected function livewireViewsPath($path = '')
{
return resource_path('views').'/livewire'.($path ? '/'.$path : '');
}
protected function livewireTestsPath($path = '')
{
return base_path('tests/Feature/Livewire'.($path ? '/'.$path : ''));
}
}
| |
244000
|
<div>
@foreach ($children as $child)
@livewire('child', ['name' => $child], key($child))
@endforeach
</div>
| |
244013
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<h1>This is a custom layout</h1>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244014
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244015
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $header ?? 'No Header' }}
{{ $slot }}
{{ $footer ?? 'No Footer' }}
</body>
</html>
| |
244016
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
<style>
.show {
display: block;
}
</style>
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244028
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244030
|
<html>
<head>
<meta name="csrf-token" content="{{ csrf_token() }}">
@stack('styles')
</head>
<body>
{{ $slot }}
@stack('scripts')
</body>
</html>
| |
244037
|
Because forms are the backbone of most web applications, Livewire provides loads of helpful utilities for building them. From handling simple input elements to complex things like real-time validation or file uploading, Livewire has simple, well-documented tools to make your life easier and delight your users.
Let's dive in.
## Submitting a form
Let's start by looking at a very simple form in a `CreatePost` component. This form will have two simple text inputs and a submit button, as well as some code on the backend to manage the form's state and submission:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title = '';
public $content = '';
public function save()
{
Post::create(
$this->only(['title', 'content'])
);
session()->flash('status', 'Post successfully updated.');
return $this->redirect('/posts');
}
public function render()
{
return view('livewire.create-post');
}
}
```
```blade
<form wire:submit="save">
<input type="text" wire:model="title">
<input type="text" wire:model="content">
<button type="submit">Save</button>
</form>
```
As you can see, we are "binding" the public `$title` and `$content` properties in the form above using `wire:model`. This is one of the most commonly used and powerful features of Livewire.
In addition to binding `$title` and `$content`, we are using `wire:submit` to capture the `submit` event when the "Save" button is clicked and invoking the `save()` action. This action will persist the form input to the database.
After the new post is created in the database, we redirect the user to the `ShowPosts` component page and show them a "flash" message that the new post was created.
### Adding validation
To avoid storing incomplete or dangerous user input, most forms need some sort of input validation.
Livewire makes validating your forms as simple as adding `#[Validate]` attributes above the properties you want to be validated.
Once a property has a `#[Validate]` attribute attached to it, the validation rule will be applied to the property's value any time it's updated server-side.
Let's add some basic validation rules to the `$title` and `$content` properties in our `CreatePost` component:
```php
<?php
namespace App\Livewire;
use Livewire\Attributes\Validate; // [tl! highlight]
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
#[Validate('required')] // [tl! highlight]
public $title = '';
#[Validate('required')] // [tl! highlight]
public $content = '';
public function save()
{
$this->validate(); // [tl! highlight]
Post::create(
$this->only(['title', 'content'])
);
return $this->redirect('/posts');
}
public function render()
{
return view('livewire.create-post');
}
}
```
We'll also modify our Blade template to show any validation errors on the page.
```blade
<form wire:submit="save">
<input type="text" wire:model="title">
<div>
@error('title') <span class="error">{{ $message }}</span> @enderror <!-- [tl! highlight] -->
</div>
<input type="text" wire:model="content">
<div>
@error('content') <span class="error">{{ $message }}</span> @enderror <!-- [tl! highlight] -->
</div>
<button type="submit">Save</button>
</form>
```
Now, if the user tries to submit the form without filling in any of the fields, they will see validation messages telling them which fields are required before saving the post.
Livewire has a lot more validation features to offer. For more information, visit our [dedicated documentation page on Validation](/docs/validation).
### Extracting a form object
If you are working with a large form and prefer to extract all of its properties, validation logic, etc., into a separate class, Livewire offers form objects.
Form objects allow you to re-use form logic across components and provide a nice way to keep your component class cleaner by grouping all form-related code into a separate class.
You can either create a form class by hand or use the convenient artisan command:
```shell
php artisan livewire:form PostForm
```
The above command will create a file called `app/Livewire/Forms/PostForm.php`.
Let's rewrite the `CreatePost` component to use a `PostForm` class:
```php
<?php
namespace App\Livewire\Forms;
use Livewire\Attributes\Validate;
use Livewire\Form;
class PostForm extends Form
{
#[Validate('required|min:5')]
public $title = '';
#[Validate('required|min:5')]
public $content = '';
}
```
```php
<?php
namespace App\Livewire;
use App\Livewire\Forms\PostForm;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public PostForm $form; // [tl! highlight]
public function save()
{
$this->validate();
Post::create(
$this->form->all() // [tl! highlight]
);
return $this->redirect('/posts');
}
public function render()
{
return view('livewire.create-post');
}
}
```
```blade
<form wire:submit="save">
<input type="text" wire:model="form.title">
<div>
@error('form.title') <span class="error">{{ $message }}</span> @enderror
</div>
<input type="text" wire:model="form.content">
<div>
@error('form.content') <span class="error">{{ $message }}</span> @enderror
</div>
<button type="submit">Save</button>
</form>
```
If you'd like, you can also extract the post creation logic into the form object like so:
```php
<?php
namespace App\Livewire\Forms;
use Livewire\Attributes\Validate;
use App\Models\Post;
use Livewire\Form;
class PostForm extends Form
{
#[Validate('required|min:5')]
public $title = '';
#[Validate('required|min:5')]
public $content = '';
public function store() // [tl! highlight:5]
{
$this->validate();
Post::create($this->all());
}
}
```
Now you can call `$this->form->store()` from the component:
```php
class CreatePost extends Component
{
public PostForm $form;
public function save()
{
$this->form->store(); // [tl! highlight]
return $this->redirect('/posts');
}
// ...
}
```
If you want to use this form object for both a create and update form, you can easily adapt it to handle both use cases.
Here's what it would look like to use this same form object for an `UpdatePost` component and fill it with initial data:
```php
<?php
namespace App\Livewire;
use App\Livewire\Forms\PostForm;
use Livewire\Component;
use App\Models\Post;
class UpdatePost extends Component
{
public PostForm $form;
public function mount(Post $post)
{
$this->form->setPost($post);
}
public function save()
{
$this->form->update();
return $this->redirect('/posts');
}
public function render()
{
return view('livewire.create-post');
}
}
```
```php
<?php
namespace App\Livewire\Forms;
use Livewire\Attributes\Validate;
use Livewire\Form;
use App\Models\Post;
class PostForm extends Form
{
public ?Post $post;
#[Validate('required|min:5')]
public $title = '';
#[Validate('required|min:5')]
public $content = '';
public function setPost(Post $post)
{
$this->post = $post;
$this->title = $post->title;
$this->content = $post->content;
}
public function store()
{
$this->validate();
Post::create($this->only(['title', 'content']));
}
public function update()
{
$this->validate();
$this->post->update(
$this->all()
);
}
}
```
As you can see, we've added a `setPost()` method to the `PostForm` object to optionally allow for filling the form with existing data as well as storing the post on the form object for later use. We've also added an `update()` method for updating the existing post.
Form objects are not required when working with Livewire, but they do offer a nice abstraction for keeping your components free of repetitive boilerplate.
| |
244038
|
### Resetting form fields
If you are using a form object, you may want to reset the form after it has been submitted. This can be done by calling the `reset()` method:
```php
<?php
namespace App\Livewire\Forms;
use Livewire\Attributes\Validate;
use App\Models\Post;
use Livewire\Form;
class PostForm extends Form
{
#[Validate('required|min:5')]
public $title = '';
#[Validate('required|min:5')]
public $content = '';
// ...
public function store()
{
$this->validate();
Post::create($this->all());
$this->reset(); // [tl! highlight]
}
}
```
You can also reset specific properties by passing the property names into the `reset()` method:
```php
$this->reset('title');
// Or multiple at once...
$this->reset(['title', 'content']);
```
### Pulling form fields
Alternatively, you can use the `pull()` method to both retrieve a form's properties and reset them in one operation.
```php
<?php
namespace App\Livewire\Forms;
use Livewire\Attributes\Validate;
use App\Models\Post;
use Livewire\Form;
class PostForm extends Form
{
#[Validate('required|min:5')]
public $title = '';
#[Validate('required|min:5')]
public $content = '';
// ...
public function store()
{
$this->validate();
Post::create(
$this->pull() // [tl! highlight]
);
}
}
```
You can also pull specific properties by passing the property names into the `pull()` method:
```php
// Return a value before resetting...
$this->pull('title');
// Return a key-value array of properties before resetting...
$this->pull(['title', 'content']);
```
### Using Rule objects
If you have more sophisticated validation scenarios where Laravel's `Rule` objects are necessary, you can alternatively define a `rules()` method to declare your validation rules like so:
```php
<?php
namespace App\Livewire\Forms;
use Illuminate\Validation\Rule;
use App\Models\Post;
use Livewire\Form;
class PostForm extends Form
{
public ?Post $post;
public $title = '';
public $content = '';
protected function rules()
{
return [
'title' => [
'required',
Rule::unique('posts')->ignore($this->post), // [tl! highlight]
],
'content' => 'required|min:5',
];
}
// ...
public function update()
{
$this->validate();
$this->post->update($this->all());
$this->reset();
}
}
```
When using a `rules()` method instead of `#[Validate]`, Livewire will only run the validation rules when you call `$this->validate()`, rather than every time a property is updated.
If you are using real-time validation or any other scenario where you'd like Livewire to validate specific fields after every request, you can use `#[Validate]` without any provided rules like so:
```php
<?php
namespace App\Livewire\Forms;
use Livewire\Attributes\Validate;
use Illuminate\Validation\Rule;
use App\Models\Post;
use Livewire\Form;
class PostForm extends Form
{
public ?Post $post;
#[Validate] // [tl! highlight]
public $title = '';
public $content = '';
protected function rules()
{
return [
'title' => [
'required',
Rule::unique('posts')->ignore($this->post),
],
'content' => 'required|min:5',
];
}
// ...
public function update()
{
$this->validate();
$this->post->update($this->all());
$this->reset();
}
}
```
Now if the `$title` property is updated before the form is submitted—like when using [`wire:model.blur`](/docs/wire-model#updating-on-blur-event)—the validation for `$title` will be run.
### Showing a loading indicator
By default, Livewire will automatically disable submit buttons and mark inputs as `readonly` while a form is being submitted, preventing the user from submitting the form again while the first submission is being handled.
However, it can be difficult for users to detect this "loading" state without extra affordances in your application's UI.
Here's an example of adding a small loading spinner to the "Save" button via `wire:loading` so that a user understands that the form is being submitted:
```blade
<button type="submit">
Save
<div wire:loading>
<svg>...</svg> <!-- SVG loading spinner -->
</div>
</button>
```
Now, when a user presses "Save", a small, inline spinner will show up.
Livewire's `wire:loading` feature has a lot more to offer. Visit the [Loading documentation to learn more.](/docs/wire-loading)
## Live-updating fields
By default, Livewire only sends a network request when the form is submitted (or any other [action](/docs/actions) is called), not while the form is being filled out.
Take the `CreatePost` component, for example. If you want to make sure the "title" input field is synchronized with the `$title` property on the backend as the user types, you may add the `.live` modifier to `wire:model` like so:
```blade
<input type="text" wire:model.live="title">
```
Now, as a user types into this field, network requests will be sent to the server to update `$title`. This is useful for things like a real-time search, where a dataset is filtered as a user types into a search box.
## Only updating fields on _blur_
For most cases, `wire:model.live` is fine for real-time form field updating; however, it can be overly network resource-intensive on text inputs.
If instead of sending network requests as a user types, you want to instead only send the request when a user "tabs" out of the text input (also referred to as "blurring" an input), you can use the `.blur` modifier instead:
```blade
<input type="text" wire:model.blur="title" >
```
Now the component class on the server won't be updated until the user presses tab or clicks away from the text input.
## Real-time validation
Sometimes, you may want to show validation errors as the user fills out the form. This way, they are alerted early that something is wrong instead of having to wait until the entire form is filled out.
Livewire handles this sort of thing automatically. By using `.live` or `.blur` on `wire:model`, Livewire will send network requests as the user fills out the form. Each of those network requests will run the appropriate validation rules before updating each property. If validation fails, the property won't be updated on the server and a validation message will be shown to the user:
```blade
<input type="text" wire:model.blur="title">
<div>
@error('title') <span class="error">{{ $message }}</span> @enderror
</div>
```
```php
#[Validate('required|min:5')]
public $title = '';
```
Now, if the user only types three characters into the "title" input, then clicks on the next input in the form, a validation message will be shown to them indicating there is a five character minimum for that field.
For more information, check out the [validation documentation page](/docs/validation).
## R
| |
244040
|
xtracting input fields to Blade components
Even in a small component such as the `CreatePost` example we've been discussing, we end up duplicating lots of form field boilerplate like validation messages and labels.
It can be helpful to extract repetitive UI elements such as these into dedicated [Blade components](https://laravel.com/docs/blade#components) to be shared across your application.
For example, below is the original Blade template from the `CreatePost` component. We will be extracting the following two text inputs into dedicated Blade components:
```blade
<form wire:submit="save">
<input type="text" wire:model="title"> <!-- [tl! highlight:3] -->
<div>
@error('title') <span class="error">{{ $message }}</span> @enderror
</div>
<input type="text" wire:model="content"> <!-- [tl! highlight:3] -->
<div>
@error('content') <span class="error">{{ $message }}</span> @enderror
</div>
<button type="submit">Save</button>
</form>
```
Here's what the template will look like after extracting a re-usable Blade component called `<x-input-text>`:
```blade
<form wire:submit="save">
<x-input-text name="title" wire:model="title" /> <!-- [tl! highlight] -->
<x-input-text name="content" wire:model="content" /> <!-- [tl! highlight] -->
<button type="submit">Save</button>
</form>
```
Next, here's the source for the `x-input-text` component:
```blade
<!-- resources/views/components/input-text.blade.php -->
@props(['name'])
<input type="text" name="{{ $name }}" {{ $attributes }}>
<div>
@error($name) <span class="error">{{ $message }}</span> @enderror
</div>
```
As you can see, we took the repetitive HTML and placed it inside a dedicated Blade component.
For the most part, the Blade component contains only the extracted HTML from the original component. However, we have added two things:
* The `@props` directive
* The `{{ $attributes }}` statement on the input
Let's discuss each of these additions:
By specifying `name` as a "prop" using `@props(['name'])` we are telling Blade: if an attribute called "name" is set on this component, take its value and make it available inside this component as `$name`.
For other attributes that don't have an explicit purpose, we used the `{{ $attributes }}` statement. This is used for "attribute forwarding", or in other words, taking any HTML attributes written on the Blade component and forwarding them onto an element within the component.
This ensures `wire:model="title"` and any other extra attributes such as `disabled`, `class="..."`, or `required` still get forwarded to the actual `<input>` element.
### Custom form controls
In the previous example, we "wrapped" an input element into a re-usable Blade component we can use as if it was a native HTML input element.
This pattern is very useful; however, there might be some cases where you want to create an entire input component from scratch (without an underlying native input element), but still be able to bind its value to Livewire properties using `wire:model`.
For example, let's imagine you wanted to create an `<x-input-counter />` component that was a simple "counter" input written in Alpine.
Before we create a Blade component, let's first look at a simple, pure-Alpine, "counter" component for reference:
```blade
<div x-data="{ count: 0 }">
<button x-on:click="count--">-</button>
<span x-text="count"></span>
<button x-on:click="count++">+</button>
</div>
```
As you can see, the component above shows a number alongside two buttons to increment and decrement that number.
Now, let's imagine we want to extract this component into a Blade component called `<x-input-counter />` that we would use within a component like so:
```blade
<x-input-counter wire:model="quantity" />
```
Creating this component is mostly simple. We take the HTML of the counter and place it inside a Blade component template like `resources/views/components/input-counter.blade.php`.
However, making it work with `wire:model="quantity"` so that you can easily bind data from your Livewire component to the "count" inside this Alpine component needs one extra step.
Here's the source for the component:
```blade
<!-- resources/view/components/input-counter.blade.php -->
<div x-data="{ count: 0 }" x-modelable="count" {{ $attributes}}>
<button x-on:click="count--">-</button>
<span x-text="count"></span>
<button x-on:click="count++">+</button>
</div>
```
As you can see, the only different bit about this HTML is the `x-modelable="count"` and `{{ $attributes }}`.
`x-modelable` is a utility in Alpine that tells Alpine to make a certain piece of data available for binding from outside. [The Alpine documentation has more information on this directive.](https://alpinejs.dev/directives/modelable)
`{{ $attributes }}`, as we explored earlier, forwards any attributes passed into the Blade component from outside. In this case, the `wire:model` directive will be forwarded.
Because of `{{ $attributes }}`, when the HTML is rendered in the browser, `wire:model="quantity"` will be rendered alongside `x-modelable="count"` on the root `<div>` of the Alpine component like so:
```blade
<div x-data="{ count: 0 }" x-modelable="count" wire:model="quantity">
```
`x-modelable="count"` tells Alpine to look for any `x-model` or `wire:model` statements and use "count" as the data to bind them to.
Because `x-modelable` works for both `wire:model` and `x-model`, you can also use this Blade component interchangeably with Livewire and Alpine. For example, here's an example of using this Blade component in a purely Alpine context:
```blade
<x-input-counter x-model="quantity" />
```
Creating custom input elements in your application is extremely powerful but requires a deeper understanding of the utilities Livewire and Alpine provide and how they interact with each other.
| |
244047
|
Here at Livewire HQ, we try to remove problems from your pathway before you hit them. However, sometimes, there are some problems that we can't solve without introducing new ones, and other times, there are problems we can't anticipate.
Here are some common errors and scenarios you may encounter in your Livewire apps.
## Component mismatches
When interacting with Livewire components on your page, you may encounter odd behavior or error messages like the following:
```
Error: Component already initialized
```
```
Error: Snapshot missing on Livewire component with id: ...
```
There are lots of reasons why you may encounter these messages, but the most common one is forgetting to add `wire:key` to elements and components inside a `@foreach` loop.
### Adding `wire:key`
Any time you have a loop in your Blade templates using something like `@foreach`, you need to add `wire:key` to the opening tag of the first element within the loop:
```blade
@foreach($posts as $post)
<div wire:key="{{ $post->id }}"> <!-- [tl! highlight] -->
...
</div>
@endforeach
```
This ensures that Livewire can keep track of different elements in the loop when the loop changes.
The same applies to Livewire components within a loop:
```blade
@foreach($posts as $post)
<livewire:show-post :$post :key="$post->id" /> <!-- [tl! highlight] -->
@endforeach
```
However, here's a tricky scenario you might not have assumed:
When you have a Livewire component deeply nested inside a `@foreach` loop, you STILL need to add a key to it. For example:
```blade
@foreach($posts as $post)
<div wire:key="{{ $post->id }}">
...
<livewire:show-post :$post :key="$post->id" /> <!-- [tl! highlight] -->
...
</div>
@endforeach
```
Without the key on the nested Livewire component, Livewire will be unable to match the looped components up between network requests.
#### Prefixing keys
Another tricky scenario you may run into is having duplicate keys within the same component. This often results from using model IDs as keys, which can sometimes collide.
Here's an example where we need to add a `post-` and an `author-` prefix to designate each set of keys as unique. Otherwise, if you have a `$post` and `$author` model with the same ID, you would have an ID collision:
```blade
<div>
@foreach($posts as $post)
<div wire:key="post-{{ $post->id }}">...</div> <!-- [tl! highlight] -->
@endforeach
@foreach($authors as $author)
<div wire:key="author-{{ $author->id }}">...</div> <!-- [tl! highlight] -->
@endforeach
</div>
```
## Multiple instances of Alpine
When installing Livewire, you may run into error messages like the following:
```
Error: Detected multiple instances of Alpine running
```
```
Alpine Expression Error: $wire is not defined
```
If this is the case, you likely have two versions of Alpine running on the same page. Livewire includes its own bundle of Alpine under the hood, so you must remove any other versions of Alpine on Livewire pages in your application.
One common scenario in which this happens is adding Livewire to an existing application that already includes Alpine. For example, if you installed the Laravel Breeze starter kit and then added Livewire later, you would run into this.
The fix for this is simple: remove the extra Alpine instance.
### Removing Laravel Breeze's Alpine
If you are installing Livewire inside an existing Laravel Breeze (Blade + Alpine version), you need to remove the following lines from `resources/js/app.js`:
```js
import './bootstrap';
import Alpine from 'alpinejs'; // [tl! remove:4]
window.Alpine = Alpine;
Alpine.start();
```
### Removing a CDN version of Alpine
Because Livewire version 2 and below didn't include Alpine by default, you may have included an Alpine CDN as a script tag in the head of your layout. In Livewire v3, you can remove this CDN altogether, and Livewire will automatically provide Alpine for you:
```html
...
<script defer src="https://cdn.jsdelivr.net/npm/alpinejs@3.x.x/dist/cdn.min.js"></script> <!-- [tl! remove] -->
</head>
```
Note: you can also remove any additional Alpine plugins, as Livewire includes all Alpine plugins except `@alpinejs/ui`.
## Missing `@alpinejs/ui`
Livewire's bundled version of Alpine includes all Alpine plugins EXCEPT `@alpinejs/ui`. If you are using headless components from [Alpine Components](https://alpinejs.dev/components), which relies on this plugin, you may encounter errors like the following:
```
Uncaught Alpine: no element provided to x-anchor
```
To fix this, you can simply include the `@alpinejs/ui` plugin as a CDN in your layout file like so:
```html
...
<script defer src="https://unpkg.com/@alpinejs/ui@3.13.7-beta.0/dist/cdn.min.js"></script> <!-- [tl! add] -->
</head>
```
Note: be sure to include the latest version of this plugin, which you can find on [any component's documentation page](https://alpinejs.dev/component/headless-dialog/docs).
| |
244049
|
## Controlling Livewire from Alpine using `$wire`
One of the most powerful features available to you as a Livewire developer is `$wire`. The `$wire` object is a magic object available to all your Alpine components that are used inside of Livewire.
You can think of `$wire` as a gateway from JavaScript into PHP. It allows you to access and modify Livewire component properties, call Livewire component methods, and do much more; all from inside AlpineJS.
### Accessing Livewire properties
Here is an example of a simple "character count" utility in a form for creating a post. This will instantly show a user how many characters are contained inside their post's content as they type:
```html
<form wire:submit="save">
<!-- ... -->
<input wire:model="content" type="text">
<small>
Character count: <span x-text="$wire.content.length"></span> <!-- [tl! highlight] -->
</small>
<button type="submit">Save</button>
</form>
```
As you can see `x-text` in the above example is being used to allow Alpine to control the text content of the `<span>` element. `x-text` accepts any JavaScript expression inside of it and automatically reacts when any dependencies are updated. Because we are using `$wire.content` to access the value of `$content`, Alpine will automatically update the text content every time `$wire.content` is updated from Livewire; in this case by `wire:model="content"`.
### Mutating Livewire properties
Here is an example of using `$wire` inside Alpine to clear the "title" field of a form for creating a post.
```html
<form wire:submit="save">
<input wire:model="title" type="text">
<button type="button" x-on:click="$wire.title = ''">Clear</button> <!-- [tl! highlight] -->
<!-- ... -->
<button type="submit">Save</button>
</form>
```
As a user is filling out the above Livewire form, they can press "Clear" and the title field will be cleared without sending a network request from Livewire. The interaction will be "instant".
Here's a brief explanation of what's going on to make that happen:
* `x-on:click` tells Alpine to listen for a click on the button element
* When clicked, Alpine runs the provided JS expression: `$wire.title = ''`
* Because `$wire` is a magic object representing the Livewire component, all properties from your component can be accessed or mutated straight from JavaScript
* `$wire.title = ''` sets the value of `$title` in your Livewire component to an empty string
* Any Livewire utilities like `wire:model` will instantly react to this change, all without sending a server-roundtrip
* On the next Livewire network request, the `$title` property will be updated to an empty string on the backend
### Calling Livewire methods
Alpine can also easily call any Livewire methods/actions by simply calling them directly on `$wire`.
Here is an example of using Alpine to listen for a "blur" event on an input and triggering a form save. The "blur" event is dispatched by the browser when a user presses "tab" to remove focus from the current element and focus on the next one on the page:
```html
<form wire:submit="save">
<input wire:model="title" type="text" x-on:blur="$wire.save()"> <!-- [tl! highlight] -->
<!-- ... -->
<button type="submit">Save</button>
</form>
```
Typically, you would just use `wire:model.blur="title"` in this situation, however, it's helpful for demonstration purposes how you can achieve this using Alpine.
#### Passing parameters
You can also pass parameters to Livewire methods by simply passing them to the `$wire` method call.
Consider a component with a `deletePost()` method like so:
```php
public function deletePost($postId)
{
$post = Post::find($postId);
// Authorize user can delete...
auth()->user()->can('update', $post);
$post->delete();
}
```
Now, you can pass a `$postId` parameter to the `deletePost()` method from Alpine like so:
```html
<button type="button" x-on:click="$wire.deletePost(1)">
```
In general, something like a `$postId` would be generated in Blade. Here's an example of using Blade to determine which `$postId` Alpine passes into `deletePost()`:
```html
@foreach ($posts as $post)
<button type="button" x-on:click="$wire.deletePost({{ $post->id }})">
Delete "{{ $post->title }}"
</button>
@endforeach
```
If there are three posts on the page, the above Blade template will render to something like the following in the browser:
```html
<button type="button" x-on:click="$wire.deletePost(1)">
Delete "The power of walking"
</button>
<button type="button" x-on:click="$wire.deletePost(2)">
Delete "How to record a song"
</button>
<button type="button" x-on:click="$wire.deletePost(3)">
Delete "Teach what you learn"
</button>
```
As you can see, we've used Blade to render different post IDs into the Alpine `x-on:click` expressions.
#### Blade parameter "gotchas"
This is an extremely powerful technique, but can be confusing when reading your Blade templates. It can be hard to know which parts are Blade and which parts are Alpine at first glance. Therefore, it's helpful to inspect the HTML rendered on the page to make sure what you are expecting to be rendered is accurate.
Here's an example that commonly confuses people:
Let's say, instead of an ID, your Post model uses UUIDs for indexes (IDs are integers, and UUIDs are long strings of characters).
If we render the following just like we did with an ID there will be an issue:
```html
<!-- Warning: this is an example of problematic code... -->
<button
type="button"
x-on:click="$wire.deletePost({{ $post->uuid }})"
>
```
The above Blade template will render the following in your HTML:
```html
<!-- Warning: this is an example of problematic code... -->
<button
type="button"
x-on:click="$wire.deletePost(93c7b04c-c9a4-4524-aa7d-39196011b81a)"
>
```
Notice the lack of quotes around the UUID string? When Alpine goes to evaluate this expression, JavaScript will throw an error: "Uncaught SyntaxError: Invalid or unexpected token".
To fix this, we need to add quotations around the Blade expression like so:
```html
<button
type="button"
x-on:click="$wire.deletePost('{{ $post->uuid }}')"
>
```
Now the above template will render properly and everything will work as expected:
```html
<button
type="button"
x-on:click="$wire.deletePost('93c7b04c-c9a4-4524-aa7d-39196011b81a')"
>
```
### Refreshing a component
You can easily refresh a Livewire component (trigger network roundtrip to re-render a component's Blade view) using `$wire.$refresh()`:
```html
<button type="button" x-on:click="$wire.$refresh()">
```
| |
244051
|
Livewire makes it easy to bind a component property's value with form inputs using `wire:model`.
Here is a simple example of using `wire:model` to bind the `$title` and `$content` properties with form inputs in a "Create Post" component:
```php
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title = '';
public $content = '';
public function save()
{
$post = Post::create([
'title' => $this->title
'content' => $this->content
]);
// ...
}
}
```
```blade
<form wire:submit="save">
<label>
<span>Title</span>
<input type="text" wire:model="title"> <!-- [tl! highlight] -->
</label>
<label>
<span>Content</span>
<textarea wire:model="content"></textarea> <!-- [tl! highlight] -->
</label>
<button type="submit">Save</button>
</form>
```
Because both inputs use `wire:model`, their values will be synchronized with the server's properties when the "Save" button is pressed.
> [!warning] "Why isn't my component live updating as I type?"
> If you tried this in your browser and are confused why the title isn't automatically updating, it's because Livewire only updates a component when an "action" is submitted—like pressing a submit button—not when a user types into a field. This cuts down on network requests and improves performance. To enable "live" updating as a user types, you can use `wire:model.live` instead. [Learn more about data binding](/docs/properties#data-binding).
## Customizing update timing
By default, Livewire will only send a network request when an action is performed (like `wire:click` or `wire:submit`), NOT when a `wire:model` input is updated.
This drastically improves the performance of Livewire by reducing network requests and provides a smoother experience for your users.
However, there are occasions where you may want to update the server more frequently for things like real-time validation.
### Live updating
To send property updates to the server as a user types into an input-field, you can append the `.live` modifier to `wire:model`:
```html
<input type="text" wire:model.live="title">
```
#### Customizing the debounce
By default, when using `wire:model.live`, Livewire adds a 150 millisecond debounce to server updates. This means if a user is continually typing, Livewire will wait until the user stops typing for 150 milliseconds before sending a request.
You can customize this timing by appending `.debounce.Xms` to the input. Here is an example of changing the debounce to 250 milliseconds:
```html
<input type="text" wire:model.live.debounce.250ms="title">
```
### Updating on "blur" event
By appending the `.blur` modifier, Livewire will only send network requests with property updates when a user clicks away from an input, or presses the tab key to move to the next input.
Adding `.blur` is helpful for scenarios where you want to update the server more frequently, but not as a user types. For example, real-time validation is a common instance where `.blur` is helpful.
```html
<input type="text" wire:model.blur="title">
```
### Updating on "change" event
There are times when the behavior of `.blur` isn't exactly what you want and instead `.change` is.
For example, if you want to run validation every time a select input is changed, by adding `.change`, Livewire will send a network request and validate the property as soon as a user selects a new option. As opposed to `.blur` which will only update the server after the user tabs away from the select input.
```html
<select wire:model.change="title">
<!-- ... -->
</select>
```
Any changes made to the text input will be automatically synchronized with the `$title` property in your Livewire component.
## All available modifiers
Modifier | Description
-------------------|-------------------------------------------------------------------------
`.live` | Send updates as a user types
`.blur` | Only send updates on the `blur` event
`.change` | Only send updates on the the `change` event
`.lazy` | An alias for `.change`
`.debounce.[?]ms` | Debounce the sending of updates by the specified millisecond delay
`.throttle.[?]ms` | Throttle network request updates by the specified millisecond interval
`.number` | Cast the text value of an input to `int` on the server
`.boolean` | Cast the text value of an input to `bool` on the server
`.fill` | Use the initial value provided by a "value" HTML attribute on page-load
## I
| |
244052
|
nput fields
Livewire supports most native input elements out of the box. Meaning you should just be able to attach `wire:model` to any input element in the browser and easily bind properties to them.
Here's a comprehensive list of the different available input types and how you use them in a Livewire context.
### Text inputs
First and foremost, text inputs are the bedrock of most forms. Here's how to bind a property named "title" to one:
```blade
<input type="text" wire:model="title">
```
### Textarea inputs
Textarea elements are similarly straightforward. Simply add `wire:model` to a textarea and the value will be bound:
```blade
<textarea type="text" wire:model="content"></textarea>
```
If the "content" value is initialized with a string, Livewire will fill the textarea with that value - there's no need to do something like the following:
```blade
<!-- Warning: This snippet demonstrates what NOT to do... -->
<textarea type="text" wire:model="content">{{ $content }}</textarea>
```
### Checkboxes
Checkboxes can be used for single values, such as when toggling a boolean property. Or, checkboxes may be used to toggle a single value in a group of related values. We'll discuss both scenarios:
#### Single checkbox
At the end of a signup form, you might have a checkbox allowing the user to opt-in to email updates. You might call this property `$receiveUpdates`. You can easily bind this value to the checkbox using `wire:model`:
```blade
<input type="checkbox" wire:model="receiveUpdates">
```
Now when the `$receiveUpdates` value is `false`, the checkbox will be unchecked. Of course, when the value is `true`, the checkbox will be checked.
#### Multiple checkboxes
Now, let's say in addition to allowing the user to decide to receive updates, you have an array property in your class called `$updateTypes`, allowing the user to choose from a variety of update types:
```php
public $updateTypes = [];
```
By binding multiple checkboxes to the `$updateTypes` property, the user can select multiple update types and they will be added to the `$updateTypes` array property:
```blade
<input type="checkbox" value="email" wire:model="updateTypes">
<input type="checkbox" value="sms" wire:model="updateTypes">
<input type="checkbox" value="notification" wire:model="updateTypes">
```
For example, if the user checks the first two boxes but not the third, the value of `$updateTypes` will be: `["email", "sms"]`
### Radio buttons
To toggle between two different values for a single property, you may use radio buttons:
```blade
<input type="radio" value="yes" wire:model="receiveUpdates">
<input type="radio" value="no" wire:model="receiveUpdates">
```
### Select dropdowns
Livewire makes it simple to work with `<select>` dropdowns. When adding `wire:model` to a dropdown, the currently selected value will be bound to the provided property name and vice versa.
In addition, there's no need to manually add `selected` to the option that will be selected - Livewire handles that for you automatically.
Below is an example of a select dropdown filled with a static list of states:
```blade
<select wire:model="state">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
...
</select>
```
When a specific state is selected, for example, "Alaska", the `$state` property on the component will be set to `AK`. If you would prefer the value to be set to "Alaska" instead of "AK", you can leave the `value=""` attribute off the `<option>` element entirely.
Often, you may build your dropdown options dynamically using Blade:
```blade
<select wire:model="state">
@foreach (\App\Models\State::all() as $state)
<option value="{{ $state->id }}">{{ $state->label }}</option>
@endforeach
</select>
```
If you don't have a specific option selected by default, you may want to show a muted placeholder option by default, such as "Select a state":
```blade
<select wire:model="state">
<option disabled value="">Select a state...</option>
@foreach (\App\Models\State::all() as $state)
<option value="{{ $state->id }}">{{ $state->label }}</option>
@endforeach
</select>
```
As you can see, there is no "placeholder" attribute for a select menu like there is for text inputs. Instead, you have to add a `disabled` option element as the first option in the list.
### Dependent select dropdowns
Sometimes you may want one select menu to be dependent on another. For example, a list of cities that changes based on which state is selected.
For the most part, this works as you'd expect, however there is one important gotcha: You must add a `wire:key` to the changing select so that Livewire properly refreshes it's value when the options change.
Here's an example of two selects, one for states, one for cities. When the state select changes, the options in the city select will change properly:
```blade
<!-- States select menu... -->
<select wire:model.live="selectedState">
@foreach (State::all() as $state)
<option value="{{ $state->id }}">{{ $state->label }}</option>
@endforeach
</select>
<!-- Cities dependent select menu... -->
<select wire:model.live="selectedCity" wire:key="{{ $selectedState }}"> <!-- [tl! highlight] -->
@foreach (City::whereStateId($selectedState->id)->get() as $city)
<option value="{{ $city->id }}">{{ $city->label }}</option>
@endforeach
</select>
```
Again, the only thing non-standard here is the `wire:key` that has been added to the second select. This ensures that when the state changes, the "selectedCity" value will be reset properly.
### Multi-select dropdowns
If you are using a "multiple" select menu, Livewire works as expected. In this example, states will be added to the `$states` array property when they are selected and removed if they are deselected:
```blade
<select wire:model="states" multiple>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
...
</select>
```
## Going deeper
For a more complete documentation on using `wire:model` in the context of HTML forms, visit the [Livewire forms documentation page](/docs/forms).
| |
244057
|
Livewire's `wire:navigate` feature makes page navigation much faster, providing an SPA-like experience for your users.
This page is a simple reference for the `wire:navigate` directive. Be sure to read the [page on Livewire's Navigate feature](/docs/navigate) for more complete documentation.
Below is a simple example of adding `wire:navigate` to links in a nav bar:
```blade
<nav>
<a href="/" wire:navigate>Dashboard</a>
<a href="/posts" wire:navigate>Posts</a>
<a href="/users" wire:navigate>Users</a>
</nav>
```
When any of these links are clicked, Livewire will intercept the click and, instead of allowing the browser to perform a full page visit, Livewire will fetch the page in the background and swap it with the current page (resulting in much faster and smoother page navigation).
## Prefetching pages on hover
By adding the `.hover` modifier, Livewire will pre-fetch a page when a user hovers over a link. This way, the page will have already been downloaded from the server when the user clicks on the link.
```blade
<a href="/" wire:navigate.hover>Dashboard</a>
```
## Going deeper
For more complete documentation on this feature, visit [Livewire's navigate documentation page](/docs/navigate).
| |
244059
|
## Real-time validation
Real-time validation is the term used for when you validate a user's input as they fill out a form rather than waiting for the form submission.
By using `#[Validate]` attributes directly on Livewire properties, any time a network request is sent to update a property's value on the server, the provided validation rules will be applied.
This means to provide a real-time validation experience for your users on a specific input, no extra backend work is required. The only thing that is required is using `wire:model.live` or `wire:model.blur` to instruct Livewire to trigger network requests as the fields are filled out.
In the below example, `wire:model.blur` has been added to the text input. Now, when a user types in the field and then tabs or clicks away from the field, a network request will be triggered with the updated value and the validation rules will run:
```blade
<form wire:submit="save">
<input type="text" wire:model.blur="title">
<!-- -->
</form>
```
If you are using a `rules()` method to declare your validation rules for a property instead of the `#[Validate]` attribute, you can still include a #[Validate] attribute with no parameters to retain the real-time validating behavior:
```php
use Livewire\Attributes\Validate;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
#[Validate] // [tl! highlight]
public $title = '';
public $content = '';
protected function rules()
{
return [
'title' => 'required|min:5',
'content' => 'required|min:5',
];
}
public function save()
{
$validated = $this->validate();
Post::create($validated);
return redirect()->to('/posts');
}
```
Now, in the above example, even though `#[Validate]` is empty, it will tell Livewire to run the fields validation provided by `rules()` everytime the property is updated.
## Customizing error messages
Out-of-the-box, Laravel provides sensible validation messages like "The title field is required." if the `$title` property has the `required` rule attached to it.
However, you may need to customize the language of these error messages to better suite your application and its users.
### Custom attribute names
Sometimes the property you are validating has a name that isn't suited for displaying to users. For example, if you have a database field in your app named `dob` that stands for "Date of birth", you would want to show your users "The date of birth field is required" instead of "The dob field is required".
Livewire allows you to specify an alternative name for a property using the `as: ` parameter:
```php
use Livewire\Attributes\Validate;
#[Validate('required', as: 'date of birth')]
public $dob = '';
```
Now, if the `required` validation rule fails, the error message will state "The date of birth field is required." instead of "The dob field is required.".
### Custom messages
If customizing the property name isn't enough, you can customize the entire validation message using the `message: ` parameter:
```php
use Livewire\Attributes\Validate;
#[Validate('required', message: 'Please fill out your date of birth.')]
public $dob = '';
```
If you have multiple rules to customize the message for, it is recommended that you use entirely separate `#[Validate]` attributes for each, like so:
```php
use Livewire\Attributes\Validate;
#[Validate('required', message: 'Please enter a title.')]
#[Validate('min:5', message: 'Your title is too short.')]
public $title = '';
```
If you want to use the `#[Validate]` attribute's array syntax instead, you can specify custom attributes and messages like so:
```php
use Livewire\Attributes\Validate;
#[Validate([
'titles' => 'required',
'titles.*' => 'required|min:5',
], message: [
'required' => 'The :attribute is missing.',
'titles.required' => 'The :attribute are missing.',
'min' => 'The :attribute is too short.',
], attribute: [
'titles.*' => 'title',
])]
public $titles = [];
```
## Defining a `rules()` method
As an alternative to Livewire's `#[Validate]` attributes, you can define a method in your component called `rules()` and return a list of fields and corresponding validation rules. This can be helpful if you are trying to use run-time syntaxes that aren't supported in PHP Attributes, for example, Laravel rule objects like `Rule::password()`.
These rules will then be applied when you run `$this->validate()` inside the component. You also can define the `messages()` and `validationAttributes()` functions.
Here's an example:
```php
use Livewire\Component;
use App\Models\Post;
use Illuminate\Validation\Rule;
class CreatePost extends Component
{
public $title = '';
public $content = '';
protected function rules() // [tl! highlight:6]
{
return [
'title' => Rule::exists('posts', 'title'),
'content' => 'required|min:3',
];
}
protected function messages() // [tl! highlight:6]
{
return [
'content.required' => 'The :attribute are missing.',
'content.min' => 'The :attribute is too short.',
];
}
protected function validationAttributes() // [tl! highlight:6]
{
return [
'content' => 'description',
];
}
public function save()
{
$this->validate();
Post::create([
'title' => $this->title,
'content' => $this->content,
]);
return redirect()->to('/posts');
}
// ...
}
```
> [!warning] The `rules()` method doesn't validate on data updates
> When defining rules via the `rules()` method, Livewire will ONLY use these validation rules to validate properties when you run `$this->validate()`. This is different than standard `#[Validate]` attributes which are applied every time a field is updated via something like `wire:model`. To apply these validation rules to a property every time it's updated, you can still use `#[Validate]` with no extra parameters.
> [!warning] Don't conflict with Livewire's mechanisms
> While using Livewire's validation utilities, your component should **not** have properties or methods named `rules`, `messages`, `validationAttributes` or `validationCustomValues`, unless you're customizing the validation process. Otherwise, those will conflict with Livewire's mechanisms.
## Using Laravel Rule objects
Laravel `Rule` objects are an extremely powerful way to add advanced validation behavior to your forms.
Here is an example of using Rule objects in conjunction with Livewire's `rules()` method to achieve more sophisticated validation:
```php
<?php
namespace App\Livewire;
use Illuminate\Validation\Rule;
use App\Models\Post;
use Livewire\Form;
class UpdatePost extends Form
{
public ?Post $post;
public $title = '';
public $content = '';
protected function rules()
{
return [
'title' => [
'required',
Rule::unique('posts')->ignore($this->post), // [tl! highlight]
],
'content' => 'required|min:5',
];
}
public function mount()
{
$this->title = $this->post->title;
$this->content = $this->post->content;
}
public function update()
{
$this->validate(); // [tl! highlight]
$this->post->update($this->all());
$this->reset();
}
// ...
}
```
## Manually controlling validation errors
Livewire's validation utilities should handle the most common validation scenarios; however, there are times when you may want full control over the validation messages in your component.
Below are all the available methods for manipulating the validation errors in your Livewire component:
Method | Description
--- | ---
`$this->addError([key], [message])` | Manually add a validation message to the error bag
`$this->resetValidation([?key])` | Reset the validation errors for the provided key, or reset all errors if no key is supplied
`$this->getErrorBag()` | Retrieve the underlying Laravel error bag used in the Livewire component
> [!info] Using `$this->addError()` with Form Objects
> When manually adding errors using `$this->addError` inside of a form object the key will automatically be prefixed with the name of the property the form is assigned to in the parent component. For example, if in your Component you assign the form to a property called `$data`, key will become `data.key`.
| |
244061
|
After a user performs some action — like submitting a form — you may want to redirect them to another page in your application.
Because Livewire requests aren't standard full-page browser requests, standard HTTP redirects won't work. Instead, you need to trigger redirects via JavaScript. Fortunately, Livewire exposes a simple `$this->redirect()` helper method to use within your components. Internally, Livewire will handle the process of redirecting on the frontend.
If you prefer, you can use [Laravel's built-in redirect utilities](https://laravel.com/docs/responses#redirects) within your components as well.
## Basic usage
Below is an example of a `CreatePost` Livewire component that redirects the user to another page after they submit the form to create a post:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class CreatePost extends Component
{
public $title = '';
public $content = '';
public function save()
{
Post::create([
'title' => $this->title,
'content' => $this->content,
]);
$this->redirect('/posts'); // [tl! highlight]
}
public function render()
{
return view('livewire.create-post');
}
}
```
As you can see, when the `save` action is triggered, a redirect will also be triggered to `/posts`. When Livewire receives this response, it will redirect the user to the new URL on the frontend.
## Redirect to Route
In case you want to redirect to a page using its route name you can use the `redirectRoute`.
For example, if you have a page with the route named `'profile'` like this:
```php
Route::get('/user/profile', function () {
// ...
})->name('profile');
```
You can use `redirectRoute` to redirect to that page using the name of the route like so:
```php
$this->redirectRoute('profile');
```
In case you need to pass parameters to the route you may use the second argument of the method `redirectRoute` like so:
```php
$this->redirectRoute('profile', ['id' => 1]);
```
## Redirect to intended
In case you want to redirect the user back to the previous page they were on you can use `redirectIntended`. It accepts an optional default URL as its first argument which is used as a fallback if no previous page can be determined:
```php
$this->redirectIntended('/default/url');
```
## Redirecting to full-page components
Because Livewire uses Laravel's built-in redirection feature, you can use all of the redirection methods available to you in a typical Laravel application.
For example, if you are using a Livewire component as a full-page component for a route like so:
```php
use App\Livewire\ShowPosts;
Route::get('/posts', ShowPosts::class);
```
You can redirect to the component by providing the component name to the `redirect()` method:
```php
public function save()
{
// ...
$this->redirect(ShowPage::class);
}
```
## Flash messages
In addition to allowing you to use Laravel's built-in redirection methods, Livewire also supports Laravel's [session flash data utilities](https://laravel.com/docs/session#flash-data).
To pass flash data along with a redirect, you can use Laravel's `session()->flash()` method like so:
```php
use Livewire\Component;
class UpdatePost extends Component
{
// ...
public function update()
{
// ...
session()->flash('status', 'Post successfully updated.');
$this->redirect('/posts');
}
}
```
Assuming the page being redirected to contain the following Blade snippet, the user will see a "Post successfully updated." message after updating the post:
```blade
@if (session('status'))
<div class="alert alert-success">
{{ session('status') }}
</div>
@endif
```
| |
244065
|
## Basic usage
Showing or hiding content in Livewire is as simple as using one of Blade's conditional directives like `@if`. To enhance this experience for your users, Livewire provides a `wire:transition` directive that allows you to transition conditional elements smoothly in and out of the page.
For example, below is a `ShowPost` component with the ability to toggle viewing comments on and off:
```php
use App\Models\Post;
class ShowPost extends Component
{
public Post $post;
public $showComments = false;
}
```
```blade
<div>
<!-- ... -->
<button wire:click="$set('showComments', true)">Show comments</button>
@if ($showComments)
<div wire:transition> <!-- [tl! highlight] -->
@foreach ($post->comments as $comment)
<!-- ... -->
@endforeach
</div>
@endif
</div>
```
Because `wire:transition` has been added to the `<div>` containing the post's comments, when the "Show comments" button is pressed, `$showComments` will be set to `true` and the comments will "fade" onto the page instead of abruptly appearing.
## Limitations
Currently, `wire:transition` is only supported on a single element inside a Blade conditional like `@if`. It will not work as expected when used in a list of sibling elements. For example, the following will NOT work properly:
```blade
<!-- Warning: The following is code that will not work properly -->
<ul>
@foreach ($post->comments as $comment)
<li wire:transition wire:key="{{ $comment->id }}">{{ $comment->content }}</li>
@endforeach
</ul>
```
If one of the above comment `<li>` elements were to get removed, you would expect Livewire to transition it out. However, because of hurdles with Livewire's underlying "morph" mechanism, this will not be the case. There is currently no way to transition dynamic lists in Livewire using `wire:transition`.
## Default transition style
By default, Livewire applies both an opacity and a scale CSS transition to elements with `wire:transition`. Here's a visual preview:
<div x-data="{ show: false }" x-cloak class="border border-gray-700 rounded-xl p-6 w-full flex justify-between">
<a href="#" x-on:click.prevent="show = ! show" class="py-2.5 outline-none">
Preview transition <span x-text="show ? 'out' : 'in →'">in</span>
</a>
<div class="hey">
<div
x-show="show"
x-transition
class="inline-flex px-16 py-2.5 rounded-[10px] bg-pink-400 text-white uppercase font-medium transition focus-visible:outline-none focus-visible:!ring-1 focus-visible:!ring-white"
style="
background: linear-gradient(109.48deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.1) 100%), #EE5D99;
box-shadow: inset 0px -1px 0px rgba(0, 0, 0, 0.5), inset 0px 1px 0px rgba(255, 255, 255, 0.1);
"
>
</div>
</div>
</div>
The above transition uses the following values for transitioning by default:
Transition in | Transition out
--- | ---
`duration: 150ms` | `duration: 75ms`
`opacity: [0 - 100]` | `opacity: [100 - 0]`
`transform: scale([0.95 - 1])` | `transform: scale([1 - 0.95])`
##
| |
244066
|
Customizing transitions
To customize the CSS Livewire internally uses when transitioning, you can use any combination of the available modifiers:
Modifier | Description
--- | ---
`.in` | Only transition the element "in"
`.out` | Only transition the element "out"
`.duration.[?]ms` | Customize the transition duration in milliseconds
`.duration.[?]s` | Customize the transition duration in seconds
`.delay.[?]ms` | Customize the transition delay in milliseconds
`.delay.[?]s` | Customize the transition delay in seconds
`.opacity` | Only apply the opacity transition
`.scale` | Only apply the scale transition
`.origin.[top\|bottom\|left\|right]` | Customize the scale "origin" used
Below is a list of various transition combinations that may help to better visualize these customizations:
**Fade-only transition**
By default, Livewire both fades and scales the element when transitioning. You can disable scaling and only fade by adding the `.opacity` modifier. This is useful for things like transitioning a full-page overlay, where adding a scale doesn't make sense.
```html
<div wire:transition.opacity>
```
<div x-data="{ show: false }" x-cloak class="border border-gray-700 rounded-xl p-6 w-full flex justify-between">
<a href="#" x-on:click.prevent="show = ! show" class="py-2.5 outline-none">
Preview transition <span x-text="show ? 'out' : 'in →'">in</span>
</a>
<div class="hey">
<div
x-show="show"
x-transition.opacity
class="inline-flex px-16 py-2.5 rounded-[10px] bg-pink-400 text-white uppercase font-medium transition focus-visible:outline-none focus-visible:!ring-1 focus-visible:!ring-white"
style="
background: linear-gradient(109.48deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.1) 100%), #EE5D99;
box-shadow: inset 0px -1px 0px rgba(0, 0, 0, 0.5), inset 0px 1px 0px rgba(255, 255, 255, 0.1);
"
>
...
</div>
</div>
</div>
**Fade-out transition**
A common transition technique is to show an element immediately when transitioning in, and fade its opacity when transitioning out. You'll notice this effect on most native MacOS dropdowns and menus. Therefore it's commonly applied on the web to dropdowns, popovers, and menus.
```html
<div wire:transition.out.opacity.duration.200ms>
```
<div x-data="{ show: false }" x-cloak class="border border-gray-700 rounded-xl p-6 w-full flex justify-between">
<a href="#" x-on:click.prevent="show = ! show" class="py-2.5 outline-none">
Preview transition <span x-text="show ? 'out' : 'in →'">in</span>
</a>
<div class="hey">
<div
x-show="show"
x-transition.out.opacity.duration.200ms
class="inline-flex px-16 py-2.5 rounded-[10px] bg-pink-400 text-white uppercase font-medium transition focus-visible:outline-none focus-visible:!ring-1 focus-visible:!ring-white"
style="
background: linear-gradient(109.48deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.1) 100%), #EE5D99;
box-shadow: inset 0px -1px 0px rgba(0, 0, 0, 0.5), inset 0px 1px 0px rgba(255, 255, 255, 0.1);
"
>
...
</div>
</div>
</div>
**Origin-top transition**
When using Livewire to transition an element such as a dropdown menu, it makes sense to scale in from the top of the menu as the origin, rather than center (Livewire's default). This way the menu feels visually anchored to the element that triggered it.
```html
<div wire:transition.scale.origin.top>
```
<div x-data="{ show: false }" x-cloak class="border border-gray-700 rounded-xl p-6 w-full flex justify-between">
<a href="#" x-on:click.prevent="show = ! show" class="py-2.5 outline-none">
Preview transition <span x-text="show ? 'out' : 'in →'">in</span>
</a>
<div class="hey">
<div
x-show="show"
x-transition.origin.top
class="inline-flex px-16 py-2.5 rounded-[10px] bg-pink-400 text-white uppercase font-medium transition focus-visible:outline-none focus-visible:!ring-1 focus-visible:!ring-white"
style="
background: linear-gradient(109.48deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.1) 100%), #EE5D99;
box-shadow: inset 0px -1px 0px rgba(0, 0, 0, 0.5), inset 0px 1px 0px rgba(255, 255, 255, 0.1);
"
>
...
</div>
</div>
</div>
> [!tip] Livewire uses Alpine transitions behind the scenes
> When using `wire:transition` on an element, Livewire is internally applying Alpine's `x-transition` directive. Therefore you can use most if not all syntaxes you would normally use with `x-transition`. Check out [Alpine's transition documentation](https://alpinejs.dev/directives/transition) for all its capabilities.
| |
244067
|
To begin your Livewire journey, we will create a simple "counter" component and render it in the browser. This example is a great way to experience Livewire for the first time as it demonstrates Livewire's _liveness_ in the simplest way possible.
## Prerequisites
Before we start, make sure you have the following installed:
- Laravel version 10 or later
- PHP version 8.1 or later
## Install Livewire
From the root directory of your Laravel app, run the following [Composer](https://getcomposer.org/) command:
```shell
composer require livewire/livewire
```
> [!warning] Make sure Alpine isn't already installed
> If the application you are using already has AlpineJS installed, you will need to remove it for Livewire to work properly; otherwise, Alpine will be loaded twice and Livewire won't function. For example, if you installed the Laravel Breeze "Blade with Alpine" starter kit, you will need to remove Alpine from `resources/js/app.js`.
## Create a Livewire component
Livewire provides a convenient Artisan command to generate new components quickly. Run the following command to make a new `Counter` component:
```shell
php artisan make:livewire counter
```
This command will generate two new files in your project:
* `app/Livewire/Counter.php`
* `resources/views/livewire/counter.blade.php`
## Writing the class
Open `app/Livewire/Counter.php` and replace its contents with the following:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class Counter extends Component
{
public $count = 1;
public function increment()
{
$this->count++;
}
public function decrement()
{
$this->count--;
}
public function render()
{
return view('livewire.counter');
}
}
```
Here's a brief explanation of the code above:
- `public $count = 1;` — Declares a public property named `$count` with an initial value of `1`.
- `public function increment()` — Declares a public method named `increment()` that increments the `$count` property each time it's called. Public methods like this can be triggered from the browser in a variety of ways, including when a user clicks a button.
- `public function render()` — Declares a `render()` method that returns a Blade view. This Blade view will contain the HTML template for our component.
## Writing the view
Open the `resources/views/livewire/counter.blade.php` file and replace its content with the following:
```blade
<div>
<h1>{{ $count }}</h1>
<button wire:click="increment">+</button>
<button wire:click="decrement">-</button>
</div>
```
This code will display the value of the `$count` property and two buttons that increment and decrement the `$count` property, respectively.
> [!warning] Livewire components MUST have a single root element
> In order for Livewire to work, components must have just **one** single element as its root. If multiple root elements are detected, an exception is thrown. It is recommended to use a `<div>` element as in the example. HTML comments count as separate elements and should be put inside the root element.
> When rendering [full-page components](/docs/components#full-page-components), named slots for the layout file may be put outside the root element. These are removed before the component is rendered.
## Register a route for the component
Open the `routes/web.php` file in your Laravel application and add the following code:
```php
use App\Livewire\Counter;
Route::get('/counter', Counter::class);
```
Now, our _counter_ component is assigned to the `/counter` route, so that when a user visits the `/counter` endpoint in your application, this component will be rendered by the browser.
## Create a template layout
Before you can visit `/counter` in the browser, we need an HTML layout for our component to render inside. By default, Livewire will automatically look for a layout file named: `resources/views/components/layouts/app.blade.php`
You may create this file if it doesn't already exist by running the following command:
```shell
php artisan livewire:layout
```
This command will generate a file called `resources/views/components/layouts/app.blade.php` with the following contents:
```blade
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $title ?? 'Page Title' }}</title>
</head>
<body>
{{ $slot }}
</body>
</html>
```
The _counter_ component will be rendered in place of the `$slot` variable in the template above.
You may have noticed there is no JavaScript or CSS assets provided by Livewire. That is because Livewire 3 and above automatically injects any frontend assets it needs.
## Test it out
With our component class and templates in place, our component is ready to test!
Visit `/counter` in your browser, and you should see a number displayed on the screen with two buttons to increment and decrement the number.
After clicking one of the buttons, you will notice that the count updates in real time, without the page reloading. This is the magic of Livewire: dynamic frontend applications written entirely in PHP.
We've barely scratched the surface of what Livewire is capable of. Keep reading the documentation to see everything Livewire has to offer.
| |
244068
|
Components are the building blocks of your Livewire application. They combine state and behavior to create reusable pieces of UI for your front end. Here, we'll cover the basics of creating and rendering components.
## Creating components
A Livewire component is simply a PHP class that extends `Livewire\Component`. You can create component files by hand or use the following Artisan command:
```shell
php artisan make:livewire CreatePost
```
If you prefer kebab-cased names, you can use them as well:
```shell
php artisan make:livewire create-post
```
After running this command, Livewire will create two new files in your application. The first will be the component's class: `app/Livewire/CreatePost.php`
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public function render()
{
return view('livewire.create-post');
}
}
```
The second will be the component's Blade view: `resources/views/livewire/create-post.blade.php`
```blade
<div>
{{-- ... --}}
</div>
```
You may use namespace syntax or dot-notation to create your components in sub-directories. For example, the following commands will create a `CreatePost` component in the `Posts` sub-directory:
```shell
php artisan make:livewire Posts\\CreatePost
php artisan make:livewire posts.create-post
```
### Inline components
If your component is fairly small, you may want to create an _inline_ component. Inline components are single-file Livewire components whose view template is contained directly in the `render()` method rather than a separate file:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public function render()
{
return <<<'HTML' // [tl! highlight:4]
<div>
{{-- Your Blade template goes here... --}}
</div>
HTML;
}
}
```
You can create inline components by adding the `--inline` flag to the `make:livewire` command:
```shell
php artisan make:livewire CreatePost --inline
```
### Omitting the render method
To reduce boilerplate in your components, you can omit the `render()` method entirely and Livewire will use its own underlying `render()` method, which returns a view with the conventional name corresponding to your component:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
//
}
```
If the component above is rendered on a page, Livewire will automatically determine it should be rendered using the `livewire.create-post` template.
### Customizing component stubs
You can customize the files (or _stubs_) Livewire uses to generate new components by running the following command:
```shell
php artisan livewire:stubs
```
This will create four new files in your application:
* `stubs/livewire.stub` — used for generating new components
* `stubs/livewire.inline.stub` — used for generating _inline_ components
* `stubs/livewire.test.stub` — used for generating test files
* `stubs/livewire.view.stub` — used for generating component views
Even though these files live in your application, you can still use the `make:livewire` Artisan command and Livewire will automatically use your custom stubs when generating files.
## Setting properties
Livewire components have properties that store data and can be easily accessed within the component's class and Blade view. This section discusses the basics of adding a property to a component and using it in your application.
To add a property to a Livewire component, declare a public property in your component class. For example, let's create a `$title` property in the `CreatePost` component:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
class CreatePost extends Component
{
public $title = 'Post title...';
public function render()
{
return view('livewire.create-post');
}
}
```
### Accessing properties in the view
Component properties are automatically made available to the component's Blade view. You can reference it using standard Blade syntax. Here we'll display the value of the `$title` property:
```blade
<div>
<h1>Title: "{{ $title }}"</h1>
</div>
```
The rendered output of this component would be:
```blade
<div>
<h1>Title: "Post title..."</h1>
</div>
```
### Sharing additional data with the view
In addition to accessing properties from the view, you can explicitly pass data to the view from the `render()` method, like you might typically do from a controller. This can be useful when you want to pass additional data without first storing it as a property—because properties have [specific performance and security implications](/docs/properties#security-concerns).
To pass data to the view in the `render()` method, you can use the `with()` method on the view instance. For example, let's say you want to pass the post author's name to the view. In this case, the post's author is the currently authenticated user:
```php
<?php
namespace App\Livewire;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;
class CreatePost extends Component
{
public $title;
public function render()
{
return view('livewire.create-post')->with([
'author' => Auth::user()->name,
]);
}
}
```
Now you may access the `$author` property from the component's Blade view:
```blade
<div>
<h1>Title: {{ $title }}</h1>
<span>Author: {{ $author }}</span>
</div>
```
### Adding `wire:key` to `@foreach` loops
When looping through data in a Livewire template using `@foreach`, you must add a unique `wire:key` attribute to the root element rendered by the loop.
Without a `wire:key` attribute present within a Blade loop, Livewire won't be able to properly match old elements to their new positions when the loop changes. This can cause many hard to diagnose issues in your application.
For example, if you are looping through an array of posts, you may set the `wire:key` attribute to the post's ID:
```blade
<div>
@foreach ($posts as $post)
<div wire:key="{{ $post->id }}"> <!-- [tl! highlight] -->
<!-- ... -->
</div>
@endforeach
</div>
```
If you are looping through an array that is rendering Livewire components you may set the key as a component attribute `:key()` or pass the key as a third argument when using the `@livewire` directive.
```blade
<div>
@foreach ($posts as $post)
<livewire:post-item :$post :key="$post->id">
@livewire(PostItem::class, ['post' => $post], key($post->id))
@endforeach
</div>
```
### Binding inputs to properties
One of Livewire's most powerful features is "data binding": the ability to automatically keep properties in-sync with form inputs on the page.
Let's bind the `$title` property from the `CreatePost` component to a text input using the `wire:model` directive:
```blade
<form>
<label for="title">Title:</label>
<input type="text" id="title" wire:model="title"> <!-- [tl! highlight] -->
</form>
```
Any changes made to the text input will be automatically synchronized with the `$title` property in your Livewire component.
> [!warning] "Why isn't my component live updating as I type?"
> If you tried this in your browser and are confused why the title isn't automatically updating, it's because Livewire only updates a component when an "action" is submitted—like pressing a submit button—not when a user types into a field. This cuts down on network requests and improves performance. To enable "live" updating as a user types, you can use `wire:model.live` instead. [Learn more about data binding](/docs/properties#data-binding).
Livewire properties are extremely powerful and are an important concept to understand. For more information, check out the [Livewire properties documentation](/docs/properties).
## Calling act
| |
244070
|
omponents
Livewire allows you to assign components directly to a route in your Laravel application. These are called "full-page components". You can use them to build standalone pages with logic and views, fully encapsulated within a Livewire component.
To create a full-page component, define a route in your `routes/web.php` file and use the `Route::get()` method to map the component directly to a specific URL. For example, let's imagine you want to render the `CreatePost` component at the dedicated route: `/posts/create`.
You can accomplish this by adding the following line to your `routes/web.php` file:
```php
use App\Livewire\CreatePost;
Route::get('/posts/create', CreatePost::class);
```
Now, when you visit the `/posts/create` path in your browser, the `CreatePost` component will be rendered as a full-page component.
### Layout files
Remember that full-page components will use your application's layout, typically defined in the `resources/views/components/layouts/app.blade.php` file.
You may create this file if it doesn't already exist by running the following command:
```shell
php artisan livewire:layout
```
This command will generate a file called `resources/views/components/layouts/app.blade.php`.
Ensure you have created a Blade file at this location and included a `{{ $slot }}` placeholder:
```blade
<!-- resources/views/components/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $title ?? 'Page Title' }}</title>
</head>
<body>
{{ $slot }}
</body>
</html>
```
#### Global layout configuration
To use a custom layout across all your components, you can set the `layout` key in `config/livewire.php` to the path of your custom layout, relative to `resources/views`. For example:
```php
'layout' => 'layouts.app',
```
With the above configuration, Livewire will render full-page components inside the layout file: `resources/views/layouts/app.blade.php`.
#### Per-component layout configuration
To use a different layout for a specific component, you can place Livewire's `#[Layout]` attribute above the component's `render()` method, passing it the relative view path of your custom layout:
```php
<?php
namespace App\Livewire;
use Livewire\Attributes\Layout;
use Livewire\Component;
class CreatePost extends Component
{
// ...
#[Layout('layouts.app')] // [tl! highlight]
public function render()
{
return view('livewire.create-post');
}
}
```
Or if you prefer, you can use this attribute above the class declaration:
```php
<?php
namespace App\Livewire;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('layouts.app')] // [tl! highlight]
class CreatePost extends Component
{
// ...
}
```
PHP attributes only support literal values. If you need to pass a dynamic value, or prefer this alternative syntax, you can use the fluent `->layout()` method in the component's `render()` method:
```php
public function render()
{
return view('livewire.create-post')
->layout('layouts.app'); // [tl! highlight]
}
```
Alternatively, Livewire supports using traditional Blade layout files with `@extends`.
Given the following layout file:
```blade
<body>
@yield('content')
</body>
```
You can configure Livewire to reference it using `->extends()` instead of `->layout()`:
```php
public function render()
{
return view('livewire.show-posts')
->extends('layouts.app'); // [tl! highlight]
}
```
If you need to configure the `@section` for the component to use, you can configure that as well with the `->section()` method:
```php
public function render()
{
return view('livewire.show-posts')
->extends('layouts.app')
->section('body'); // [tl! highlight]
}
```
### Setting the page title
Assigning unique page titles to each page in your application is helpful for both users and search engines.
To set a custom page title for a full-page component, first, make sure your layout file includes a dynamic title:
```blade
<head>
<title>{{ $title ?? 'Page Title' }}</title>
</head>
```
Next, above your Livewire component's `render()` method, add the `#[Title]` attribute and pass it your page title:
```php
<?php
namespace App\Livewire;
use Livewire\Attributes\Title;
use Livewire\Component;
class CreatePost extends Component
{
// ...
#[Title('Create Post')] // [tl! highlight]
public function render()
{
return view('livewire.create-post');
}
}
```
This will set the page title for the `CreatePost` Livewire component. In this example, the page title will be "Create Post" when the component is rendered.
If you prefer, you can use this attribute above the class declaration:
```php
<?php
namespace App\Livewire;
use Livewire\Attributes\Title;
use Livewire\Component;
#[Title('Create Post')] // [tl! highlight]
class CreatePost extends Component
{
// ...
}
```
If you need to pass a dynamic title, such as a title that uses a component property, you can use the `->title()` fluent method in the component's `render()` method:
```php
public function render()
{
return view('livewire.create-post')
->title('Create Post'); // [tl! highlight]
}
```
### Setting additional layout file slots
If your [layout file](#layout-files) has any named slots in addition to `$slot`, you can set their content in your Blade view by defining `<x-slot>`s outside your root element. For example, if you want to be able to set the page language for each component individually, you can add a dynamic `$lang` slot into the opening HTML tag in your layout file:
```blade
<!-- resources/views/components/layouts/app.blade.php -->
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', $lang ?? app()->getLocale()) }}"> <!-- [tl! highlight] -->
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ $title ?? 'Page Title' }}</title>
</head>
<body>
{{ $slot }}
</body>
</html>
```
Then, in your component view, define an `<x-slot>` element outside the root element:
```blade
<x-slot:lang>fr</x-slot> // This component is in French <!-- [tl! highlight] -->
<div>
// French content goes here...
</div>
```
### Accessing route parameters
When working with full-page components, you may need to access route parameters within your Livewire component.
To demonstrate, first, define a route with a parameter in your `routes/web.php` file:
```php
use App\Livewire\ShowPost;
Route::get('/posts/{id}', ShowPost::class);
```
Here, we've defined a route with an `id` parameter which represents a post's ID.
Next, update your Livewire component to accept the route parameter in the `mount()` method:
```php
<?php
namespace App\Livewire;
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public Post $post;
public function mount($id) // [tl! highlight]
{
$this->post = Post::findOrFail($id);
}
public function render()
{
return view('livewire.show-post');
}
}
```
In this example, because the parameter name `$id` matches the route parameter `{id}`, if the `/posts/1` URL is visited, Livewire will pass the value of "1" as `$id`.
### Using rout
| |
244071
|
e model binding
Laravel's route model binding allows you to automatically resolve Eloquent models from route parameters.
After defining a route with a model parameter in your `routes/web.php` file:
```php
use App\Livewire\ShowPost;
Route::get('/posts/{post}', ShowPost::class);
```
You can now accept the route model parameter through the `mount()` method of your component:
```php
<?php
namespace App\Livewire;
use App\Models\Post;
use Livewire\Component;
class ShowPost extends Component
{
public Post $post;
public function mount(Post $post) // [tl! highlight]
{
$this->post = $post;
}
public function render()
{
return view('livewire.show-post');
}
}
```
Livewire knows to use "route model binding" because the `Post` type-hint is prepended to the `$post` parameter in `mount()`.
Like before, you can reduce boilerplate by omitting the `mount()` method:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use App\Models\Post;
class ShowPost extends Component
{
public Post $post; // [tl! highlight]
public function render()
{
return view('livewire.show-post');
}
}
```
The `$post` property will automatically be assigned to the model bound via the route's `{post}` parameter.
### Modifying the response
In some scenarios, you might want to modify the response and set a custom response header. You can hook into the response object by calling the `response()` method on the view and use a closure to modify the response object:
```php
<?php
namespace App\Livewire;
use Livewire\Component;
use Illuminate\Http\Response;
class ShowPost extends Component
{
public function render()
{
return view('livewire.show-post')
->response(function(Response $response) {
$response->header('X-Custom-Header', true);
});
}
}
```
## Using JavaScript
There are many instances where the built-in Livewire and Alpine utilities aren't enough to accomplish your goals inside your Livewire components.
Fortunately, Livewire provides many useful extension points and utilities to interact with bespoke JavaScript. You can learn from the exhaustive reference on [the JavaScript documentation page](/docs/javascript). But for now, here are a few useful ways to use your own JavaScript inside your Livewire components.
### Executing scripts
Livewire provides a helpful `@script` directive that, when wrapping a `<script>` element, will execute the given JavaScript when your component is initialized on the page.
Here is an example of a simple `@script` that uses JavaScript's `setInterval()` to refresh your component every two seconds:
```blade
@script
<script>
setInterval(() => {
$wire.$refresh()
}, 2000)
</script>
@endscript
```
You'll notice we are using an object called `$wire` inside the `<script>` to control the component. Livewire automatically makes this object available inside any `@script`s. If you're unfamiliar with `$wire`, you can learn more about `$wire` in the following documentation:
* [Accessing properties from JavaScript](/docs/properties#accessing-properties-from-javascript)
* [Calling Livewire actions from JS/Alpine](/docs/actions#calling-actions-from-alpine)
* [The `$wire` object reference](/docs/javascript#the-wire-object)
### Loading assets
In addition to one-off `@script`s, Livewire provides a helpful `@assets` utility to easily load any script/style dependencies on the page.
It also ensures that the provided assets are loaded only once per browser page, unlike `@script`, which executes every time a new instance of that Livewire component is initialized.
Here is an example of using `@assets` to load a date picker library called [Pikaday](https://github.com/Pikaday/Pikaday) and initialize it inside your component using `@script`:
```blade
<div>
<input type="text" data-picker>
</div>
@assets
<script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js" defer></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
@endassets
@script
<script>
new Pikaday({ field: $wire.$el.querySelector('[data-picker]') });
</script>
@endscript
```
> [!info] Using `@verbatim@script@endverbatim` and `@verbatim@assets@endverbatim` inside Blade components
> If you are using [Blade components](https://laravel.com/docs/blade#components) to extract parts of your markup, you can use `@verbatim@script@endverbatim` and `@verbatim@assets@endverbatim` inside them as well; even if there are multiple Blade components inside the same Livewire component. However, `@verbatim@script@endverbatim` and `@verbatim@assets@endverbatim` are currently only supported in the context of a Livewire component, meaning if you use the given Blade component outside of Livewire entirely, those scripts and assets won't be loaded on the page.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.