简体   繁体   中英

How to save image path into database in Laravel?

I want to upload an image and retrieve in from database when i need this.My code is perfectly working to upload image but it's path did not save in database.In database it's showing Null .Here is my code:

    if ($request->hasFile('profilePic')) {
        $file = array('profilePic' => Input::file('profilePic'));
        $destinationPath = 'img/'; // upload path
        $extension = Input::file('profilePic')->getClientOriginalExtension(); 
        $fileName = rand(11111,99999).'.'.$extension; // renaming image
        Input::file('profilePic')->move($destinationPath, $fileName);
    }else{
        echo "Please Upload Your Profile Image!";
    }
    $profile->save();

My Question:

  • How to save image path into database?
  • And how to retrieve image from database?

Updated: Profile.php

class Profile extends Model
{
    protected $table = "profiles";
    public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
}

In your code there should be like this:

$profile->profilePic = $fileName;

& then

$profile->save();

try this

$path = $file->getRealPath();;
    $pos = strpos($path,'/public/');
    if ($pos !== false) {
        $path = substr($path, $pos + 1);
    }
    $input['file'] = $path;

1.How to save image path into database?

To save your full image path in a database field, the code is:

$profile->profilePic = $destinationPath.$fileName;
$profile->save();


2.And how to retrieve image from database?

In your view file using blade engine, write HTML code like this. In the image src you have to provide profilePic data as shown in the below HTML code:

<img src="{{asset($profile->profilePic)}}"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM