Saving multiple images

Asked

Viewed 335 times

1

I’m not able to save multiple images in my database, follow my code below to in the highlighted line with the arrow (-->).

Observing: when it was just a normal saving image.

public function store(Request $request)
{
    $this->validate($request, [
        'descricao' => 'required',
        'valor' => 'required',
        'id_categorias' => 'required'
    ]);

    //verifica se a img existe e faz a validação da mesma
--> if ($request->hasFile('imagem') && $request->file('imagem')->isValid()) 
    {
        $filePath = $request->file('imagem')->store('public');
        foreach ($request->file('imagem') as $imagem){
        ProdutosImg::create([
           'id_produto' =>$request->id,
            'imagem' => $filePath,
        ]);
        }

        $produto = Produto::create([
            'descricao' => $request['descricao'],
            'valor' => $request['valor'],
            'id_categorias' => $request['id_categorias'],
            'imagem' => $filePath,
        ]);

        \Session::flash('mensagem_sucesso_produtos', 'Produto cadastrado com sucesso!!');
        return Redirect::to('produtos');
    } else {
        Produto::create($request->all());
        \Session::flash('mensagem_sucesso_produtos', 'Produto cadastrado com sucesso!!');
        return Redirect::to('produtos');
    }
}

Form:

@extends('layouts.app')
@section('content')
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
        <script src="jquery.maskMoney.js" type="text/javascript"></script>
    </head>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">
                    @if(Route::is('produtos.editar'))
                        Editando produto: <strong>{{$produto->descricao}}</strong>
                    @else
                        Cadastro de novo produto
                    @endif
                        <a class="pull-right" href="{{url('produtos')}}">Listar produtos</a>                    
                    </div>
                    <div class="panel-body">

                        <div class="panel-body">
                            @if(Route::is('produtos.editar'))

                                {{Form::model($produto,['class' => 'form-horizontal', 'method'=>'PATCH','url'=> route('produtos.update', $produto->id),
                                'files' => true])}}

                                {{ Form::hidden('id') }}
                            @else
                                {{ Form::open(['class' => 'form-horizontal', 'method' => 'POST', 'url' => route('produtos.salvar'),
                                'files' => true]) }}
                            @endif
                                    <div class="form-group">
                                        {!! Form::label('descricao','Descrição: ',['class' => 'control-label col-md-4']) !!}
                                        <div class="col-md-6">
                                            {!! Form::input('text','descricao',null,['class'=>'form-control {{ $errors->has("descricao") ? "has-error" : "" }}','autofocus','placeholder'=>'Descriçao']) !!}
                                        </div>
                                        @if($errors->has('name'))
                                            <span class="help-block">{{$errors->first('name')}}</span>
                                        @endif
                                    </div>

                                    <div class="form-group">
                                        {!! Form::label('valor','Valor: ', ['class' => 'control-label col-md-4']) !!}
                                        <div class="col-md-6">
                                            {!! Form::input('text','valor',null,['class'=>'form-control {{$errors->has("valor") ? "has-error" : ""}}','autofocus','placeholder'=>'Valor']) !!}
                                        </div>
                                        @if($errors->has('name'))
                                            <span class="help-block">{{$errors->first('name')}}</span>
                                        @endif
                                    </div>

                                    <div class="form-group">
                                        {!! Form::label('categoria','Categoria: ', ['class' => 'control-label col-md-4']) !!}
                                        <div class="col-md-6">
                                            <select name="id_categorias" id="categoria" class="form-control">
                                                @foreach($categorias as $categoria)
                                                    <option value="{{ $categoria->id }}">{{ $categoria->descricao }}</option>
                                                @endforeach
                                            </select>
                                        </div>
                                        @if($errors->has('name'))
                                            <span class="help-block">{{$errors->first('name')}}</span>
                                        @endif
                                    </div>
                                    <div class="form-group">
                                        {!! Form::label('imagem','Imagem: ', ['class' => 'control-label col-md-4']) !!}
                                        <div class="col-md-6">
                                            <input type="file" name="imagem[]" multiple/>
                                        </div>
                                    </div>
                                <div class="form-group">
                                    <div class="col-md-6 col-md-offset-4"><br>
                                        <button type="submit" class="btn btn-primary ">
                                        @if(Route::is('produtos.editar'))
                                            Editar
                                        @else
                                            Cadastrar
                                        @endif
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection

error below: appears when I save the image, so I’m seeing for in if :/

inserir a descrição da imagem aqui

  • Which version of Laravel? post the form in the question!

  • What is the error you have on the screen?

  • is the Laravel 5.4

1 answer

0


The solution is that instead of just doing with an image your code has to iterate on the result of several images, in this case it is a array now, example:

if ($request->hasFile('imagem')) 
{
    foreach($request->file('imagem') as $imagem)
    {
        if ($imagem->isValid())
        {
            $filePath = $imagem->store('public');

            ProdutosImg::create([
                'id_produto' => $request->id,
                'imagem' => $filePath,
            ]);

            $produto = Produto::create([
                'descricao' => $request['descricao'],
                'valor' => $request['valor'],
                'id_categorias' => $request['id_categorias'],
                'imagem' => $filePath,
            ]);
        }
    }
}

the code is what you need to solve the problem and to understand that when passing image in a field configured with multiple, the code reproduced by generates a array of information then need to check position to position the data sent to the server, for example the result of $request->file with the command var_dump

array(2) {
  [0]=>
  object(Illuminate\Http\UploadedFile)#207 (8) {
    ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    bool(false)
    ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(5) "2.png"
    ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(9) "image/png"
    ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(34686)
    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(0)
    ["hashName":protected]=>
    NULL
    ["pathName":"SplFileInfo":private]=>
    string(27) "C:\Windows\Temp\php81C4.tmp"
    ["fileName":"SplFileInfo":private]=>
    string(11) "php81C4.tmp"
  }
  [1]=>
  object(Illuminate\Http\UploadedFile)#208 (8) {
    ["test":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    bool(false)
    ["originalName":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(8) "1600.png"
    ["mimeType":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    string(9) "image/png"
    ["size":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(52826)
    ["error":"Symfony\Component\HttpFoundation\File\UploadedFile":private]=>
    int(0)
    ["hashName":protected]=>
    NULL
    ["pathName":"SplFileInfo":private]=>
    string(27) "C:\Windows\Temp\php81C5.tmp"
    ["fileName":"SplFileInfo":private]=>
    string(11) "php81C5.tmp"
  }
}

checking the result was sent two photos, so it is always so when uploaded photos in a field configured with multiple.

References

  • I mean, just me leaving my code in the format you put it there and that’s it?

  • @hmenezes follow the logic ... it has to run inside a foreach because it is an upload array! ok?

  • All right, thank you so much for your help!! D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.