Home > Back-end >  Storing an image in public/images using Laravel9 Vue3
Storing an image in public/images using Laravel9 Vue3

Time:04-15

So I am currently using Laravel9 and Vue3 and I am trying to upload an image to a folder in public/images named cars_images and, after that, store the link of that image in a table called cars, in the image zone.. I am rather new to coding and I lack the knowledge to make all of this possible atm, any help would be apreciated.

Here is the component that I am trying to upload it to (PS. I have more requests in there so the addcar submit is already there , I just need help with this specific problem.

<template>
 <form
  @submit.prevent="addcar"
  enctype="multipart/form-data"
 >
   <div >
        <input
        type="file"
        
       />
   </div>

</template>

<script>
export default {
methods: {
        addcar() {
            axios
                .post("/api/addcar", this.form)

                .catch((error) => console.log(error.response.data));
        },
}
</script>

And the php file

<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Car;
use Illuminate\Http\Request;
use DB;

    // add car
    public function addcar(Request $request)
    {
        $car = new Car([            
         'image' =>$request->image,
        ]);
        $car->save();

        return response()->json('Car successfully added');
    }

And the route in routes api

Route::post('/addcar', [CarController::class, 'addcar']);

Please let me know if there is anything else I should add in order to help.

CodePudding user response:

This is a simple image save function:

 public function store(Request $request)
{
    
        $request->validate([
        'image'         =>   'required'

    ]);

    $image = $request->file('image');
    $new_name = rand() . '.' . $image->getClientOriginalExtension();
    $image->move(public_path('images'), $new_name);
 
    $form_data = array(

         'image'            =>   $new_name,
      
    );

    YOUR_MODEL::create($form_data);

    return redirect('YOUR_PAGE')->with('success', 'Image Added successfully.');
}
  • Related