Cannot use a scalar value as an array - Laravel - php

I'm trying to create a function in laravel, but when I send a post request the data is updated successfully but I get cannot use a scalar value as an array error.
Route:
Route::post('transfer-gate-request/{id}',[GateRequestController::class,'transferRequest']);
Request: POST: http://127.0.0.1:8000/api/transfer-gate-request/333
if I switch to PUT route & request, I get Undefined array key "gate_department_id" error
// Transfer Requests
public function transferRequest(Request $request, $id)
{
$user = Auth::user();
if ($user->role_id == 4 || $user->role_id == 3) {
$postData = $request->all();
$gate_department=GateDepartment::where('id', $postData['gate_department_id'])->first();
$data = GateRequest::where('id',$id)->update([
'gate_department_id' => $postData['gate_department_id'],
'department' => $gate_department->name,
'waiting_of_approval' => $gate_department->first_approver_id,
'approved_first' => null,
'approved_second' => null,
'approved_third' => null,
'first_approve_time' => null,
'second_approve_time' => null,
'third_approve_time' => null,
'approve_counter' => 0,
]);
$data['status'] = 1;
$data['message'] = 'Gate request transferred successfully!';
return response()->json($data);
} else {
$data['gate_request'] = null;
$data['message'] = 'You are not authroized to check gate requests';
$data['status'] = 1;
return response()->json($data);
}
}

Related

pass parameters in the url and return a data in the blade

I'm having trouble doing something that should be very simple.
I'm reading documentation, looking at posts and it just doesn't work.
I need to return parameters in the url and I need to return data to the blade.
I saw that with the redirect method you can return, which is the method I'm using. But I can't get the data on the blade
public function confirmEmail(Request $request)
{
// Step one
// Check the recaptcha
$recaptcha = GoogleReCaptchaV2::verifyResponse($request->input('g-recaptcha-response'))->isSuccess();
if (!$recaptcha) {
flash('Recaptcha invalido. Tente novamente')->error();
return view('login');
// return view('login', ['error' => 1, 'recaptcha' => $recaptcha]);
// return redirect()->route('login', ['error' => 1, 'recaptcha' => $recaptcha]);
}
// Step two
// Check email
$email = $request->input('email');
$validator = Validator::make($request->all(), [
'email' => 'required|max:255'
]);
if ($validator->fails()) {
return view('login')->withErrors($validator->errors());
}
// Step three
// Generate code and send mail
$result = User::sendCode($email);
if ($result['message'] != 'success') {
flash($result['message'])->error();
return view('login');
}
return redirect()->route('login', ['error' => 0, 'stepIndex' => 2, 'formType' => 'login', 'email' => $result['user']['email']])->with(['email', $result['user']['email']]);
}
My blade
{{ session()->get('email') }}
{{ $email ?? null }}

array_map(): Expected parameter 2 to be an array, null given Laravel 8 form validation

I'm using Laravel 8 as a backend to my SPA front-end, I've done countless number of validation features before and have never bumped into this strange issue with the validator, I'm getting:
array_map(): Expected parameter 2 to be an array, null given
And the main error logged is:
[2022-06-27 19:44:11] local.ERROR: array_map(): Expected parameter 2 to be an array, null given {"userId":1,"exception":"[object] (ErrorException(code: 0): array_map(): Expected parameter 2 to be an array, null given at C:\\Users\\Ryan\\Desktop\\web-projects\\domain-monitor\\domain-monitor-api\\vendor\\laravel\\framework\\src\\Illuminate\\Validation\\ValidationRuleParser.php:92)
What am I missing from my function?
/**
* Display the specified resource.
*
* #return \Illuminate\Http\Response
*/
public function show(Request $request, $uuid)
{
$validator = Validator::make($request->all(), [
'use_filters' => `boolean`
]);
$validator->sometimes('period', 'integer|in:24,48,72,168,720,1440', function ($input) {
return $input->use_filters == true;
});
$validator->sometimes('mode', 'string|in:exact,average', function ($input) {
return $input->use_filters == true;
});
$validator->sometimes('device', 'string|in:mobile,desktop', function ($input) {
return $input->use_filters == true;
});
if ($validator->fails()) {
return response()->json([
'message' => 'It looks like you missed something',
'errors' => $validator->errors()
], 400);
}
$monitor = Monitor::where('user_id', Auth::id())
->where('uuid', $uuid)
->first();
if (!$monitor) {
return response()->json([
'success' => false,
'message' => 'We can\'t find this monitor'
], 404);
}
// if in filtering mode
if ($request->boolean('use_filters')) {
$period = $request->input('period') ?? 24;
$mode = $request->input('mode') ?? 'average';
$device = $request->input('device') ?? 'desktop';
if (intval($period) > 168 && !Auth::user()->is_subscribed) {
return response()->json([
'success' => false,
'message' => "You must upgrade your account to the Pro subscription to view more historical data."
], 400);
}
// add our uptime checks to our monitor
try {
if ($monitor) {
$monitor['charts'] = $this->getCharts($monitor, $period, $mode, $device);
}
} catch (\Exception $e) { }
}
return response()->json([
'message' => 'Your monitor',
'monitor' => $monitor
], 200);
}

How to validate if user already exists?

I want to validate if it already exists in the DB, so then show an error message. But I am always getting user already exists in both cases. How can I fix it?
Below is my code:
public function add(Request $request)
{
$request_data = $request->all();
$customer_ids = $request_data['ids'];
$campaigns_id = $request_data['campaigns_id'];
$customer_id_array = explode(',', $customer_ids);
$whereIn = $customer_id_array;
$check_customer = Participant::where('id', $campaigns_id)->whereIn('customer_id', $whereIn)->get();
if (!empty($check_customer)) {
return ['code' => 402, 'status' => 'error', 'data' => $check_customer, 'message' => 'Customer Already Exists'];
}
foreach ($customer_id_array as $key => $value) {
$participantObj = new Participant;
$participantObj['customer_id'] = $value;
$participantObj->campaign_id = $campaigns_id;
// $participantObj->pin_number = $this->randomNumber(3).''.$key;
$data = $participantObj;
$data ->save();
}
return['code' => 200, 'status' => 'success'];
}
Change this line
if (!empty($check_customer)) {
to
if ($check_customer->isNotEmpty()) {

how to logout from rest api in yii2

I m calling logout api in yii2 framework using logout action
url :http://localhost/mobile/public/api/v1/logout
Code:
public function actionLogout()
{
$user_t = Yii::$app->user->logout();
return $this->apiItem(array(),'Logout Successfully');
}
but after calling logout api
when after this i calling view profile api it returns user data
public function actionViewprofile()
{
$user = Yii::$app->user->identity;
$profile_fetch = [
'firstname' => $user['member_fname'],
'lastname' => $user['member_lname'],
'gender' => $user['member_gender'],
'dateofbirth' => $user['member_dob']
];
return $this->apiItem($profile_fetch);
}
where apitem is a function for json parameter format
/**
* Api Item response
*/
public function apiItem($data, $message = false,$flag = false )
{
Yii::$app->response->statusCode = 200;
return [
'statusCode' => 200,
'message' => $message ? $message : 'Data retrieval successful',
'data' => $data,
'flag' => $flag
];
}
Clear the token from DB and clear the user session
$userID = Yii::$app->session->get('userID');
$userModel = User::find()->where(['id'=>$userID])->one();
if(!empty($userModel))
{
$userModel->token=NULL;
$userModel->save(false);
}
Yii::app()->user->logout(false);

REST API Request parameter validation Laravel

I am new to API with Laravel. I am trying to validate parameters sent into POST request through the Laravel's validate method.
Following data is the only parameter I am sending through the POST request. I want to validate device_id for uniqueness using Laravel's validate method.
data => {"device_id":"xxxxxx2C-9EA3-4FFB-B26D-E8E483xxxxxx","password":"ANVp285x","user_type":"1"}
I can validate the only data parameter however there is no proper response or error message it's throwing exception. My main motive is to validate device_id, password and user_type.
Here's my controller's store
public function store(Request $request) {
try {
$result = $this->validate($request, [
'data' => 'required',
// 'data.device_id' => 'required|unique:users|max:60',
// 'data.password' => 'required|min:6|confirmed',
// 'data.user_type' => 'required',
]);
$user = new User;
// Parameters from request
$data = json_decode($request->data, TRUE);
$user->device_id = $data['device_id'];
$user->password = bcrypt($data['password']);
$user->u_type = $data['user_type'];
// Parameters to be generated
$user->qr_code_image = "test_qr_code.png";
$user->access_code = MyHelper::generate_access_code();
$user->save();
$user = User::find($user->id);
$result = Fractal::item($user, new UserTransformer)->getArray();
if (!empty($result['data'])) {
$result['status'] = TRUE;
$result['message'] = 'Success';
} else {
$result['status'] = FALSE;
$result['message'] = 'Failed';
}
} catch (\Exception $e) {
$result['status'] = FALSE;
$result['message'] = 'Failed';
}
return $result;
}
You can use Illuminate\Support\Facades\Validator to validate requests in your API:
$validator = Validator::make($request->all(), [
"device_id" => "required|unique:devices",
"user_type" => "required",
"password" => "required",
]);
if ($validator->fails()) {
return response(
$validator->errors(),
400
);
}
I found the solution I did this with below approch,
$data = $request->data;
$data = json_decode($data, TRUE);
$status = 200;
$validator = Validator::make(
array(
"goal_title" => $data['goal_name'],
"family_id" => $data['family_id'],
"goal_frequency" => $data['goal_frequency'],
), array(
"goal_title" => "required|regex:/(^[A-Za-z0-9 ]+$)+/|:family_goals",
"family_id" => "required",
"goal_frequency" => "required:goal_frequencies",
)
);

Categories