Search code examples
phplaravellaravel-5.3

upload image and store with different name


There're three process should be here;

  • move the image to the folder in public path : /charts/
  • store the different name which should not same (auto number for image)
  • store the name of image into charts at columns name as file

Table Stucture: charts

enter image description here

<div class="form-group col-lg-10">
                {!! Form::label('file', 'Chart upload:') !!}
                {!! Form::file('file', null,['class'=>'form-control'])!!}
</div>

I have done much here :

public function store(Request $request)
{

        $input = $request->all();

    if($file = $request->file('file'))
    {
        $name = time() . $file->getClientOriginalName();
        $file->move('charts', $name);
        charts::create(['file'=>$name]);
    }
}

MODEL:

    class charts extends Model
{
    //
    protected $uploads = '/upload/';
    protected $fillable = ['file', 'trade_id'];
    public function getFileAttribute($photo)
    {
        return $this->uploads . $photo;

    }
}

Solution

  • {{ Form::file('file', ['class' => 'form-control']) }} - second argument must be an array ( By Default Function Prototype)

    Please check your permissions for writing in charts folder
    In Linux console, for example, use: sudo chmod 755 charts

    Also, you might change folder's owner to www-data so web server process can access that folder. In Linux console: sudo chown www-data charts

    To rename file you might use php rename( string $oldname, string $newname) function after your $file->move('charts', $name);

    $newname = 'cool-name' . $file->getClientOriginalExtension();  
    rename($name , $newname);
    

    After renaming you can save info into database To save data in database:

    DB::table('charts')->insert(
        [  'trade_id' => 12345,    // 12345 Trader id example
               'file' => $newname, // new filename
         'created_at' => time(),   // current timestamp
         'updated_ad' => time()]   // current timestamp
    );