Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

laradonk's avatar

Uploading Images and storing in database

I have a profile image upload field along with the other fields of a user.

            <div class="col">
                <p><i class="text-muted fa fa-photo fa-fw mr-1"></i>Photo</p>
                <label class="custom-file">
                    {{ Form::file('image', null, array('id' => 'image', 'class' => 'custom-file-control', 'placeholder' => '')) }}
                    <span class="custom-file-control"></span>
                </label>
            </div>

It works great but when it stores the item in the database it saves the image field as 'C://whatever.tmp'

I need it to store only the filename of the image and extension, as I'm saving it to the laravel app/storage/uploads folder.

Below is my controller, but I don't understand how to overwrite/modify $request->image so that when it does the storing in the database it will only use the filename instead of exactly the

response from the form.

<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Person;
use Intervention\Image\ImageServiceProvider;
use Illuminate\Support\Facades\Input;

class PersonController extends Controller
{
    public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

    $file = $request->file('image');
    $extension = $request->image->extension();
    $path = $request->image->store('uploads');

    $image = 'hi';
    $request->image = 'hi';

    Person::create($request->all());
    return redirect()->route('people.index')
        ->with('success','Item created successfully');
    }
}

All of my attempts to change the image are unsuccessful! What am I missing? EDIT: Formatting SUCKS

0 likes
11 replies
laradonk's avatar

Hi @jlrdw , the storing is fine, the problem is when adding it to the database. I did use that link to get everything working the way it is now, but I need to somehow edit $request->all() or something before it saves to the database.

As per my code even specifying

$request->image = 'hi';

Doesn't actually change it at all. I'm sure I'm missing something basic but I don't believe it is within that help page as I have scrutinized it before asking. It doesn't mention how to store it in the database at all.

MWDeveloper's avatar

@laradonk try this


public function store(Request $request)
    {
        $this->validate($request, [
            'name' => 'required',
            'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ]);

person = new person;
person->name = $request->name;

if($request->hasFile('image')){
          $image= $request->file('image');
          $filename = time() . '.' . $image->getClientOriginalExtension();
          Image::make($image)->resize(300, 300)->save( public_path('/images/' . $filename ) );
    
          $person->image= $filename;
          $person->save();
        };
          $person->save();

return redirect()->route('people.index')
        ->with('success','Item created successfully');
}


I used the image intervention

http://image.intervention.io/getting_started/installation#laravel

1 like
jlrdw's avatar

Yeah at some point tell laravel what to do

$destinationPath = ROOTDIR . 'upload/imgdogs/';
$file->move($destinationPath, $newname);

ROOTDIR is a constant I derived. Just resolve the paths correctly.

laradonk's avatar

@MWDeveloper I used that code and got a syntax error (unexpected '='). If it isn't obvious I'm still new to Laravel. I tried adding $ before person = new person; and tried making an array person[] but these all failed with syntax errors. I have intervention installed as well, I was pointed to that first but I wasn't able to get it to work following the documentation and my own basic knowledge.

@jlrdw I can save the to the proper directories but I need to modify the 'image' attribute from the $request array. (I think that is proper "Laraspeak") to be able to stop it from saving it into the database as C:\whatever.tmp regardless of where the actual file got saved.

jlrdw's avatar

modify the 'image' attribute

What are you modifing?

laradonk's avatar

@jlrdw OK so here is my form.

{!! Form::open(array('route' => 'people.store','method'=>'POST','files'=>'true')) !!}
@endsection

@section('title')
New Person
@endsection


@section('content')
@if (count($errors) > 0)
<div class="alert alert-danger">
    <strong>Whoops!</strong> There were some problems with your input.<br><br>
    <ul>
        @foreach ($errors->all() as $error)
        <li>{{ $error }}</li>
        @endforeach
    </ul>
</div>
@endif

<div class="card">
    <div class="card-header">
        <div class="form-group row">
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-user fa-fw mr-1"></i>Full Name</label>
                <input type="text" name="name" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Name">
            </div>
            <div class="col-md-2">
                <label for="status"><i class="text-muted fa fa-eye fa-fw mr-1"></i>Status</label>
                <select name="status" class="form-control">
                    <option value="0">Inactive</option>
                    <option value="1" selected>Active</option>
                </select>
            </div>
        </div>
        <div class="form-group row">
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-user-circle fa-fw mr-1"></i>First</label>
                <input type="text" class="form-control" id="first" aria-describedby="emailHelp" placeholder="First" name="first">
            </div>
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-diamond fa-fw mr-1"></i>Last</label>
                <input type="text" class="form-control" id="last" aria-describedby="emailHelp" placeholder="Last" name="last">
            </div>
        </div>
        <div class="form-group row">
            <div class="col-md-3">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-tag fa-fw mr-1"></i>Title</label>
                <input type="text" class="form-control" id="title" aria-describedby="emailHelp" placeholder="Title" name="title">
            </div>
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-building fa-fw mr-1"></i>Company</label>
                <input type="text" class="form-control" id="company" aria-describedby="emailHelp" placeholder="Company">
            </div>
            <div class="col-md-2">
                <label for="status"><i class="text-muted fa fa-sitemap fa-fw mr-1"></i>Type</label>
                <select name="type" class="form-control">
                    <option value="0">Inactive</option>
                    <option value="1" selected>Active</option>
                </select>
            </div>
        </div>
    </div>
    <div class="card-block">
        <div class="form-group row">
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-phone fa-fw mr-1"></i>Phone</label>
                <input type="text" name="phone" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Phone">
            </div>
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-envelope fa-fw mr-1"></i>Email</label>
                <input type="text" name="email" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Email">
            </div>
        </div>
        <div class="form-group row">
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-mobile fa-fw mr-1"></i>Alt</label>
                <input type="text" name="alt" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Alt">
            </div>
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-globe fa-fw mr-1"></i>Web</label>
                <input type="text" name="web" class="form-control" id="name" aria-describedby="emailHelp" placeholder="Web">
            </div>
        </div>
        <div class="form-group row">
            <div class="col">
                <p><i class="text-muted fa fa-photo fa-fw mr-1"></i>Photo</p>
                <label class="custom-file">
                    {{ Form::file('image', null, array('id' => 'image', 'class' => 'custom-file-control', 'placeholder' => '')) }}
                    <span class="custom-file-control"></span>
                </label>
            </div>
        </div>
    </div>

    <div class="card-footer text-muted">
        <div class="form-group row">
            <div class="col">
                <label for="exampleInputEmail1"><i class="text-muted fa fa-sticky-note fa-fw mr-1"></i>Notes</label>
                <textarea class="form-control" name="note" id="exampleTextarea" rows="3"></textarea>
            </div>
        </div>
    </div>
</div>
@endsection

@section('form-close')
{!! Form::close() !!}
@endsection

My controller is listed above in initial post.

If I go to the page and fill out the form and upload a valid .JPG file named "test.jpg" it is generated with a random number and filename into the "uploads" folder in my app storage. This is good.

But what is entered into the database in the image column is different. It goes as "C:\Users\x\originalfilename.tmp" This is bad. I need the data being saved in the database to match the file that Laravel created seconds before.

How do I go about this?

jlrdw's avatar

not laravel, but similar

public function add()
    {
        if (isset($_POST['submit'])) {
            echo "made it here";
            $lid = DB::table('dogs')->count();
            $lid = $lid + 1;
            $file = Input::file('ufile');
            $file_name = $file->getClientOriginalName();
            $file_ext = $file->getClientOriginalExtension();

            $fileInfo = pathinfo($file_name);
            $filename = $fileInfo['filename'];




            $newname = $filename . $lid . "." . $file_ext;
            $destinationPath = ROOTDIR . 'upload/imgdogs/';
            //Input::file('ufile')->move($destinationPath, $newname);
            $file->move($destinationPath, $newname);


            $dogpic = Cln::fixValue($newname);
            $dogname = ucfirst(Cln::fixValue($_POST['dogname']));
            $sex = ucfirst($_POST['sex']);
            $comments = Cln::fixValue($_POST['comments']);
            $adopted = (isset($_POST['adopted']) == '1' ? '1' : '0'); ///added
            $lastedit = date("Y-m-d H:i:s");
            echo "adpt=" . $adopted . "aaa";

            if (!isset($error)) {
                $postdata = array(
                    'dogpic' => $dogpic,
                    'dogname' => $dogname,
                    'sex' => $sex,
                    'comments' => $comments,
                    'adopted' => $adopted,
                    'lastedit' => $lastedit
                );

                DB::table('dogs')->insert($postdata);
            }
        }

        $this->layout = 'addtpl';
        return View::make('Dogs/Add')->shares('title', 'Dog Add');
    }

You have to resolve path correctly

MWDeveloper's avatar
Level 4

@laradonk this should do the trick


public function store(Request $request)
    {
      $this->validate($request, array(
        'name' => 'required',
        'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
      ));
      //save the data to the database
        $person  = new person ;
        $person->name = $request->name;

        if($request->hasFile('image')){
          $image = $request->file('image');
          $filename = time() . '.' . $image->getClientOriginalExtension();
          Image::make($image)->resize(300, 300)->save( storage_path('/uploads/' . $filename ) );
          $person->image = $filename;
          $person->save();
        };

      $person->save();

      return redirect()->route('people.index')
        ->with('success','Item created successfully');
    }


make sure to use this in the top of your controller


use App\Person;
use Image;

the file will be moved inside the storage folder under the uploads folder .

i the field image of the form

<div class="form-group">
    {!! form::file('image',['class'=>'form-control','placeholder'=>''])!!}
</div>

Also change


'files' => 'true' to 
'files' => true 

in the form tag

2 likes
laradonk's avatar

@MWDeveloper Thanks! I finally got a chance to play with it, your last suggestion worked perfectly. My code is like follows:

    $this->validate($request, array(
        'first' => 'required',
        'image' => 'image|mimes:jpeg,png,jpg,gif,svg|max:2048',
        ));

    $person  = new person ;
    $person->name = $request->first . ' ' . $request->last;
    $person->status = $request->status;
    $person->type = $request->type;
    $person->first = $request->first;
    $person->last = $request->last;
    $person->title = $request->title;
    $person->phone = $request->phone;
    $person->email = $request->email;
    $person->alt = $request->alt;
    $person->web = $request->web;
    $person->note = $request->note;

    if($request->hasFile('image')){
        $image = $request->file('image');
        $filename = time() . '.' . $image->getClientOriginalExtension();
        Image::make($image)->resize(160, 160)->save( public_path() . '\\media\\people\\'. $filename );
        $person->image = $filename;
    };

    $places = $request->places;
    $person->save();

It's a chore to have to list every element/variable but at least it works! Thank you so much for your help :)

Please or to participate in this conversation.