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 .