如何保存 url 和本地图像?

How can I save url and local images?

我正在做一个使用 Spotify API 的项目。我从用户那里获得了所有热门曲目和顶级艺术家。我将信息保存到我的数据库中,我从 Spotify 获得的图像是 URL 图像。像这样https://i.scdn.co/image/ab67616d0000b27300d5163a674cf57fe79866a6

在我的 CMS 中,我希望能够更改艺术家或曲目的图像。为此,我从文档 https://backpackforlaravel.com/docs/4.1/crud-fields#image-1 "public function setImageAttribute($value) 中复制了代码并将其放入我的模型中。这部分一切正常,我可以上传一个新图像并且它保存到我的 public 文件夹中并显示在我的 table.

我遇到的问题是,当新用户登录并且 artist/track 数据需要保存在数据库中时,它会通过模型中的这个 setImageAttribute($value) 并且不会添加URL进入数据库列。

有没有一种方法可以在不通过模型中的 setImageAttribute 函数的情况下添加 URL 图像?

控制器:

//get Top Artists
            $client = new Client([]);
            $topartists = $client->get('https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=25&offset=5', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $token,
                ],
            ]);
            $listtopartists = json_decode($topartists->getBody(), true);
    
            $p = 25;
        foreach ($listtopartists['items'] as $topartist) {
            $artist = TopArtist::where('artist_id', $topartist['id'])->first();
            $artist_genre = json_encode($topartist['genres']);

            if ($artist === null) {
                $new_artist = TopArtist::create([
                    'artist_id' => $topartist['id'],
                    'name' => $topartist['name'],
                    'genres' => $artist_genre,
                    'users_popularity' => $p,
                    'popularity' => $topartist['popularity'],
                    'image' => $topartist['images'][0]['url'],
                    'url' => $topartist['external_urls']['spotify'],
                ]);

                $spotify_user->topArtists()->attach($new_artist->id);

            } else {

                $exists = $spotify_user->topArtists()->where('spotify_user_id', $spotify_user->id)->where('top_artist_id', $artist->id)->get();

                if ($exists->isEmpty()) {
                    $spotify_user->topArtists()->attach($artist->id);
                }
            }
            $p--;
        }

模特:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;

class TopArtist extends Model
{
    use \Backpack\CRUD\app\Models\Traits\CrudTrait;
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'artist_id',
        'name',
        'popularity',
        'users_popularity',
        'url',
        'image',
        'genres',
        'status',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'id' => 'integer',
        'status' => 'boolean',
    ];

    public function setImageAttribute($value)
    {
        $attribute_name = "image";
        // or use your own disk, defined in config/filesystems.php
        $disk = config('backpack.base.root_disk_name');
        // destination path relative to the disk above
        $destination_path = "public/storage/artists";
        // if the image was erased
        if ($value==null) {
            // delete the image from disk
            \Storage::disk($disk)->delete($this->{$attribute_name});
            // set null in the database column
            $this->attributes[$attribute_name] = null;
        }

        // if a base64 was sent, store it in the db
        if (Str::startsWith($value, 'data:image'))
        {
            $image = \Image::make($value)->encode('jpg', 90);
            $filename = md5($value.time()).'.jpg';
            \Storage::disk($disk)->put($destination_path.'/'.$filename, $image->stream());
            \Storage::disk($disk)->delete($this->{$attribute_name});
            $public_destination_path = Str::replaceFirst('public/', '', $destination_path);
            $this->attributes[$attribute_name] = $public_destination_path.'/'.$filename;
        }
    }

    public function spotifyUsers()
    {
        return $this->belongsToMany(\App\Models\SpotifyUser::class);
    }
}

我修好了,我不得不在

之后添加一个else语句
if (Str::startsWith($value, 'data:image'))

在我设置的模型中$this->attributes[$attribute_name] = $value;