Gabotronix's avatar

Storing images in public folder via AJAX POST

Hi, I'm making an admin panel for a personal project as a means to studying laravel framework, so far I'm loving it!

I came up with a issue where I don't know how to store the uploaded image into my app (I'd like to use public folder instead of other storage despite being less secure), I have my folder called uploads inside public.

This is my AJAX POST call:

$('.form_store_button').click(function(){
        
        var linked_entry = $(this).attr("data-link");
        var form = $(this).closest('form');
        
        
        
        
        $.ajaxSetup({
            headers: { 'X-CSRF-Token' : $('meta[name=csrf-token]').attr('content') }
        });
        

        switch(linked_entry) {
            
            case "sliders":
            
                console.log('new slider button clicked');
                
                var formData = new FormData();
                formData.append('title', form.closest($("input[name='title']").val()));
                formData.append('body', form.closest($("textarea[name='body']").val()));
                formData.append('image', form.closest($("input[name='image']").prop('files')[0]));
                formData.append('isVisible', form.closest($("input[name='isVisible']").is(':checked') ? 1 : 0));

                
                $.ajax({

                async: true,
                url: '/sliders',
                type: 'POST',
                data: formData,
                dataType: 'JSON',
                processData: false,
                contentType: false,
            
                success: function (data) { 
                    $('.form_valid_container').html('<span class="form_valid_text">✓ '+ data.success +'</span>');
                    form.trigger("reset");
                    console.log(data.success, data.errors);
                },
            
                error: function (data){
                    var errors = data.responseJSON;
                    console.log(errors);
                
                    $.each(errors , function(){
                        $('.form_error_container').html('<span class="form_error_text">✘ '+ errors.message +'</span>')
                    }); 
                }
                
                
                });

            break;
                    
                    

            default:
                        
        }
                
    });

My resource controller:

public function store(StoreSlider $request)
    {
        
        
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $request->file('image');
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json($slider);
    }

Migration where I create sliders table:

//CREATE SLIDERS TABLE
        Schema::create('sliders', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title')->nullable();
            $table->string('body')->nullable();
            $table->string('image');
            $table->boolean('isVisible')->default(true);
            $table->timestamps();
        });
        //FILL SLIDER TABLE WITH DUMMY POSTS
        DB::table('sliders')->insert([
            'title' => config('globals.slider_title_1'),
            'body' => config('globals.slider_body_1'),
            'image' => config('globals.slider_image_1'),
            'isVisible' => true,
        ]);
        DB::table('sliders')->insert([
            'title' => config('globals.slider_title_2'),
            'body' => config('globals.slider_body_2'),
            'image' => config('globals.slider_image_2'),
            'isVisible' => true,
        ]);
        DB::table('sliders')->insert([
            'title' => config('globals.slider_title_3'),
            'body' => config('globals.slider_body_3'),
            'image' => config('globals.slider_image_3'),
            'isVisible' => true,
        ]);

Form Request for storing my sliders:

public function rules()
    {
        return [
            
            'title' => 'required|min:5|max:100',
            'body' => 'required|min:10|max:250',
            'image' => 'required | mimes:jpeg,jpg,png | max:2000',
            
        ];
    }
0 likes
1 reply
beetuco's avatar
beetuco
Best Answer
Level 9

So you're actually trying to store the image straight into the database which isn't going to work unless the column is of Binary Data\Medium+ BLOB type and DBA's all around the world will just turn in their graves .. ok I did it about 3 years ago and am ashamed of it still (omgosh this is public record now)!

Have a look at File Uploads

With the Storage facade for instance you would save the file to the folder and get the path with a generated unique filename

$path = Storage::putFile('thumbnail-images', $request->file('start_image'));

Then save that path to the database.

And yes, storing in the public folder is dangerous. Living on the edge!

So for example, using the local storage driver as you mentioned the public folder previously.


public function store(StoreSlider $request)
    {
        
        $imagePath = Storage::disk('local')->putFile('uploads', $request->file('image'));
        
        $slider = new Slider();
        $slider->title = $request->title;
        $slider->body = $request->body;
        $slider->image = $imagePath;
        $slider->isVisible = $request->isVisible;
        $slider->save();
        
        return response()->json($slider);
    }

You could then use Storage::url($slider->image); to get the url for the photo.

Please or to participate in this conversation.