To work with the Asset Repository, use the following Facade:
use Statamic\Facades\Asset;php
Methods#
Methods | Description |
---|---|
all() |
Get all Assets |
find($filename) |
Get Asset by filename |
findByPath($path) |
Get Asset by path |
findByUrl($url) |
Get Asset by url |
findOrFail($filename) |
Get Asset by filename . Throws an AssetNotFoundException when the asset cannot be found. |
query() |
Query Builder |
whereContainer($container) |
Find Assets by AssetContainer |
whereFolder($folder) |
Find Assets in a filesystem folder |
make() |
Makes a new Asset instance |
You must specify the Asset Container when querying Assets.
Querying#
Examples#
Get all assets in a container#
Asset::query()->where('container', 'main')->get();php
Get all assets in a folder#
Asset::query()->where('container', 'main')->where('folder', 'team_photos')->get();php
Get all assets without an alt tag#
Asset::query()->where('container', 'main')->where('alt', null)->get();php
Get all Assets with "thumbnail" in the path.#
Asset::query()->where('container', 'main')->where('path', 'like', '%thumbnail%')->get();php
Get the newest 10 assets from a container#
Asset::query()->where('container', 'main')->orderBy('last_modified', 'desc')->get();php
Creating#
Start by making an instance of an asset with the make
method.
You need at least a path and the container before you can save an asset.
$asset = Asset::make()->container('assets')->path('images/hat.jpg');php
Or, if you have an asset container instance, you can use the makeAsset
method.
$asset = $container->makeAsset('images/hat.jpg');php
Once you have an asset instance, you can add data to it.
$asset->data(['foo' => 'bar']);php
Finally, save it. It'll return a boolean for whether it succeeded.
$asset->save(); // true or falsephp
Saving an asset instance will only store the metadata. It doesn't actually create the asset itself.
You should manually place the asset at the corresponding location, or you can use the upload
method which accepts an UploadedFile
instance.
$file = $request->file('file');$asset->upload($file);php