How to update an image to the database with Laravel?

Asked

Viewed 606 times

2

I managed to upload the photos in the database, but I can’t update these photos, when it is updated it deletes the image from the database but does not use the new.

I kind of tried to copy the code from store but it didn’t work. I know it sounds like a stupid question but I couldn’t find anywhere similar to help me, all the questions were to save in a folder of the Port being that as I use the server of the shared Hostinger there is no way I take the photos of the folder Storage.

So it has to be recorded in the database.

Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;
use App\Empresa;
use App\Sobre;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Input;
use Intervention\Image\ImageManagerStatic as Image;
use Response;

class SobresController extends Controller
{
    public function __construct(){
        $this->middleware('auth');
    }

    public function index()
    {
        $empresas = DB::table('empresas')->select('id', 'cnpj', 'razao_social', 'nome_fantasia')->get();
        $usuario = DB::table('users')->pluck('name');
        $sobres = DB::table('sobres')->select('id', 'titulo_sobre', 'descricao_sobre', 'pic')->get();
        $configuracoes = DB::table('configuracoes')->select('id', 'pic', 'cor_principal')->get();

        return view('sobres.index')->with('sobres', $sobres)->with('empresas', $empresas)->with('configuracoes', $configuracoes);
    }

    public function create()
    {
        $empresas = DB::table('empresas')->select('id', 'cnpj', 'razao_social', 'nome_fantasia')->get();
        $usuario = DB::table('users')->pluck('name');
        $configuracoes = DB::table('configuracoes')->select('id', 'pic', 'cor_principal')->get();

        return view('sobres.create')->with('empresas', $empresas)->with('configuracoes', $configuracoes);
    }

    public function store(Request $request)
    {
        $file = Input::file('pic');
        $img = Image::make($file);
        Response::make($img->encode('jpeg'));

        $sobres = new Sobre;
        $sobres->titulo_sobre = $request->get('titulo_sobre');
        $sobres->descricao_sobre = $request->get('descricao_sobre');        
        $sobres->pic = $img;
        $sobres->save();

        return redirect()->route('sobres.index')
                        ->with('success','Registro Criado com sucesso.');
    }

    public function show($id)
    {
        $empresas = DB::table('empresas')->select('id', 'cnpj', 'razao_social', 'nome_fantasia')->get();
        $usuario = DB::table('users')->pluck('name');

        $sobres = DB::table('sobres')->select('id', 'titulo_sobre', 'descricao_sobre', 'pic')->get();
        $configuracoes = DB::table('configuracoes')->select('id', 'pic', 'cor_principal')->get();

        $sobre = Sobre::where('id', $id)->firstOrFail();

        return view('sobres.show')->withSobre($sobre)->with('sobres', $sobres)->with('empresas', $empresas)->with('configuracoes', $configuracoes);
    }

    public function edit($id)
    {
        $empresas = DB::table('empresas')->select('id', 'cnpj', 'razao_social', 'nome_fantasia')->get();
        $usuario = DB::table('users')->pluck('name');

        $sobres = DB::table('sobres')->select('id', 'titulo_sobre', 'descricao_sobre', 'pic')->get();
        $configuracoes = DB::table('configuracoes')->select('id', 'pic', 'cor_principal')->get();

        $sobre = Sobre::where('id', $id)->firstOrFail();

        return view('sobres.edit')->withSobre($sobre)->with('sobres', $sobres)->with('empresas', $empresas)->with('configuracoes', $configuracoes);
    }

    public function update(Request $request, $id)
    {
        $sobres = Sobre::find($id);
        $file = Input::file('pic');
        $img = Image::make($file);
        Response::make($img->encode('jpeg'));

        $sobres->titulo_sobre = $request->titulo_sobre;
        $sobres->descricao_sobre = $request->descricao_sobre;        
        $sobres->pic = $img;
        $sobres->save();

        return redirect()->route('sobres.index')
                        ->with('success','Registro alterado com sucesso!');
    }

    public function destroy($id)
    {
        $sobre = Sobre::find($id);

        $sobre->delete();

        return redirect()->route('sobres.index')
                        ->with('success','Registro deletado com sucesso!');
    }

    public function showPictureS($id)
    {
        $sobres = Sobre::findOrFail($id);
        //dd($sobres->foto);
        $pic = Image::make($sobres->pic);

        $response = Response::make($pic->encode('jpeg'));
        //setting content-type
        $response->header('Content-Type', 'image/jpeg');

        return $response;
    }    
}

View

@extends('layouts.admin')
@section('content')

    @if ($errors->any())
        <div class="alert alert-danger">
            <strong>Opa!</strong> Tem algum problema com o campo.<br><br>
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <div class="row">
        <div class="col-lg-12">
            <a href="{{ route('sobres.index') }}"  class="btn btn-light">
                <i class="fas fa-chevron-left"></i>&nbsp;&nbsp;Voltar para lista
            </a>
        </div>
    </div>

    <br>

    <div class="row">
        <div class="col-lg-12">
            <ol class="breadcrumb">
                <li>
                    <i class="fas fa-clipboard-list"></i> Sobre
                </li>
            </ol>
        </div>
    </div>
    <div class="container">
        <form action="{{ route('sobres.update', $sobre->id) }}" method="POST">
        @csrf
        @method('PUT')
        <div class="row">
            <div class="col-xs-4 col-sm-4 col-md-4">
                <div class="form-group">
                    <strong>Título:</strong>
                    <input type="text" name="titulo_sobre" value="{{ $sobre->titulo_sobre }}" class="form-control" placeholder="Título" required>
                </div>
            </div>
            <div class="col-xs-4 col-sm-4 col-md-4">
                <div class="form-group">
                    <strong>Descrição:</strong>
                    <input type="text" name="descricao_sobre" value="{{ $sobre->descricao_sobre }}" class="form-control" placeholder="Descrição" required>
                </div>
            </div>
            <div class="col-xs-4 col-sm-4 col-md-4">
                <div class="form-group">
                    <strong>Imagem:</strong>
                    <input type="file" id="pic" name="pic" class="form-control"></input>
                </div>
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12 text-center">
              <button type="submit" class="btn btn-primary">Enviar</button>
            </div>
        </div>

    </form>
    </div>
@endsection
  • That column picis in what format blob ? after creating you can recover normally?

  • Yes, it is longblob, and I can recover normal yes!

  • can rotate a dd($file);after the $file = Input::file('pic'); of update and tell me or tell me the result. if it works, do the same thing with the store

  • Update UploadedFile {#274 ▼&#xA; -test: false&#xA; -originalName: "avengers1.jpg"&#xA; -mimeType: "image/jpeg"&#xA; -error: 0&#xA; #hashName: null&#xA; path: "C:\xampp\tmp"&#xA; filename: "phpEA34.tmp"&#xA; basename: "phpEA34.tmp"&#xA; pathname: "C:\xampp\tmp\phpEA34.tmp"&#xA; extension: "tmp"&#xA; realPath: "C:\xampp\tmp\phpEA34.tmp"&#xA; inode: 0&#xA; size: 27056&#xA; perms: 0100666&#xA; owner: 0&#xA; group: 0&#xA; type: "file"&#xA; writable: true&#xA; readable: true&#xA; executable: false&#xA; file: true&#xA; dir: false&#xA; link: false&#xA; linkTarget: "C:\xampp\tmp\phpEA34.tmp"&#xA;}

  • Store UploadedFile {#282 ▼&#xA; -test: false&#xA; -originalName: "2.jpg"&#xA; -mimeType: "image/jpeg"&#xA; -error: 0&#xA; #hashName: null&#xA; path: "C:\xampp\tmp"&#xA; filename: "phpA5A1.tmp"&#xA; basename: "phpA5A1.tmp"&#xA; pathname: "C:\xampp\tmp\phpA5A1.tmp"&#xA; extension: "tmp"&#xA; realPath: "C:\xampp\tmp\phpA5A1.tmp"&#xA; inode: 0&#xA; size: 106327&#xA; perms: 0100666&#xA; owner: 0&#xA; group: 0&#xA; type: "file"&#xA; writable: true&#xA; readable: true&#xA; executable: false&#xA; file: true&#xA; dir: false&#xA; link: false&#xA; linkTarget: "C:\xampp\tmp\phpA5A1.tmp"&#xA;}

  • When you update the other fields are updated normally ?

  • Yes, all fields update normal, only the photo that instead of showing the new photo, it deletes the old photo and leaves the field "empty" but in fact it is not empty. It gets 24 bytes.

Show 3 more comments

1 answer

1


According to what we talked on chat, the problem is related to form of editing which was missing the enctype="multipart/form-data", but when reading your code I realized that you can make some things more practical and safe, for example:

You’re using it in the views like this:

return view('sobres.create')->with('empresas', $empresas)->with('configuracoes', $configuracoes); 

You could type less using the compact();

return view('sobres.create', compact('empresas', 'configuracoes'));

I also saw that you used this command here to alert the user when an ok registration occurs:

return redirect()->route('sobres.index')
                        ->with('success','Registro deletado com sucesso!');

I use this one Laravelpnotify give a look it speeds the use of Pnotify very practical to use and apply in your project.

I saw that you are not treating the received data, in Laravel this is very quiet to do, da uma lida na documentação do Validation that you apply this in about 3 minutes.

And soon I hope I’ve helped!

Browser other questions tagged

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