Home > Back-end >  Laravel: Storing image custom name to db
Laravel: Storing image custom name to db

Time:02-11

I want to store a file name to my db so it can retrieve that image and display it, I have implemented something that prevents files with the same name being added to my images folder by adding the time of upload in front of the actual file name as seen in the '$newImageName' variable, my question is how do I pass the '$newImageName' to be stored as that in the db given with the current code I have?

public function store(Request $request)
{
    $this->validate($request, [
        'subject' => 'required|min:5',
        'tags' => 'required',
        'thread' => 'required|min:25',
        'image' => 'required|mimes:png,jpg,jpeg'
    ]);

    $newImageName = time() . '-' . $request->subject . '.' . $request->image->extension();

    $request->image->move(public_path('images'), $newImageName);

    $thread = auth()->user()->marketthreads()->create($request->all());

    $thread->tags()->attach($request->tags);

    return back()->withMessage('Market thread has been created');

Any help will be highly appreciated

Thank you :)

CodePudding user response:

You need to create a table in your database for storing the images. In your table, you basically need an ID and the name of the image file in your storage, in your case called $newImageName. You can do this by migration as below:

Schema::create('images', function (Blueprint $table) {
    $table->increments('id');
    $table->string('filename');
    $table->timestamps();
});
  • Tip: the timestamp store your image creation time so you wouldn't need to store it in your filename. Instead, later after the creation of the item, you can retrieve the ID generated by the new Object to use for your filename in order to prevent overwriting. This is a bit more secure approach as there is a nuance possibility of simultaneous uploads with the same name.

In your controller whenever you are uploading a new item, do accordingly:

$image = new Image();
$image->filename = $newImageName;
$image->save();

This will save the Image filename in your DB for further usage.

  • Tip: If you want to go further on creating a more structured design, you can go ahead and create a Model for your Image and attach them to your other Models, in case of retrieving them in an easier way.
  • Related