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',
];
}