-2

I have a code with saving a article. With my article I have a photo ('img'), which I want to add to Model Article in field 'img'. How I can do it with using a best practices in Laravel?

ArticleController:

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 Article:

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);
    });
}
RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Klipe_LD
  • 31
  • 3
  • 2
    In the code you've shared there is no image upload. What have you tried? – Gert B. Nov 17 '22 at 13:00
  • I have edited my questions right now and have added some line of codes with 'not best practices'.. – Klipe_LD Nov 17 '22 at 13:08
  • 4
    There's a whole section in the docs on handling file uploads properly. https://laravel.com/docs/9.x/filesystem#file-uploads `$path = $request->file('avatar')->store('avatars');` is all it takes. – ceejayoz Nov 17 '22 at 13:11
  • The use of the `best practices` term does not fool anybody you know – RiggsFolly Nov 17 '22 at 13:57

1 Answers1

0

Laravel provide a more efficient way to store file, in docs.[https://laravel.com/docs/9.x/filesystem#file-uploads] it provides a store() which accepts storage path. you can simply do this like:

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

Note: file should be a laravel file not string, you can check it with isFile().