Yousef Altaf
Yousef Altaf

Reputation: 2763

how to store the image name without the path - laravel

What is the right way to store my images to database

should I store the fill path of the image like so images/pagesImages/image.jpg or the right way is store only the image name and write the path where the image should appear?

I am new to Laravel and I am updating image on the page when I updated the image I found that the full path was stored on the database

can I store only the image name without the path?

here is my controller

public function editAboutImage()
    {
        $id = 1;
        $image = Text_area::find($id);

        $validation = Validator::make(Input::all(), [
            'image' => 'sometimes|image|mimes:jpeg,png|min:1|max:250'
        ]);

        if ($validation->fails()) {
            return Redirect::to('edit-about')->with('errors', $validation->errors());
        }
        if (Input::hasFile('image')) {
            $file = Input::file('image');
            $destination_path = 'images/pagesImages/';
            $filename = str_random(6) . '_' . $file->getClientOriginalName();
            $file->move($destination_path, $filename);
            $image->image = $destination_path . $filename;
            $image->save();
        }
        return Redirect::to('edit-about')->with('message', 'You just updated an image!');
    }

clarify my two questions

  1. which is the better way to store images should I store it with path or just the image name.
  2. if I need to store the image name only without the path what should I do with my controller.

many thanks

Upvotes: 0

Views: 2665

Answers (2)

Tobi
Tobi

Reputation: 16

This might be a very late answer but for those that come accross it. When you call the store method

$request->file('image')->store('',YourBaseFolderName);

This will save the folder in the folder you want, for example public/images, would be

$request->file('image')->store('','images');

and only the file name would be returned

Upvotes: 0

Rama Durai
Rama Durai

Reputation: 750

  1. Just store image name only. Because, if you are going to changing the path, then you can easily get by file name. If also changing the file to new path.
  2. You can use your model to simply store the file (my suggestion)

    in your model, create one variable and one function to store image
    For model:-

     public static $imagePath = 'images/profile_images';       
    
     public function getImageAttribute($value)       
     {
        if($value != ''){
            return self::getImagePath . '.' . $value;
        }
     }
    
     public function getImagePath()       
     {
            return self::imagePath;
     }       
    

    For controller:-

    get as usual file name,
    At the storage

    $file->move($this->getImagePath(), $filename);        
    $image->image = $filename;         
    

    Try this and said result

Upvotes: 3

Related Questions