0

hope you doing well.

I've been fighting with this more than a week and i can't seem to find an answer or solution.

I'm trying to store an image to the database using react and laravel.

The thing is im getting always 'null' on the database.

I've tried many things and i can't seem to find the right answer.

I want to store the image as a string on the database using react and have stored too on the public folder on laravel, so i can call it on react after.

I already used 'php artisan storage:link' , and created manually a folder to store it in laravel.

In the postman everything is fine, but because he store it as a string directly, so i think the problem might be on react and how he sends the (file,data,image) to laravel.

Any information will be appreciated. Thank you for your time guys !.


Here is the controller used.

public function store(Request $request)
{
    $validator=FacadesValidator::make($request->all(), [
        'username' => 'required|max:255',
        'email' => 'required|email|max:255',
        'password' => 'required|min:8',
    ]);

    if($validator->fails()){
        return response()->json([
            'error' => $validator->getMessageBag()
        ],202);
        
    }
    else {
        $user = new User;
        $user->username = $request->input('username');
        $user->email = $request->input('email');
        $user->password = $request->input('password');
        if($request->hasFile('file'))
        {
            $file = $request->file('image');
            $extension = $file->getClientOriginalExtension();
            $filename = time() .'.'.$extension;
            $file->move(public_path('uploads/images/'), $filename);
            $user->file = 'uploads/images/'.$filename;
        }
        $user->save();

        return response()->json([
            'status' => 200,
            'message' => 'User added succesfully',
        ]);
    }
}

Migration file

 public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('username')->unique();
        $table->string('email')->unique();
        $table->string('file', 2048)->nullable();
        $table->string('type')->default(2);
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
});
}

React code

const [registerInput, setRegister] = useState({
    username: "",
    email: "",
    password: "",
    confirmed: "",
    error_list: [],
});

const handleInput = (e) => {
    setRegister({ ...registerInput, [e.target.name]: e.target.value });
}
const [imagedata, setImagedata] = useState("");

const handleImage = (file) => {
    setImagedata(file[0]);
};


const registerSubmit = async (e) => {
    e.preventDefault();

    const data = new FormData();
    data.append("image", imagedata);
    data.append("username", registerInput.username);
    data.append("email", registerInput.email);
    data.append("password", registerInput.password);
    data.append("confirmed", registerInput.confirmed);
    
    await axios.post('http://127.0.0.1:8000/api/register', data).then(res => {

        if (res.data.status === 200) {

            localStorage.setItem('auth_name', res.data.username);
            localStorage.setItem('auth_token', res.data.token);
            swal({
                title: "Welcome!",
                text: "You are now registered!",
                icon: "success",
                button: "Continue...",
            });
            history.push('/section');
            setRegister({
                username: '',
                email: '',
                password: '',
                confirmed: '',
                file: '',
            });
        }
        else {
            setRegister({ ...registerInput, error_list: res.data.validation_errors });
        }

    });

}

input code

 <div class="user signupBx">
                    <div class="imgBx"><img src={map1} /></div>
                    <div class="formBx">
                        <form onSubmit={registerSubmit}>
                            <h2>Create an account</h2>
                            <input type="text" placeholder="Username" name='username' onChange={handleInput} value={registerInput.username} />
                            <span className="text-danger">{registerInput.error_list.username}</span>
                            <input type="text" placeholder="Email Adress" name='email' onChange={handleInput} value={registerInput.email} />
                            <span className="text-danger">{registerInput.error_list.email}</span>
                            <input type="password" placeholder="Create Password" name='password' onChange={handleInput} value={registerInput.password} />
                            <span className="text-danger">{registerInput.error_list.password}</span>
                            <input type="password" placeholder="Confirm Password" name='confirmed' onChange={handleInput} value={registerInput.confirmed} />
                            <span className="text-danger">{registerInput.error_list.confirmed}</span>
                            <input type="file" name='image' id='image' onChange={e => handleImage(e.target.files)} />
                            <input type="submit" value="Sign up" />
                            <p class="signup">Already have an account? <a href="#" onClick={toggleForm}>Sign in.</a></p>
                        </form>
                    </div>
                </div>
Babaduk98
  • 1
  • 2
  • Maybe the answer here will solve your problem: https://stackoverflow.com/questions/43013858/how-to-post-a-file-from-a-form-with-axios – aceraven777 Apr 16 '22 at 15:54

1 Answers1

1

Your form needs to be enctype=multipart/form-data.