Skip to content

Instantly share code, notes, and snippets.

@jimgwhit
Created June 14, 2020 19:49
Show Gist options
  • Save jimgwhit/0e4929230cd6b7df4b274b0b04312edd to your computer and use it in GitHub Desktop.
Save jimgwhit/0e4929230cd6b7df4b274b0b04312edd to your computer and use it in GitHub Desktop.
Image upload
// In an update method
public function add()
{
    // Validate as needed
    $lid=DB::table('dc_dogs')->count();
    $lid=$lid+1;
    $file=Request::file('ufile');
    $file_name=$file->getClientOriginalName();
    $file_ext=$file->getClientOriginalExtension();

    $fileInfo=pathinfo($file_name);
    $filename=$fileInfo['filename'];
    $newname=$filename.$lid.".".$file_ext;
    $destinationPath=ASSET.'upload/imgdogs';
    $file->move($destinationPath,$newname);

    $dogpic=$newname;
    $dogname=ucfirst(Request::input('dogname'));
    $sex=ucfirst(Request::input('sex'));
    $comments=Request::input('comments');
    $adopted=!empty(Request::input('adopted'))?'1':'0';
    $lastedit=date("Y-m-dH:i:s");

    $postdata=array(
    'dogpic'=>$dogpic,
    'dogname'=>$dogname,
    'sex'=>$sex,
    'comments'=>$comments,
    'adopted'=>$adopted,
    'lastedit'=>$lastedit
    );

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

    // Redirect somewhere or whatever
}
@jimgwhit
Copy link
Author

jimgwhit commented Jun 14, 2020

Notes:

This line:

$newname=$filename.$lid.".".$file_ext;

Is how I give new name, basically

Name + current db count + 1 + . + extension. But name however you need to.

This line:

$destinationPath=ASSET.'upload/imgdogs';   **Use your storage path**

ASSET is a constant, since sometimes in shared host I can sometimes pick a certain folder in the file system.
In example it's just:

define('ASSET', realpath(dirname(__FILE__)). DS . 'assets' . DS);

So above is uploaded to assets/upload/imgdogs Of course replace with your upload location.
Where DS is

defined('DS') || define('DS', DIRECTORY_SEPARATOR);

I put a few custom constants in index.php

Also behind the scenes, Symfony components are used which in turn uses PHP's

move_uploaded_file

Reference: https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/File/UploadedFile.php

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment