Jun 6, 2023
0
Level 3
Facing problems formatting my api body in laravel
want to fix my code such that when i post my request the body must be the same as my response fix this my body
"accountNumber" : "",
"accountType": "Metlite",
"address": "9567 Uniidale",
"collectionPoint": "Main-Branch",
"firstName": "fauuso",
"gender": "male",
"identificationNumber": "69-2958546E22",
"lastName ":"test",
"mobileNumber" :"263777299986",
"sourceOfFunds": "self",
"dob": "2002-01-12"
}
my response
{
"data": [
{
"personal_info": {
"title": "Dr.",
"first_name": "Judd",
"last_name": "Daniel",
"nick_name": "easter.morissette",
"job_title": "Customer Service Representative",
"gender": "Male",
"date_of_birth": "2020-03-12",
"verification_status": null,
"photo": "https://via.placeholder.com/640x480.png/00ddcc?text=necessitatibus",
"id_number": "70688539330547"
},
"address": {
"address_type": "Work",
"is_billing": "1",
"address_line1": "91842 Konopelski Station Apt. 898",
"address_line2": "Suite 826",
"postal_zip_code": "60736",
"country_code": "CY",
"state_region": "Oklahoma",
"city_town": "Huelstad",
"status": "Active",
"address_verification_status": "Not Verified"
},
i want my body to be the same as my response my model
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use App\Models\Accounts;
use Database\Factories\UserFactory;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array<int, string>
*/
protected $fillable = [
//personal information
'title',
'first_name',
'last_name',
'nick_name',
'job_title',
'gender',
'date_of_birth',
'photo',
'id_number',
//address
'address_type',
'is_billing',
'address_line1',
'address_line2',
'postal_zip_code',
'country_code',
'state_region',
'city_town',
'status',
'address_verification_status',
//email
'email_type',
'address',
'email_verification_status',
'email_is_primary',
//phone
'phone_type',
'phone_country_code',
'number',
'phone_verification_status',
'phone_is_primary',
//security
'password',
'security_code',
'secret_question_1',
'security_answer_1',
'security_question_2',
'security_answer_2',
//preferences
'preferred_language_code',
'enable_facebook_account',
'enable_promotion_notification',
'enable_email_notification',
'enable_sms_notification',
'enable_push_notification',
'timezone',
'enable_device_authentication',
//currency
'code',
//terms_conditions
'terms_conditions_acceptance',
//geo_coordinates
'latitude',
'longitude',
'position_description',
//custom_fields
'custom_field_acceptance',
'acceptance2',
//notation
'notes',
//others
'validate',
];
/**
* The attributes that should be hidden for serialization.
*
* @var array<int, string>
*/
protected $hidden = ['password', 'remember_token'];
public function account()
{
return $this->hasOne(Accounts::class, 'user_id');
}
protected static function booted()
{
parent::booted();
static::created(function ($user) {
$account = Accounts::inRandomOrder()->first();
if (!$account) {
// Handle the case where no accounts are available
throw new \Exception('No accounts available.');
}
$account->id = $user->id;
$account->save();
});
}
/**
* The attributes that should be cast.
*
* @var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
'password' => 'hashed',
];
}
``` my store request ```<?php
namespace App\Http\Requests;
use App\Rules\ZimbabweanPhoneNumber;
use App\Rules\ZimbabweanIdNumber;
use App\Rules\DateOfBirth;
use Illuminate\Foundation\Http\FormRequest;
class UserStoreRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, \Illuminate\Contracts\Validation\ValidationRule|array|string>
*/
public function rules(): array
{
return [
// personal information
'title' => 'required',
'first_name' => 'required',
'last_name' => 'required',
'nick_name' => 'nullable',
'job_title' => 'nullable',
'gender' => 'nullable',
'date_of_birth' => ['required', 'date', 'date_format:Y-m-d'],
'photo' => 'nullable',
'id_number' => ['required', 'string', new ZimbabweanIdNumber()],
//address
'address_type' => 'nullable|integer',
'is_billing' => 'nullable|integer',
'address_line1' => 'nullable',
'address_line2' => 'nullable',
'postal_zip_code' => 'nullable',
'country_code' => 'nullable',
'state_region' => 'nullable',
'city_town' => 'nullable',
'status' => 'nullable|integer',
'address_verification_status' => 'nullable|integer',
//email
'email_type' => 'nullable',
'address' => 'nullable',
'email_verification_status' => 'nullable',
'email_is_primary' => 'nullable|boolean',
//phone
'phone_type' => 'nullable',
'phone_country_code' => 'nullable',
'number' => ['required', 'string', new ZimbabweanPhoneNumber()],
'phone_verification_status' => 'nullable',
'phone_is_primary' => 'nullable|integer',
//security
'password' => 'nullable',
'security_code' => 'nullable',
'secret_question_1' => 'nullable',
'security_answer_1' => 'nullable',
'security_question_2' => 'nullable',
'security_answer_2' => 'nullable',
//preferences
'preferred_language_code' => 'nullable',
'enable_facebook_account' => 'nullable|boolean',
'enable_promotion_notification' => 'nullable|boolean',
'enable_email_notification' => 'nullable|boolean',
'enable_sms_notification' => 'nullable|boolean',
'enable_push_notification' => 'nullable|boolean',
'timezone' => 'nullable',
'enable_device_authentication' => 'nullable|boolean',
//code
'code' => 'nullable',
//terms_conditions
'terms_conditions_acceptance' => 'nullable',
//geo_coordinates
'latitude' => 'nullable|numeric',
'longitude' => 'nullable|numeric',
'position_description' => 'nullable',
//custom_fields
'custom_field_acceptance' => 'nullable',
'acceptance2' => 'nullable',
//notation
'notes' => 'nullable',
'validate',
'validate' => 'nullable|integer',
];
}
public function headers(): array
{
return [
'lang' => $this->header('lang'),
'Time_zone' => $this->header('Time_zone'),
'Source_id' => $this->header('Source_id'),
];
}
}
``` my controller ```<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Models\Accounts;
use Illuminate\Http\Request;
use App\Models\User;
use App\Http\Requests\UserStoreRequest;
use App\Http\Resources\V1\UserResource;
use App\Http\Resources\V1\UserCollection;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*/
public function index()
{
return new UserCollection(User::all());
}
public function createUser(Request $request)
{
// Create the user
$user = User::create([
// User data...
]);
// Fetch a random account number from the accounts table
$accountNumber = Accounts::pluck('account_number')->random();
// Create the associated account with the randomly picked account number
$user->accounts()->create([
'account_number' => $accountNumber,
'card_number' => '1234567890', // Assuming a placeholder card number
]);
// Retrieve the user with the associated account
$userWithAccount = User::with('accounts')->find($user->id);
// Return the response with the user and account information
return new UserResource($userWithAccount);
}
/**
* Store a newly created resource in storage.
*/
public function store(UserStoreRequest $request)
{
return new UserResource(User::create($request->all()));
}
/**
* Display the specified resource.
*/
public function show(User $user)
{
return new UserResource($user);
}
/**
* Update the specified resource in storage.
*/
public function update(UserStoreRequest $request, string $id)
{
$request->validated();
$user = User::findOrFail($id);
$user->update($request->all());
}
/**
* Remove the specified resource from storage.
*/
public function destroy(string $id)
{
$user = User::findOrFail($id);
$user->delete();
}
}
Please or to participate in this conversation.