50 lines
1.2 KiB
PHP
50 lines
1.2 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Traits;
|
||
|
|
|
||
|
|
trait ImageUrlTrait
|
||
|
|
{
|
||
|
|
/**
|
||
|
|
* Automatically prepend the base URL to image fields.
|
||
|
|
*
|
||
|
|
* @param string $key
|
||
|
|
* @return mixed
|
||
|
|
*/
|
||
|
|
public function getAttribute($key)
|
||
|
|
{
|
||
|
|
$value = parent::getAttribute($key);
|
||
|
|
|
||
|
|
// Check if the current key is in the imageFields array
|
||
|
|
if (isset($this->imageFields) && in_array($key, $this->imageFields) && $value) {
|
||
|
|
// Check if it's already a full URL
|
||
|
|
if (!filter_var($value, FILTER_VALIDATE_URL)) {
|
||
|
|
return asset($value);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $value;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Handle serialization to array.
|
||
|
|
*
|
||
|
|
* @return array
|
||
|
|
*/
|
||
|
|
public function attributesToArray()
|
||
|
|
{
|
||
|
|
$attributes = parent::attributesToArray();
|
||
|
|
|
||
|
|
if (isset($this->imageFields)) {
|
||
|
|
foreach ($this->imageFields as $field) {
|
||
|
|
if (isset($attributes[$field]) && $attributes[$field]) {
|
||
|
|
if (!filter_var($attributes[$field], FILTER_VALIDATE_URL)) {
|
||
|
|
$attributes[$field] = asset($attributes[$field]);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $attributes;
|
||
|
|
}
|
||
|
|
}
|