A
A
ashfedor2020-04-22 12:23:45
Laravel
ashfedor, 2020-04-22 12:23:45

How to properly upload an image in Laravel?

I’ll write right away that I’m just learning Laravel and perhaps this question is ridiculous for Lara experts.
Now I am uploading a picture for a post
in the form for adding a post, added the upload input and enctype="multipart/form-data"

<div class="form-group">
                <input type="file" name="img">
            </div>

further after checking the fields in the request
'title' => 'required|min:5|max:200|unique:blog_posts',
            'slug' => 'max:200',
            'excerpt'=> 'max:250',
            'content_raw' => 'required|string|max:15000|min:3',
            'category_id'=> 'required|integer|exists:blog_categories,id',
            'img'=> 'required|image',

I send them to the controller
$data = $request->input();
I try to print in dd($data)
in the controller,
but there is no img image field.
5ea00a16dfdd1983728580.jpeg
I fought with the form all day, I thought that it did not send the file, but when I tried to get it separately, it turned out. Now I got it and added it to the data array
$data = $request->input();
        $path = $request->file('img')->store('upload', 'public');
        $data = array_add($data, 'img', $path);
        dd($data);

5ea00b2940e84649035341.jpeg
In general, now everything works fine, but it’s right to throw the image processing logic into the obsserver. I generate a slug in it, work with text and produce other little things.
now the controller code is like this
public function store(BlogPostCreateRequest $request)
    {
        $data = $request->input();
        $path = $request->file('img')->store('upload', 'public');
        $data = array_add($data, 'img', $path);

        $item = (new BlogPost())->create($data);
    }

The question is how to transfer and is it worth it? and why $data = $request->input(); doesn't display a picture?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question