簡體   English   中英

如何使用 Laravel (php) 中的最佳實踐保存圖像?

[英]How I can save image with using a best practices in Laravel (php)?

我有一個保存文章的代碼。 在我的文章中,我有一張照片 ('img'),我想將其添加到字段 'img' 中的 Model 文章中。 我如何使用 Laravel 中的最佳實踐來做到這一點?

文章控制器:

public function __construct(Article $article, ArticleService $articleService)
{
    $this->article = $article;
    $this->articleService = $articleService;
}

public function store(StoreRequest $request)
{
    if($request->file())
    {
        $file = ($request->file())['img'];
        $fileName = time().'_'.rand().'.'.$file->extension();
        $file->move(public_path('img/articles'), 
        $fileName);
        $request->img= $fileName;
    }
    $article = $this->article->create($request->validated());

    return redirect(route('article.index',['article' => $article->id]));
}

Model 文章:

protected $fillable = [
        'title_en',
        'body_en',
        'title_pl',
        'body_pl',
        'title_ru',
        'body_ru'
    ];

public static function boot()
{
    parent::boot();

    static::saving(function ($model) {
        $model->slug = Str::slug($model->title_en);
    });
}

Laravel 提供了一種更有效的文件存儲方式,在文檔中。[https://laravel.com/docs/9.x/filesystem#file-uploads] 它提供了一個 store() 接受存儲路徑。 你可以簡單地這樣做:

$data = $request->only('field1',...);
if($request->hasFile('filename')) {
$file = $request->file('filename');
$data['key_name'] = $file->store('pathname');
}
$article->create($data);

注意:文件應該是一個 laravel 文件而不是字符串,你可以用 isFile() 檢查它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM