ΠΠ»Ρ ΠΏΡΠΈΠΊΡΠ΅ΠΏΠ»Π΅Π½ΠΈΡ ΠΈΠ·ΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΡ ΠΊ ΡΠ΅ΡΡΡΡΡ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠ΅ΡΡΡ Π±ΠΈΠ±Π»ΠΈΠΎΡΠ΅ΠΊΠ° spatie/laravel-medialibrary.
Π Π΅Π³ΠΈΡΡΡΠ°ΡΠΈΡ ΠΌΠ΅Π΄ΠΈΠ°-ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΠΈ Π² ΠΌΠΎΠ΄Π΅Π»ΠΈ.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;
class Post extends Model implements HasMedia
{
use InteractsWithMedia
public function registerMediaCollections(): void
{
// ΠΠΎΠ»Π»Π΅ΠΊΡΠΈΡ Π΄Π»Ρ ΠΎΠ΄Π½ΠΎΠΉ ΠΊΠ°ΡΡΠΈΠ½ΠΊΠΈ
$this->addMediaCollection('preview')->singleFile();
}
}
Π livewire ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½ΡΠ΅ Π½ΡΠΆΠ½ΠΎ ΠΏΠΎΠ΄ΠΊΠ»ΡΡΠΈΡΡ ΡΡΠ΅ΠΉΡ HasMedia ΠΈ Π΄ΠΎΠ±Π°Π²ΠΈΡΡ Π½ΠΎΠ²ΠΎΠ΅ ΠΏΡΠ±Π»ΠΈΡΠ½ΠΎΠ΅ ΡΠ²ΠΎΠΉΡΡΠ²ΠΎ, ΠΊΠΎΡΠΎΡΠΎΠ΅ ΡΠΎΠ²ΠΏΠ°Π΄Π°Π΅Ρ Ρ Π½Π°Π·Π²Π°Π½ΠΈΠ΅ΠΌ ΠΌΠ΅Π΄ΠΈΠ°-ΠΊΠΎΠ»Π»Π΅ΠΊΡΠΈΠΈ Π² ΠΌΠΎΠ΄Π΅Π»ΠΈ.
ΠΠ»Ρ Π²Π°Π»ΠΈΠ΄Π°ΡΠΈΠΈ ΠΏΠΎΠ»Ρ ΠΈΡΠΏΠΎΠ»ΡΠ·ΡΠΉΡΠ΅ ΠΊΠ°ΡΡΠΎΠΌΠ½ΠΎΠ΅ ΠΏΡΠ°Π²ΠΈΠ»ΠΎ SingleMedia ΠΈΠ· Rock.Cms.
app/Http/Livewire/Admin/Posts/PostItem.php
<?php
namespace App\Http\Livewire\Admin\Posts;
use App\Models\Post;
use WebVovan\RockCms\Http\Livewire\ResourceComponent;
use WebVovan\RockCms\Rules\SingleMedia;
use WebVovan\RockCms\Traits\Livewire\HasMedia;
class PostItem extends ResourceComponent
{
use HasMedia;
// Π‘Π²ΠΎΠΉΡΡΠ²ΠΎ Π΄Π»Ρ ΠΈΠ·ΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΡ
public $preview;
public Post $resource;
public string $resourceClass = Post::class;
public string $nameRouteResourceList = 'posts.list';
public string $nameRouteResourceEdit = 'posts.edit';
// ΠΡΠ°Π²ΠΈΠ»Π° Π²Π°Π»ΠΈΠ΄Π°ΡΠΈΠΈ ΠΏΠΎΠ»Π΅ΠΉ
public function rules()
{
return [
'resource.title' => 'string|required',
'resource.desc' => 'string',
'preview' => new SingleMedia(),
];
}
/**
* ΠΡΠ·ΡΠ²Π°Π΅ΡΡΡ ΠΎΠ΄ΠΈΠ½ ΡΠ°Π· ΠΏΡΠΈ ΠΈΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΈΠΈ ΠΊΠΎΠΌΠΏΠΎΠ½Π΅Π½ΡΠ°
*/
public function init()
{
$this->resource->title = $this->resource->title ?? '';
$this->resource->desc = $this->resource->desc ?? '';
// ΠΠ½ΠΈΡΠΈΠ°Π»ΠΈΠ·Π°ΡΠΈΡ ΡΠ²ΠΎΠΉΡΡΠ²Π° Ρ ΠΈΠ·ΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΠ΅ΠΌ
$this->preview = $this->resource->getFirstMedia('preview');
}
/**
* ΠΡΠ·ΡΠ²Π°Π΅ΡΡΡ ΠΏΡΠΈ ΡΠΎΡ
ΡΠ°Π½Π΅Π½ΠΈΠΈ ΡΠ΅ΡΡΡΡΠ°
*/
public function save()
{
$this->resource->save();
// Π‘ΠΎΡ
ΡΠ°Π½Π΅Π½ΠΈΠ΅ ΠΈΠ·ΠΎΠ±ΡΠ°ΠΆΠ΅Π½ΠΈΡ
$this->saveSingleMedia($this->resource, $this->preview, 'preview');
}
public function render()
{
return view('livewire.admin.posts.post-item');
}
}
<x-rock-cms::fields.single-image :model="$preview" field="preview" title="ΠΡΠ΅Π²ΡΡ"/>