30 lines
744 B
PHP
30 lines
744 B
PHP
<?php
|
|
|
|
namespace App\Traits;
|
|
|
|
use App\Models\Image;
|
|
use Illuminate\Http\Request;
|
|
|
|
trait HandlesImageUpload
|
|
{
|
|
/**
|
|
* If the request carries an uploaded image file, store it, create an Image
|
|
* record for it, and return that record's id. Returns null when no file is
|
|
* present so callers can fall back to a provided image_id.
|
|
*/
|
|
protected function uploadedImageId(Request $request, string $field = 'image'): ?int
|
|
{
|
|
if (!$request->hasFile($field)) {
|
|
return null;
|
|
}
|
|
|
|
$path = $request->file($field)->store('images', 'public');
|
|
|
|
return Image::create([
|
|
'user_id' => auth()->id(),
|
|
'path' => $path,
|
|
'type' => 'public',
|
|
])->id;
|
|
}
|
|
}
|