- Laravel Search Box
- Laravel Search Query
- Laravel Search In A Table
- Laravel Search Array
- Laravel Search Ajax Video
- Configuration
- Retrieving Files
- Storing Files
Introduction
Introduction Status Guide. Setup Middleware Schemes Providers. Laravel JWT Laravel Passport Laravel Sanctum. Laravel 5.2 Oracle User Provider When using oracle, we may encounter a problem on authentication because oracle queries are case sensitive by default. By using this oracle user provider, we will now be able to avoid user issues when logging in and doing a forgot password failure because of case sensitive search.
Laravel provides a powerful filesystem abstraction thanks to the wonderful Flysystem PHP package by Frank de Jonge. The Laravel Flysystem integration provides simple drivers for working with local filesystems, SFTP, and Amazon S3. Even better, it's amazingly simple to switch between these storage options between your local development machine and production server as the API remains the same for each system.
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.
{tip} You may configure as many disks as you like and may even have multiple disks that use the same driver.
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
:
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.
To create the symbolic link, you may use the storage:link
Artisan command:
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:
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:
Driver Prerequisites
Composer Packages
Before using the S3 or SFTP drivers, you will need to install the appropriate package via the Composer package manager:
- Amazon S3:
composer require league/flysystem-aws-s3-v3 '~1.0'
- SFTP:
composer require league/flysystem-sftp '~1.0'
In addition, you may choose to install a cached adapter for increased performance:
- CachedAdapter:
composer require league/flysystem-cached-adapter '~1.0'
S3 Driver Configuration
The S3 driver configuration information is located in your config/filesystems.php
configuration file. This file contains an example configuration array for an S3 driver. You are free to modify this array with your own S3 configuration and credentials. For convenience, these environment variables match the naming convention used by the AWS CLI.
FTP Driver Configuration
Laravel's Flysystem integrations work great with FTP; however, a sample configuration is not included with the framework's default filesystems.php
configuration file. If you need to configure an FTP filesystem, you may use the configuration example below:
SFTP Driver Configuration
Laravel's Flysystem integrations work great with SFTP; however, a sample configuration is not included with the framework's default filesystems.php
configuration file. If you need to configure an SFTP filesystem, you may use the configuration example below:
Caching
To enable caching for a given disk, you may add a cache
directive to the disk's configuration options. The cache
option should be an array of caching options containing the disk
name, the expire
time in seconds, and the cache prefix
:
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:
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:
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:
The exists
method may be used to determine if a file exists on the disk:
The missing
method may be used to determine if a file is missing from the disk:
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:
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:
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 at public/storage
which points to the storage/app/public
directory.
{note} 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.
Temporary URLs
Using the temporaryUrl
method, you may create temporary URLs to files stored using the s3
driver. This method accepts a path and a DateTime
instance specifying when the URL should expire:
If you need to specify additional S3 request parameters, you may pass the array of request parameters as the third argument to the temporaryUrl
method:
URL Host Customization
If you would like to pre-define the host for URLs generated using the Storage
facade, you may add a url
option to the disk's configuration array:
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:
The lastModified
method returns the UNIX timestamp of the last time the file was modified:
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:
Storing Files
The put
method may be used to store file contents on a disk. You may also pass a PHP resource
to the put
method, which will use Flysystem's underlying stream support. Remember, all file paths should be specified relative to the 'root' location configured for the disk:
Laravel Search Box
Automatic Streaming
Streaming files to storage offers significantly reduced memory usage. If you would like Laravel to automatically manage streaming a given file to your storage location, you may use the putFile
or putFileAs
method. This method accepts either an IlluminateHttpFile
or IlluminateHttpUploadedFile
instance and will automatically stream the file to your desired location:
There are a few important things to note about the putFile
method. Note that we only specified a directory name and not a filename. By default, the putFile
method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the putFile
method so you can store the path, including the generated filename, in your database.
The putFile
and putFileAs
methods also accept an argument to specify the 'visibility' of the stored file. This is particularly useful if you are storing the file on a cloud disk such as Amazon S3 and would like the file to be publicly accessible via generated URLs:
Prepending & Appending To Files
The prepend
and append
methods allow you to write to the beginning or end of a file:
Copying & Moving Files
The copy
method may be used to copy an existing file to a new location on the disk, while the move
method may be used to rename or move an existing file to a new location:
File Uploads
In web applications, one of the most common use-cases for storing files is storing user uploaded files such as photos and documents. Laravel makes it very easy to store uploaded files using the store
method on an uploaded file instance. Call the store
method with the path at which you wish to store the uploaded file:
There are a few important things to note about this example. Note that we only specified a directory name, not a filename. By default, the store
method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the store
method so you can store the path, including the generated filename, in your database.
You may also call the putFile
method on the Storage
facade to perform the same file storage operation as the example above:
Specifying A File Name
If you do not want a filename to be automatically assigned to your stored file, you may use the storeAs
method, which receives the path, the filename, and the (optional) disk as its arguments:
You may also use the putFileAs
method on the Storage
facade, which will perform the same file storage operation as the example above:
{note} Unprintable and invalid unicode characters will automatically be removed from file paths. Therefore, you may wish to sanitize your file paths before passing them to Laravel's file storage methods. File paths are normalized using the LeagueFlysystemUtil::normalizePath
method.
Specifying A Disk
By default, this uploaded file's store
method will use your default disk. If you would like to specify another disk, pass the disk name as the second argument to the store
method:
If you are using the storeAs
method, you may pass the disk name as the third argument to the method:
Other Uploaded File Information
If you would like to get the original name of the uploaded file, you may do so using the getClientOriginalName
method:
The extension
method may be used to get the file extension of the uploaded file:
File Visibility
In Laravel's Flysystem integration, 'visibility' is an abstraction of file permissions across multiple platforms. Files may either be declared public
or private
. When a file is declared public
, you are indicating that the file should generally be accessible to others. For example, when using the S3 driver, you may retrieve URLs for public
files.
You can set the visibility when writing the file via the put
method:
If the file has already been stored, its visibility can be retrieved and set via the getVisibility
and setVisibility
methods:
When interacting with uploaded files, you may use the storePublicly
and storePubliclyAs
methods to store the uploaded file with public
visibility:
Local Files & Visibility
When using the local
driver, public
visibility translates to 0755
permissions for directories and 0644
permissions for files. You can modify the permissions mappings in your application's filesystems
configuration file:
Deleting Files
The delete
method accepts a single filename or an array of files to delete:
If necessary, you may specify the disk that the file should be deleted from:
Directories
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:
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:
Create A Directory
The makeDirectory
method will create the given directory, including any needed subdirectories:
Delete A Directory
Finally, the deleteDirectory
method may be used to remove a directory and all of its files:
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:
Next, you can register the driver within the boot
method of one of your application's service providers. To accomplish this, you should use the extend
method of the Storage
facade:
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 LeagueFlysystemFilesystem
. 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.
- Installation
- Configuration
- Indexing
- Searching
Introduction
Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.
Currently, Scout ships with Algolia and MeiliSearch drivers; however, writing custom drivers is simple and you are free to extend Scout with your own search implementations.
Installation
First, install Scout via the Composer package manager:
After installing Scout, you should publish the Scout configuration file using the vendor:publish
Artisan command. This command will publish the scout.php
configuration file to your application's config
directory:
Finally, add the LaravelScoutSearchable
trait to the model you would like to make searchable. This trait will register a model observer that will automatically keep the model in sync with your search driver:
Driver Prerequisites
Algolia
When using the Algolia driver, you should configure your Algolia id
and secret
credentials in your config/scout.php
configuration file. Once your credentials have been configured, you will also need to install the Algolia PHP SDK via the Composer package manager:
MeiliSearch
When using the MeiliSearch driver you will need to install the MeiliSearch PHP SDK via the Composer package manager:
Then, set the SCOUT_DRIVER
environment variable as well as your MeiliSearch host
and key
credentials within your application's .env
file:
For more information regarding MeiliSearch, please consult the MeiliSearch documentation.
{tip} If you aren't sure how to install MeiliSearch on your local machine, you may use Laravel Sail, Laravel's officially supported Docker development environment.
Queueing
While not strictly required to use Scout, you should strongly consider configuring a queue driver before using the library. Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface.
Once you have configured a queue driver, set the value of the queue
option in your config/scout.php
configuration file to true
:
Configuration
Configuring Model Indexes
Each Eloquent model is synced with a given search 'index', which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. By default, each model will be persisted to an index matching the model's typical 'table' name. Typically, this is the plural form of the model name; however, you are free to customize the model's index by overriding the searchableAs
method on the model:
Configuring Searchable Data
By default, the entire toArray
form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray
method on the model:
Configuring The Model ID
By default, Scout will use the primary key of the model as model's unique ID / key that is stored in the search index. If you need to customize this behavior, you may override the getScoutKey
and the getScoutKeyName
methods on the model:
Identifying Users
Scout also allows you to auto identify users when using Algolia. Associating the authenticated user with search operations may be helpful when viewing your search analytics within Algolia's dashboard. You can enable user identification by defining a SCOUT_IDENTIFY
environment variable as true
in your application's .env
file:
Enabling this feature this will also pass the request's IP address and your authenticated user's primary identifier to Algolia so this data is associated with any search request that is made by the user.
Indexing
Batch Import
Laravel Search Query
If you are installing Scout into an existing project, you may already have database records you need to import into your indexes. Scout provides a scout:import
Artisan command that you may use to import all of your existing records into your search indexes:
The flush
command may be used to remove all of a model's records from your search indexes:
Modifying The Import Query
If you would like to modify the query that is used to retrieve all of your models for batch importing, you may define a makeAllSearchableUsing
method on your model. This is a great place to add any eager relationship loading that may be necessary before importing your models:
Adding Records
Once you have added the LaravelScoutSearchable
trait to a model, all you need to do is save
or create
a model instance and it will automatically be added to your search index. If you have configured Scout to use queues this operation will be performed in the background by your queue worker:
Adding Records Via Query
If you would like to add a collection of models to your search index via an Eloquent query, you may chain the searchable
method onto the Eloquent query. The searchable
method will chunk the results of the query and add the records to your search index. Again, if you have configured Scout to use queues, all of the chunks will be imported in the background by your queue workers:
You may also call the searchable
method on an Eloquent relationship instance:
Or, if you already have a collection of Eloquent models in memory, you may call the searchable
method on the collection instance to add the model instances to their corresponding index:
Laravel Search In A Table
{tip} The searchable
method can be considered an 'upsert' operation. In other words, if the model record is already in your index, it will be updated. If it does not exist in the search index, it will be added to the index.
Updating Records
To update a searchable model, you only need to update the model instance's properties and save
the model to your database. Scout will automatically persist the changes to your search index:
You may also invoke the searchable
method on an Eloquent query instance to update a collection of models. If the models do not exist in your search index, they will be created:
If you would like to update the search index records for all of the models in a relationship, you may invoke the searchable
on the relationship instance:
Or, if you already have a collection of Eloquent models in memory, you may call the searchable
method on the collection instance to update the model instances in their corresponding index:
Removing Records
To remove a record from your index you may simply delete
the model from the database. This may be done even if you are using soft deleted models:
If you do not want to retrieve the model before deleting the record, you may use the unsearchable
method on an Eloquent query instance:
If you would like to remove the search index records for all of the models in a relationship, you may invoke the unsearchable
on the relationship instance:
Or, if you already have a collection of Eloquent models in memory, you may call the unsearchable
method on the collection instance to remove the model instances from their corresponding index:
Pausing Indexing
Sometimes you may need to perform a batch of Eloquent operations on a model without syncing the model data to your search index. You may do this using the withoutSyncingToSearch
method. This method accepts a single closure which will be immediately executed. Any model operations that occur within the closure will not be synced to the model's index:
Conditionally Searchable Model Instances
Sometimes you may need to only make a model searchable under certain conditions. For example, imagine you have AppModelsPost
model that may be in one of two states: 'draft' and 'published'. You may only want to allow 'published' posts to be searchable. To accomplish this, you may define a shouldBeSearchable
method on your model:
The shouldBeSearchable
method is only applied when manipulating models through the save
and create
methods, queries, or relationships. Directly making models or collections searchable using the searchable
method will override the result of the shouldBeSearchable
method.
Searching
You may begin searching a model using the search
method. The search method accepts a single string that will be used to search your models. You should then chain the get
method onto the search query to retrieve the Eloquent models that match the given search query:
Since Scout searches return a collection of Eloquent models, you may even return the results directly from a route or controller and they will automatically be converted to JSON:
If you would like to get the raw search results before they are converted to Eloquent models, you may use the raw
method:
Custom Indexes
Search queries will typically be performed on the index specified by the model's searchableAs
method. However, you may use the within
method to specify a custom index that should be searched instead:
Where Clauses
Scout allows you to add simple 'where' clauses to your search queries. Currently, these clauses only support basic numeric equality checks and are primarily useful for scoping search queries by an owner ID. Since a search index is not a relational database, more advanced 'where' clauses are not currently supported:
Pagination
In addition to retrieving a collection of models, you may paginate your search results using the paginate
method. This method will return an IlluminatePaginationLengthAwarePaginator
instance just as if you had paginated a traditional Eloquent query:
You may specify how many models to retrieve per page by passing the amount as the first argument to the paginate
method:
Once you have retrieved the results, you may display the results and render the page links using Blade just as if you had paginated a traditional Eloquent query:
Of course, if you would like to retrieve the pagination results as JSON, you may return the paginator instance directly from a route or controller:
Soft Deleting
If your indexed models are soft deleting and you need to search your soft deleted models, set the soft_delete
option of the config/scout.php
configuration file to true
:
When this configuration option is true
, Scout will not remove soft deleted models from the search index. Instead, it will set a hidden __soft_deleted
attribute on the indexed record. Then, you may use the withTrashed
or onlyTrashed
methods to retrieve the soft deleted records when searching:
{tip} When a soft deleted model is permanently deleted using forceDelete
, Scout will remove it from the search index automatically.
Customizing Engine Searches
If you need to perform advanced customization of the search behavior of an engine you may pass a closure as the second argument to the search
method. For example, you could use this callback to add geo-location data to your search options before the search query is passed to Algolia:
Custom Engines
Writing The Engine
If one of the built-in Scout search engines doesn't fit your needs, you may write your own custom engine and register it with Scout. Your engine should extend the LaravelScoutEnginesEngine
abstract class. This abstract class contains eight methods your custom engine must implement:
Caching
To enable caching for a given disk, you may add a cache
directive to the disk's configuration options. The cache
option should be an array of caching options containing the disk
name, the expire
time in seconds, and the cache prefix
:
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:
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:
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:
The exists
method may be used to determine if a file exists on the disk:
The missing
method may be used to determine if a file is missing from the disk:
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:
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:
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 at public/storage
which points to the storage/app/public
directory.
{note} 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.
Temporary URLs
Using the temporaryUrl
method, you may create temporary URLs to files stored using the s3
driver. This method accepts a path and a DateTime
instance specifying when the URL should expire:
If you need to specify additional S3 request parameters, you may pass the array of request parameters as the third argument to the temporaryUrl
method:
URL Host Customization
If you would like to pre-define the host for URLs generated using the Storage
facade, you may add a url
option to the disk's configuration array:
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:
The lastModified
method returns the UNIX timestamp of the last time the file was modified:
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:
Storing Files
The put
method may be used to store file contents on a disk. You may also pass a PHP resource
to the put
method, which will use Flysystem's underlying stream support. Remember, all file paths should be specified relative to the 'root' location configured for the disk:
Laravel Search Box
Automatic Streaming
Streaming files to storage offers significantly reduced memory usage. If you would like Laravel to automatically manage streaming a given file to your storage location, you may use the putFile
or putFileAs
method. This method accepts either an IlluminateHttpFile
or IlluminateHttpUploadedFile
instance and will automatically stream the file to your desired location:
There are a few important things to note about the putFile
method. Note that we only specified a directory name and not a filename. By default, the putFile
method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the putFile
method so you can store the path, including the generated filename, in your database.
The putFile
and putFileAs
methods also accept an argument to specify the 'visibility' of the stored file. This is particularly useful if you are storing the file on a cloud disk such as Amazon S3 and would like the file to be publicly accessible via generated URLs:
Prepending & Appending To Files
The prepend
and append
methods allow you to write to the beginning or end of a file:
Copying & Moving Files
The copy
method may be used to copy an existing file to a new location on the disk, while the move
method may be used to rename or move an existing file to a new location:
File Uploads
In web applications, one of the most common use-cases for storing files is storing user uploaded files such as photos and documents. Laravel makes it very easy to store uploaded files using the store
method on an uploaded file instance. Call the store
method with the path at which you wish to store the uploaded file:
There are a few important things to note about this example. Note that we only specified a directory name, not a filename. By default, the store
method will generate a unique ID to serve as the filename. The file's extension will be determined by examining the file's MIME type. The path to the file will be returned by the store
method so you can store the path, including the generated filename, in your database.
You may also call the putFile
method on the Storage
facade to perform the same file storage operation as the example above:
Specifying A File Name
If you do not want a filename to be automatically assigned to your stored file, you may use the storeAs
method, which receives the path, the filename, and the (optional) disk as its arguments:
You may also use the putFileAs
method on the Storage
facade, which will perform the same file storage operation as the example above:
{note} Unprintable and invalid unicode characters will automatically be removed from file paths. Therefore, you may wish to sanitize your file paths before passing them to Laravel's file storage methods. File paths are normalized using the LeagueFlysystemUtil::normalizePath
method.
Specifying A Disk
By default, this uploaded file's store
method will use your default disk. If you would like to specify another disk, pass the disk name as the second argument to the store
method:
If you are using the storeAs
method, you may pass the disk name as the third argument to the method:
Other Uploaded File Information
If you would like to get the original name of the uploaded file, you may do so using the getClientOriginalName
method:
The extension
method may be used to get the file extension of the uploaded file:
File Visibility
In Laravel's Flysystem integration, 'visibility' is an abstraction of file permissions across multiple platforms. Files may either be declared public
or private
. When a file is declared public
, you are indicating that the file should generally be accessible to others. For example, when using the S3 driver, you may retrieve URLs for public
files.
You can set the visibility when writing the file via the put
method:
If the file has already been stored, its visibility can be retrieved and set via the getVisibility
and setVisibility
methods:
When interacting with uploaded files, you may use the storePublicly
and storePubliclyAs
methods to store the uploaded file with public
visibility:
Local Files & Visibility
When using the local
driver, public
visibility translates to 0755
permissions for directories and 0644
permissions for files. You can modify the permissions mappings in your application's filesystems
configuration file:
Deleting Files
The delete
method accepts a single filename or an array of files to delete:
If necessary, you may specify the disk that the file should be deleted from:
Directories
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:
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:
Create A Directory
The makeDirectory
method will create the given directory, including any needed subdirectories:
Delete A Directory
Finally, the deleteDirectory
method may be used to remove a directory and all of its files:
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:
Next, you can register the driver within the boot
method of one of your application's service providers. To accomplish this, you should use the extend
method of the Storage
facade:
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 LeagueFlysystemFilesystem
. 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.
- Installation
- Configuration
- Indexing
- Searching
Introduction
Laravel Scout provides a simple, driver based solution for adding full-text search to your Eloquent models. Using model observers, Scout will automatically keep your search indexes in sync with your Eloquent records.
Currently, Scout ships with Algolia and MeiliSearch drivers; however, writing custom drivers is simple and you are free to extend Scout with your own search implementations.
Installation
First, install Scout via the Composer package manager:
After installing Scout, you should publish the Scout configuration file using the vendor:publish
Artisan command. This command will publish the scout.php
configuration file to your application's config
directory:
Finally, add the LaravelScoutSearchable
trait to the model you would like to make searchable. This trait will register a model observer that will automatically keep the model in sync with your search driver:
Driver Prerequisites
Algolia
When using the Algolia driver, you should configure your Algolia id
and secret
credentials in your config/scout.php
configuration file. Once your credentials have been configured, you will also need to install the Algolia PHP SDK via the Composer package manager:
MeiliSearch
When using the MeiliSearch driver you will need to install the MeiliSearch PHP SDK via the Composer package manager:
Then, set the SCOUT_DRIVER
environment variable as well as your MeiliSearch host
and key
credentials within your application's .env
file:
For more information regarding MeiliSearch, please consult the MeiliSearch documentation.
{tip} If you aren't sure how to install MeiliSearch on your local machine, you may use Laravel Sail, Laravel's officially supported Docker development environment.
Queueing
While not strictly required to use Scout, you should strongly consider configuring a queue driver before using the library. Running a queue worker will allow Scout to queue all operations that sync your model information to your search indexes, providing much better response times for your application's web interface.
Once you have configured a queue driver, set the value of the queue
option in your config/scout.php
configuration file to true
:
Configuration
Configuring Model Indexes
Each Eloquent model is synced with a given search 'index', which contains all of the searchable records for that model. In other words, you can think of each index like a MySQL table. By default, each model will be persisted to an index matching the model's typical 'table' name. Typically, this is the plural form of the model name; however, you are free to customize the model's index by overriding the searchableAs
method on the model:
Configuring Searchable Data
By default, the entire toArray
form of a given model will be persisted to its search index. If you would like to customize the data that is synchronized to the search index, you may override the toSearchableArray
method on the model:
Configuring The Model ID
By default, Scout will use the primary key of the model as model's unique ID / key that is stored in the search index. If you need to customize this behavior, you may override the getScoutKey
and the getScoutKeyName
methods on the model:
Identifying Users
Scout also allows you to auto identify users when using Algolia. Associating the authenticated user with search operations may be helpful when viewing your search analytics within Algolia's dashboard. You can enable user identification by defining a SCOUT_IDENTIFY
environment variable as true
in your application's .env
file:
Enabling this feature this will also pass the request's IP address and your authenticated user's primary identifier to Algolia so this data is associated with any search request that is made by the user.
Indexing
Batch Import
Laravel Search Query
If you are installing Scout into an existing project, you may already have database records you need to import into your indexes. Scout provides a scout:import
Artisan command that you may use to import all of your existing records into your search indexes:
The flush
command may be used to remove all of a model's records from your search indexes:
Modifying The Import Query
If you would like to modify the query that is used to retrieve all of your models for batch importing, you may define a makeAllSearchableUsing
method on your model. This is a great place to add any eager relationship loading that may be necessary before importing your models:
Adding Records
Once you have added the LaravelScoutSearchable
trait to a model, all you need to do is save
or create
a model instance and it will automatically be added to your search index. If you have configured Scout to use queues this operation will be performed in the background by your queue worker:
Adding Records Via Query
If you would like to add a collection of models to your search index via an Eloquent query, you may chain the searchable
method onto the Eloquent query. The searchable
method will chunk the results of the query and add the records to your search index. Again, if you have configured Scout to use queues, all of the chunks will be imported in the background by your queue workers:
You may also call the searchable
method on an Eloquent relationship instance:
Or, if you already have a collection of Eloquent models in memory, you may call the searchable
method on the collection instance to add the model instances to their corresponding index:
Laravel Search In A Table
{tip} The searchable
method can be considered an 'upsert' operation. In other words, if the model record is already in your index, it will be updated. If it does not exist in the search index, it will be added to the index.
Updating Records
To update a searchable model, you only need to update the model instance's properties and save
the model to your database. Scout will automatically persist the changes to your search index:
You may also invoke the searchable
method on an Eloquent query instance to update a collection of models. If the models do not exist in your search index, they will be created:
If you would like to update the search index records for all of the models in a relationship, you may invoke the searchable
on the relationship instance:
Or, if you already have a collection of Eloquent models in memory, you may call the searchable
method on the collection instance to update the model instances in their corresponding index:
Removing Records
To remove a record from your index you may simply delete
the model from the database. This may be done even if you are using soft deleted models:
If you do not want to retrieve the model before deleting the record, you may use the unsearchable
method on an Eloquent query instance:
If you would like to remove the search index records for all of the models in a relationship, you may invoke the unsearchable
on the relationship instance:
Or, if you already have a collection of Eloquent models in memory, you may call the unsearchable
method on the collection instance to remove the model instances from their corresponding index:
Pausing Indexing
Sometimes you may need to perform a batch of Eloquent operations on a model without syncing the model data to your search index. You may do this using the withoutSyncingToSearch
method. This method accepts a single closure which will be immediately executed. Any model operations that occur within the closure will not be synced to the model's index:
Conditionally Searchable Model Instances
Sometimes you may need to only make a model searchable under certain conditions. For example, imagine you have AppModelsPost
model that may be in one of two states: 'draft' and 'published'. You may only want to allow 'published' posts to be searchable. To accomplish this, you may define a shouldBeSearchable
method on your model:
The shouldBeSearchable
method is only applied when manipulating models through the save
and create
methods, queries, or relationships. Directly making models or collections searchable using the searchable
method will override the result of the shouldBeSearchable
method.
Searching
You may begin searching a model using the search
method. The search method accepts a single string that will be used to search your models. You should then chain the get
method onto the search query to retrieve the Eloquent models that match the given search query:
Since Scout searches return a collection of Eloquent models, you may even return the results directly from a route or controller and they will automatically be converted to JSON:
If you would like to get the raw search results before they are converted to Eloquent models, you may use the raw
method:
Custom Indexes
Search queries will typically be performed on the index specified by the model's searchableAs
method. However, you may use the within
method to specify a custom index that should be searched instead:
Where Clauses
Scout allows you to add simple 'where' clauses to your search queries. Currently, these clauses only support basic numeric equality checks and are primarily useful for scoping search queries by an owner ID. Since a search index is not a relational database, more advanced 'where' clauses are not currently supported:
Pagination
In addition to retrieving a collection of models, you may paginate your search results using the paginate
method. This method will return an IlluminatePaginationLengthAwarePaginator
instance just as if you had paginated a traditional Eloquent query:
You may specify how many models to retrieve per page by passing the amount as the first argument to the paginate
method:
Once you have retrieved the results, you may display the results and render the page links using Blade just as if you had paginated a traditional Eloquent query:
Of course, if you would like to retrieve the pagination results as JSON, you may return the paginator instance directly from a route or controller:
Soft Deleting
If your indexed models are soft deleting and you need to search your soft deleted models, set the soft_delete
option of the config/scout.php
configuration file to true
:
When this configuration option is true
, Scout will not remove soft deleted models from the search index. Instead, it will set a hidden __soft_deleted
attribute on the indexed record. Then, you may use the withTrashed
or onlyTrashed
methods to retrieve the soft deleted records when searching:
{tip} When a soft deleted model is permanently deleted using forceDelete
, Scout will remove it from the search index automatically.
Customizing Engine Searches
If you need to perform advanced customization of the search behavior of an engine you may pass a closure as the second argument to the search
method. For example, you could use this callback to add geo-location data to your search options before the search query is passed to Algolia:
Custom Engines
Writing The Engine
If one of the built-in Scout search engines doesn't fit your needs, you may write your own custom engine and register it with Scout. Your engine should extend the LaravelScoutEnginesEngine
abstract class. This abstract class contains eight methods your custom engine must implement:
You may find it helpful to review the implementations of these methods on the LaravelScoutEnginesAlgoliaEngine
class. This class will provide you with a good starting point for learning how to implement each of these methods in your own engine.
Registering The Engine
Laravel Search Array
Once you have written your custom engine, you may register it with Scout using the extend
method of the Scout engine manager. Scout's engine manager may be resolved from the Laravel service container. You should call the extend
method from the boot
method of your AppProvidersAppServiceProvider
class or any other service provider used by your application:
Once your engine has been registered, you may specify it as your default Scout driver
in your application's config/scout.php
configuration file:
Builder Macros
If you would like to define a custom Scout search builder method, you may use the macro
method on the LaravelScoutBuilder
class. Typically, 'macros' should be defined within a service provider'sboot
method:
Laravel Search Ajax Video
The macro
function accepts a macro name as its first argument and a closure as its second argument. The macro's closure will be executed when calling the macro name from a LaravelScoutBuilder
implementation: