Darceys's avatar

Upload Multiple images

Hello, Hope you're all doing well. I have an issue with my store function to store model in my database. I have a news model with some columns including three image columns like "news_image", "news_image1", "news_image2". The fact is that when I try to add more than two images at the same time, the second image erase the first one an I have the same image on the view. Can you please help me with that ? Below my code.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class News extends Model
{
    use HasFactory;

    protected $fillable = [
      'title', 'description', 'littleDescription', 'news_image', 'news_image1', 'news_image2',
    ];

    public function comments() : HasMany{
        return $this->hasMany(Comments::class);
    }
}

store function

    public function store(Request $request){

        $this -> validate($request, [
            'title' => 'required',
            'description' => 'required',
            'littleDescription' => 'required',
            'news_image' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:20000',
            'news_image1' => 'image|mimes:jpeg,png,jpg,gif,svg|max:20000',
            'news_image2' => 'image|mimes:jpeg,png,jpg,gif,svg|max:20000',
        ]);

        $input = $request->all();

        if ($image = $request->file('news_image')) {
            $destinationPath = 'images/news/';
            $news_image = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $news_image);
            $input['news_image'] = "$news_image";
        }

        if ($image = $request->file('news_image1')) {
            $destinationPath = 'images/news/';
            $news_image1 = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $news_image1);
            $input['news_image1'] = "$news_image1";
        }

        if ($image = $request->file('news_image2')) {
            $destinationPath = 'images/news/';
            $news_image2 = date('YmdHis') . "." . $image->getClientOriginalExtension();
            $image->move($destinationPath, $news_image2);
            $input['news_image2'] = "$news_image2";
        }

        $news = News::create($input);
        $news->save();

        return redirect('news');
    }

My create form

@extends('layouts.app')

@section('title', 'Creér un restaurant.')

@section('content')

    <div class="container">
        <h1 class="mb-3">Créer une promotion </h1>
        <form method="POST" role="form" multiple="true" enctype="multipart/form-data">
            {{ csrf_field() }}
            @method('POST')
            <div class="mb-3 form-group{{ $errors->has('title') ? ' has-error' : '' }}">
                <label for="title" class="col-md-4 control-label"> Titre du restaurant</label>
                <input id="title" type="text" class="form-control w-50" name="title" required>
                @if ($errors->has('title'))
                    <span class="help-block">
                        <strong>{{ $errors->first('title') }}</strong>
                    </span>
                @endif
            </div>

            <div class="mb-3 form-group{{ $errors->has('description') ? ' has-error' : '' }}">
                <label for="description" class="col-md-4 control-label"> Promotion </label>
                <input id="description" type="text" class="form-control w-50" name="description" required>
                @if ($errors->has('description'))
                    <span class="help-block">
                        <strong>{{ $errors->first('description') }}</strong>
                    </span>
                @endif
            </div>

            <div class="mb-3 form-group{{ $errors->has('littleDescription') ? ' has-error' : '' }}">
                <label for="littleDescription" class="col-md-4 control-label">Petite description </label>
                <input id="littleDescription" type="text" class="form-control w-50" name="littleDescription" required>
                @if ($errors->has('littleDescription'))
                    <span class="help-block">
                        <strong>{{ $errors->first('littleDescription') }}</strong>
                    </span>
                @endif
            </div>


            <div class="mb-3 form-group{{ $errors->has('news_image') ? ' has-error' : '' }}">
                <label for="news_image" class="col-md-4 control-label">Image 1<span class="text-danger fs-3">*</span></label>
                <input id="news_image" class="img-thumbnail" name="news_image" type="file" required>
                @if ($errors->has('news_image'))
                    <span class="help-block">
                        <strong>{{ $errors->first('news_image') }}</strong>
                    </span>
                @endif
            </div>

            <div class="mb-3 form-group{{ $errors->has('news_image1') ? ' has-error' : '' }}">
                <label for="news_image1" class="col-md-4 control-label">Image 2</label>
                <input id="news_image1" class="img-thumbnail" name="news_image1" type="file">
                @if ($errors->has('news_image1'))
                    <span class="help-block">
                        <strong>{{ $errors->first('news_image1') }}</strong>
                    </span>
                @endif
            </div>

            <div class="mb-3 form-group{{ $errors->has('news_image2') ? ' has-error' : '' }}">
                <label for="news_image2" class="col-md-4 control-label">Image 3</label>
                <input id="news_image2" class="img-thumbnail" name="news_image2" type="file">
                @if ($errors->has('news_image2'))
                    <span class="help-block">
                        <strong>{{ $errors->first('news_image2') }}</strong>
                    </span>
                @endif
            </div>

            <div class="col-md-6 col-md-offset-4">
                <button type="submit" class="btn buttonOrange text-dark mt-3">
                    Créer Promotion
                </button>
                <a class="btn buttonOrange text-dark mt-3" href="{{route('news.index')}}"> Retour </a>
            </div>
        </form>
    </div>

@endsection

And the show section

@extends('layouts.app1')

@section('title', 'Voir un restaurant')

@section('content')

    <div class="container">
        <h3 class="ml-1"> Restaurant {{$news->title}} </h3>

        <div class="row">

            <div class="col-md-6 border-end border-dark">

                <div id="carouselExampleControls" class="carousel slide mr-3" data-bs-ride="carousel">
                    <div class="carousel-inner">

                        @if($news->news_image2 != "null")

                            <div class="carousel-item active">
                                <img class="img-fluid rounded my-3" src="{{ asset('images/news/' . $news-> news_image) }}" width="500px" height="500px">
                            </div>

                            <div class="carousel-item">
                                <img class="img-fluid rounded my-3" src="{{ asset('images/news/' . $news-> news_image1) }}"  width="500px" height="500px">
                            </div>

                            <div class="carousel-item">
                                <img class="img-fluid rounded my-3" src="{{ asset('images/news/' . $news-> news_image2) }}"  width="500px" height="500px">
                            </div>

                        @endif

                    </div>

                    <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev">
                        <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                        <span class="visually-hidden">Précédent</span>
                    </button>
                    <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next">
                        <span class="carousel-control-next-icon " aria-hidden="true"></span>
                        <span class="visually-hidden">Suivant</span>
                    </button>

                </div>
            </div>

            <div class="col-md-6 mx-auto my-auto">

                <p class="text-center fs-2 mt-5 font-weight-bold" style="font-size: larger;">  {{$news->description}} </p>
                <p class="text-center " style="font-size: larger;">  {{$news->littleDescription}} </p>

                @auth()
                    @if(auth()->user()->is_admin)
                        <hr>
                        <h5 class="mt-4"> Action sur la promo </h5>
                        <a href="{{url('/edit_news/' . $news->id)}}" class="btn btn-primary mt-2">Modifier</a>
                        <form action="{{route('new.delete', $news->id)}}" method="POST" class=" d-inline">
                        {!! csrf_field() !!}
                        @method('DELETE')
                        <button type="submit" class=" mt-2 btn btn-danger"> Supprimer </button>
                        </form>
                    @endif
                @endauth

            </div>

        </div>

        <hr>

        <h3 class="text-center my-3"> Commentaires </h3>

        <div class="col-md w-100 ">

            <form method="POST" action="{{route('comments.store')}}" role="form">
                @csrf
                @method("POST")
                <div class="mb-3 form-group form-floating {{ $errors->has('body') ? ' has-error' : '' }}">
                    <input type="hidden" name="news_id" value="{{ $news->id }}">
                    <textarea type="text" id="body" class="form-control border border-warning w-100" name="body"> </textarea>
                    <label for="body">Ajouter un commentaire</label>
                    @if ($errors->has('body'))
                        <span class="help-block">
                        <strong>{{ $errors->first('body') }}</strong>
                                </span>
                    @endif
                </div>
                <div class="col-md-6 col-md-offset-4">
                    <button type="submit" class="btn buttonOrange text-dark mt-3">
                        Ajouter
                    </button>
                    <a class="btn buttonOrange text-dark mt-3" href="{{route('news.index')}}">
                        Retour
                    </a>
                </div>

            </form>

        </div>

        @if($news->comments->isEmpty())
            <h4 class="mt-5">Soyez le premier à rajouter un commentaire!</h4>
        @else

            <div class="rounded-lg p-3 w-100 mt-3 " style="background-color: #D3D3D3">
                <ol>
                    @foreach($news->comments as $comment)
                        <li class="mt-2"> {{$comment->body}}, le <strong> {{ $comment->created_at->format('d/m/y') }} </strong> </li>
                    @endforeach
                </ol>
            </div>
        @endif

    </div>
@endsection

Can you please help me with that ?

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

it's because of the way you name the file. It only uses date to the second and your script is capable of saving multiple files per second so they get the same name and one overwrites another. Add a random string to the filename or -1, -2 etc

eg

$news_image = date('YmdHisv') . "." . $image->getClientOriginalExtension();

will add milliseconds to the filename

Please or to participate in this conversation.