jeudi 2 avril 2020

How can you properly create a form which has options to fill for text fields and an option to upload an image? PHP/Laravel

I have created a form which has fillable input fields but there is an option to upload an image to.

The form example:

{!! Form::open(['method' => 'POST', 'route' => ['app.json-ld.update']])!!}
    {!! Form::label('name', 'Store name', ['class' => 'form-label']) !!}
    {!! Form::text('name', $shop->jsonLDFields->name ?? '', ['class' => 'form-control']) !!}
    {!! Form::label('url', 'Store url', ['class' => 'form-label']) !!}
    {!! Form::text('url', $shop->jsonLDFields->url ?? '', ['class' => 'form-control']) !!}
    {!! Form::label('description', 'Store Description', ['class' => 'form-label']) !!}
    {!! Form::textarea('description', $shop->jsonLDFields->description ?? '', ['class' => 'form- 
    control form-textarea']) !!}
    {!! Form::label('telephone', 'Phone number', ['class' => 'form-label']) !!}
    {!! Form::text('telephone', $shop->jsonLDFields->telephone ?? '', ['class' => 'form- 
control']) !!}
    {!! Form::label('image', 'Upload store image', ['class' => 'form-label']) !!}
    {!! Form::file('image', (['class' => 'my-1'])) !!}
    <button class="btn btn-success my-2" type="submit">Update</button>
{!! Form::close() !!}

Controller:

public function update(Request $request)
{
    $shop = Shop::with('jsonLDFields')->first();

    $shop->jsonLDFields->update([
        'name' => $request->name,
        'url' => $request->url,
        'description' => $request->description,
        'telephone' => $request->telephone
    ]);

    return back();

I have another controller method which works for uploading, but I don't want to make multiple forms

    public function uploadImage(Request $request)
{
    $shop = Shop::with('jsonLDFields')->first();
    $jsonLd = $shop->jsonLDFields;

    if(!$jsonLd) return back();

    $request->validate(['image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048']);
    $image = $request->image;
    $filename = Str::slug(microtime()) . '.' . $image->getClientOriginalExtension();

    $request->image->move(public_path('images/json-ld/images'), $filename);

    $jsonLd->image = $filename;
    $jsonLd->save();

    return back();
}

How can I implement an option to upload an image file in update controller method?

Have been trying in different ways, but the result was null. Would appreciate help with a solution.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire