Karim Ali
Karim Ali

Reputation: 27

Update method in laravel 9 change 1 value only

I'm updating a album with multi photos (Albums table Has many relation with images Table)

but when i use the update method it change 1 value only which is the first image and the reset keep without updating

but i cannot figure the way that makes it update all images when i replace them

Edit Form

<h1 class="text-center">Edit {{$album->name}}'s Name </h1>
<div class="container">
        <form method="post" action="{{route('albums.update',$album->id)}}" enctype="multipart/form-data">
        @csrf
        @method('PUT')
            <div class="mb-3">
                <label class="form-label">Album Name</label>
                <input type="text" class="form-control @error('name') is invalid @enderror" name="name" value="{{$album->name}}">
                @error('name')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>
            <div class="mb-3">
                <label class="form-label">Album Category</label>
                <input type="text" class="form-control @error('name') is invalid @enderror" name="category_id" value="{{$album->category_id}}">
                @error('name')
                <div class="alert alert-danger">{{ $message }}</div>
                @enderror
            </div>

            <div class="mb-3">
                <label class="form-label">Image</label>
                <input type="file" class="form-control @error('image') is-invalid @enderror" name="images[]" multiple>
                @error('image')
            <div class="alert alert-danger">{{ $message }}</div>
        @enderror

            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>

``

Update method in AlbumsController

public function update(Request $request, $id)
{
    $album=Album::findOrFail($id);
    $album->update([
        'name'=>$request->name,

        'category_id'=>$request->category_id,
    ]);

    foreach($request->images as $image){
        $albumImage=Time() . "_" . $image->getClientOriginalName();
        $image->move('albums',$albumImage);
        // $albumImage=Image::where('album_id', $id)->firstOrFail();
        $albumImage2=Image::where('album_id', $id)->firstOrFail();
        $albumImage2->update([
            'album_id'=>$album->id,
            'filename'=>$albumImage
        ]);
    }
    $albums=Album::all();
    return view('admin.albums.all',compact('albums'));

}

Upvotes: 0

Views: 5224

Answers (1)

ekkev
ekkev

Reputation: 56

Your line

$albumImage2=Image::where('album_id', $id)->firstOrFail();

will come back with the same related image every time: the first. Try replacing all the album images with the ones selected (delete all, then insert each).

Upvotes: 1

Related Questions