i’m building an API with laravel8 and want to upload image for posts , and when i don’t send values for posts fields in postman , gives me this error :
call to a member function extension() on null
and when i send values for fields , gives this error :
"error": { "images": [ "validation.uploaded" ] },
i changed the size of uploaded files in php.ini
but it wasn’t fixed.
so as you can see , my validation doesn’t work when i don’t enter values for the fields
my codes :
post table :
public function up() { Schema::create('posts', function (Blueprint $table) { $table->id(); $table->unsignedBigInteger('category_id'); $table->unsignedBigInteger('user_id'); $table->string('title'); $table->longText('body'); $table->string('video')->nullable(); $table->string('study_time'); $table->string('images'); $table->integer('likes')->nullable(); $table->tinyInteger('status')->nullable()->comment('status is 1 when a post is active and it is 0 otherwise.')->nullable(); $table->text('tags')->nullable(); $table->foreign('category_id')->references('id')->on('categories'); $table->foreign('user_id')->references('id')->on('users'); }); }
and store()
method in PostController
:
public function store(Request $request ) { $data = $request->all(); $validator = Validator::make($data, [ 'user_id'=>'required', 'category_id'=>'required', 'title' => 'required|max:100|unique:categories', 'body' => 'required|max:500', 'study_time'=>'required', 'images' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048', ]); $imageName = time().'.'.$request->images->extension(); $request->images->move(public_path('images'), $imageName); if ($validator->fails()) { return response()->json(['error' => $validator->errors(), 'Validation Error']); } $post = Post::create($data); return response()->json([ "success" => true, "message" => "successfully", "data" => $post ]); }
thank you for you help .
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
It seems that your image is not being uploaded to Laravel, How do you sent your image file to Laravel server?
If you are using VueJS remember to use Formdata more info here.
If a natural form make sure that your image is being sent through by inspecting dev tools on your browser.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0