Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Desssha's avatar

API PostMan problem try to make new hotel booking

still not solved can any one help please

this ApiHotelController

$booking = new Booking();

        $booking->room_id = $request->room_id;
        $booking->user_id = $request->user()->id;
        $booking->date_start = $request->date_start;
        $booking->date_end = $request->date_end;
        $booking->booking_number = mt_rand(1000000, 9999999);
        $booking->save();


        return['booking_number'=>$booking->booking_number];

}

this BookingResource

class BookingResource extends JsonResource { /** * Transform the resource into an array. * * param \Illuminate\Http\Request $request * return array */ public function toArray($request) { return [ 'room_id' => $this->room_id, 'booking_number' =>$this->booking_number, 'date_start' => $this->date_start, 'date_end' => $this->date_end, ]; } }

model class Booking extends Model { use HasFactory;

protected $fillable = [
    'room_id',
    'user_id',
    'booking_number',
    'date_start',
    'date_end'
];
    public function room(){

        return   $this->belongsTo(Room::class,'room_id');
    }

    public function user(){

        return  $this->belongsTo (User::class,'user_id');
    }

model users class User extends Authenticatable { use HasFactory, Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
    'name',
    'email',
    'password',
];

/**
 * The attributes that should be hidden for arrays.
 *
 * @var array
 */
protected $hidden = [
    'password',
    'remember_token',
];

/**
 * The attributes that should be cast to native types.
 *
 * @var array
 */
protected $casts = [
    'email_verified_at' => 'datetime',
];

public function bookings(){
  
    return  $this->hasMany(Booking::class);
}

public function hotels(){
    return $this->belongsToMany(Hotel::class);
}

}

0 likes
2 replies
martinbean's avatar

@desssha Read the error message. It’s telling you the problem. Your bookings table has a column called user_id. You’re not passing a value for this column, so MySQL doesn’t know what value to use for it.

Desssha's avatar

when i pass this $booking->user_id = $request->user->id; or $booking->user_id = $request->user()->id give me this errorsErrorException: Trying to get property 'id' of non-object in file C:\xampp\htd)

Please or to participate in this conversation.