#php #laravel #postman #laravel-8 #content-type
Вопрос:
Если я выберу content-type: application/json
, то я передам свои данные в тело как a raw(application/json)
, тогда мой код будет работать, что означает, что он отправляет мои данные в базу данных, но мои данные смешаны, значит, двоичные, и form-data
, если я использую content-type: multipart/form-data
его, отображается следующая ошибка. Как устранить эту ошибку?
Осветитьбазы данныхQueryException: кодом sqlstate[23000]: нарушение ограничения целостности: 1048 колонка ‘имя’ не может быть null (в SQL: вставить в
books
(name
,image
,price
,title
,quantity
,ratings
,author
,description
,user_id
,updated_at
,created_at
) значения (?, ?, ?, ?, ?, ?, ?, ?, 1, 2021-06-30 20:40:15, 2021-06-30 20:40:15)) в файле C:UsersVICKYDesktop8laravel-bookstorevendorlaravelframeworksrcIlluminateDatabaseConnection.php на линии 692
BooksController.php
<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use AppModelsBooks;
use AppModelsUser;
use AppHttpRequests;
use SymfonyComponentHttpFoundationResponse;
use AppHttpResourcesBooks as BooksResource;
use AppHttpMiddlewareAuthenticate;
class BooksController extends Controller
{
/**
* Display a listing of the resource.
*
* @return IlluminateHttpResponse
*/
public function DisplayBooks()
{
$books=Books::all();
return User::find($books->user_id=auth()->id())->books;
}
/**
* Show the form for creating a new resource.
*
* @return IlluminateHttpResponse
*/
public function AddBooks(Request $request)
{
$book=new Books();
$book->name=$request->input('name');
$book->image=$request->input('image');
$book->price=$request->input('price');
$book->title=$request->input('title');
$book->quantity=$request->input('quantity');
$book->ratings=$request->input('ratings');
$book->author=$request->input('author');
$book->description=$request->input('description');
$book->user_id = auth()->id();
$book->save();
return new BooksResource($book);
}
/**
* Display the specified resource.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function ShowBook($id)
{
$book=Books::findOrFail($id);
if($book->user_id==auth()->id())
return new BooksResource($book);
else{
return response()->json([
'error' => 'UnAuthorized/invalid id'], 401);
}
}
/**
* Update the specified resource in storage.
*
* @param IlluminateHttpRequest $request
* @param int $id
* @return IlluminateHttpResponse
*/
public function UpdateBook(Request $request, $id)
{
$book=Books::findOrFail($id);
if($book->user_id==auth()->id()){
$book->name=$request->input('name');
$book->image=$request->input('image');
$book->price=$request->input('price');
$book->title=$request->input('title');
$book->quantity=$request->input('quantity');
$book->ratings=$request->input('ratings');
$book->author=$request->input('author');
$book->description=$request->input('description');
$book->save();
return new BooksResource($book);
}
else
{
return response()->json([
'error' => ' Book is not available ith id'], 404);
}
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return IlluminateHttpResponse
*/
public function DeleteBook($id)
{
$book=Books::findOrFail($id);
if($book->user_id==auth()->id()){
if($book->delete()){
return response()->json(['message'=>'Deleted'],201);
}
}
else{
return response()->json([
'error' => ' Method Not Allowed/invalid Book id'], 405);
}
}
}
Books migration
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateBooksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('books', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->length(50)->unique();
$table->binary('image');
$table->integer('price')->unsigned();
$table->text('title');
$table->integer('quantity')->length(2)->unsigned();
$table->integer('ratings')->length(2)->unsigned();
$table->string('author');
$table->longText('description');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('books');
}
}
Books.php (model)
<?php
namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Books extends Model
{
use HasFactory;
protected $fillable = [
'name',
'image',
'price',
'title',
'quantity',
'ratings',
'author' ,
'description'
];
protected $hidden = [
'password',
'remember_token',
'updated_at'
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* @return array
*/
public function getJWTCustomClaims()
{
return [];
}
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* @return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
//inverse one to many
public function user(){
return $this->belongsTo(User::class);
}
}
Комментарии:
1. все пусто, и мы не видим кода, в котором вы заполняете подготовленное заявление
2. Предположительно, ваш код пытается прочитать JSON из входных данных, а не из данных формы. Но поскольку вы не показали нам никакого соответствующего кода, мы не можем сказать вам, в чем проблема. Пожалуйста, обновите свой вопрос
3. @ADyson, только что я обновил, пожалуйста, проверьте это один раз
4. @nbk, извините за беспокойство, только что я обновил код
5. или перейдите в консоль почтальона, чтобы просмотреть фактические заголовки отправленных запросов