irankhosravi
4 months ago
361
27
Laravel

How to update and edit a image in laravel 5.8

Posted 4 months ago by irankhosravi

I have a table called Services, now this table has the following -

-id -title -body -image -slug -timestamps

And in administrator, services page I created for Add, Edit, Delete it.

My problem is edit and update a image. A strange problem is that, when I change the of image to aaaaa field in the service table (database), Nothing happens. should happen. because I changed rename of image to aaaaa.

web.php

Route::resource('services', 'ServiceController');

ServiceController.php

public function edit(Service $service)
{
    return view('Admin.services.edit', compact('service'));
}

public function update(Request $request, Service $service)
{
    $service->title = $request->title;
    $service->body = $request->body;

    if($request->hasFile('image')) {
        $image = $request->file('image');
        $filename = $image->getClientOriginalName();
        $image->move(public_path('images/services'), $filename);
        $service->image = $request->file('image')->getClientOriginalName();
    }

    $service->update();

    return redirect()->route('services.index');
}

edit.blade.php

<form class="form-horizontal" action="{{ route('services.update', $service->id) }}" method="post" enctype="multipart/form-data">
    {{ csrf_field() }}
    {{ method_field('PATCH') }}
    @include('Admin.layouts.errors')
    <div class="form-group">
        <label for="title">Title</label>
        <input type="text" class="form-control" id="title" name="title" placeholder="Title" value="{{ $service->title ? : old('title') }}">
    </div>
    <div class="form-group">
        <label for="body">Body</label>
        <textarea class="form-control" rows="10" id="body" name="body" placeholder="Body">{{ $service->body ? : old('body') }}</textarea>
    </div>
    <div class="form-group">
        <label for="image">Image</label>
        <div class="custom-file">
            <input type="file" class="custom-file-input" id="image" name="image">
            <label class="custom-file-label" for="image">Image</label>
        </div>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary">Save</button>
    </div>
</form>

Service.php

protected $fillable = [
    'title',
    'body',
    'image',
    'slug',
];

I even changed the controller in the update method as follows, nothing happened.

$service->save();

Please sign in or create an account to participate in this conversation.