I am trying to update values in laravel. I have a userupdate profile api which I can update the values first time with given parameters and their values but 2nd time when I update same values it gives me user profile does not exist.
My Code is :
public function UpdateUserProfile(Request $request)
{
$id = $request->input('id');
$client_gender = $request->input('client_gender');
$client_age = $request->input('client_age');
$client_weight = $request->input('client_weight');
$client_height = $request->input('client_height');
$client_dob = $request->input('client_dob');
$profile= DB::table('clients')
->where('id',$id)
->update(['client_gender'=>$client_gender,'client_age'=>$client_age,'client_height'=>$client_height,'client_weight'=>$client_weight,'client_dob'=>$client_dob]);
if($profile)
{
$resultArray = ['status' => 'true', 'message' => 'User profile updated Successfully!'];
return Response::json( $resultArray, 200);
}
$resultArray = ['status' => 'false', 'message' => 'User profile does not exist!'];
return Response::json($resultArray, 400);}
first time when I update the value it gives me the response like this:
{
"status": "true",
"message": "User profile updated Successfully!"
}
and when I hit the update request through a postman it gives a 400 Bad request and response is :
{
"status": "false",
"message": "User profile does not exist!"
}
I'd recommend rewriting that function to look like the following; mostly because it reads better and uses the Model methods that are more commonly found in Laravel
public function UpdateUserProfile(Request $request)
{
// this code fails if there is no client with this id
$client = App\Client::findOrFail($request->id);
// attach new values for all of the attributes
$client->client_gender = $request->input('client_gender');
$client->client_age = $request->input('client_age');
$client->client_weight = $request->input('client_weight');
$client->client_height = $request->input('client_height');
$client->client_dob = $request->input('client_dob');
// save
$client->save();
return ['status' => 'true', 'message' => 'User profile updated Successfully!'];
}
Related
On Laravel site using jenssegers/mongodb I have store method like :
public function store(ItemRequest $request)
{
$request = request();
try {
$session = DB::getMongoClient()->startSession();
$session->startTransaction();
$insertData = $request->all();
$insertData['published'] = ! empty($insertData['published']);
$item = Item::create([
'title' => $insertData['title'],
'text' => $insertData['text'],
'published' => $insertData['published'],
]);
$session->commitTransaction();
} catch (Exception $e) {
$session->abortTransaction();
return back()->withErrors(['message' => $e->getMessage()]);
}
return redirect(route('admin.items.edit', $item->_id))
->with('message', 'New item was successfully added')
->with('message_type', 'success');
}
But making test for this controller method I did not find how to get ID on new ite, generated on mongodb site :
public function testIsItemEditFormSubmittedWithSuccess()
{
$this->withoutMiddleware();
$item = \App\Models\Item::factory(Item::class)->make();
// Test Action
$response = $this->actingAs(self::$loggedAdmin, 'web')->post(route('admin.items.store'), $item->toArray());
$newItemId = DB::getPdo()->lastInsertId();
// If to uncomment line above I got "Error: Call to a member function lastInsertId() on null"
$response->assertStatus(302); // Redirection status
$response->assertRedirect(route('admin.items.edit', [???])); // HOW can New ID on "store" method above ?
$response->assertSessionHasNoErrors();
}
Any equvalent of lastInsertId for jenssegers/mongodb ?
"jenssegers/mongodb": "^3.9.2",
"laravel/framework": "^9.30.1",
Thanks in advance!
Check this issue.
https://github.com/jenssegers/laravel-mongodb/issues/2451
Your laravel should be 9.31. So downgrade it to 9.30 and wait next release.
The built in behavior for flashing back validation errors in Laravel does not seem to be working for my use case.
I have a (React) form that posts it's data via fetch API using this method, which reloads or redirects the page with (hopefully) any session data after the response is returned:
fetch(props.register_route, {
method: 'POST',
headers: {
'X-CSRF-Token': props.csrf,
},
body: data,
})
.then((result) => {
return result.json();
})
.then((result) => {
console.log(result);
window.location.href = result.url;
},
(error) => {
console.log(error);
});
In my controller, I validate this data but if I structure it as follows, the errors are not available as $errors in the resulting page
if ($validator->fails()) {
return redirect()->back()->withErrors($validator);
}
However if I manually flash the errors to the session and return a url instead of a redirect, suddenly the behavior works.
if ($validator->fails()) {
Session::flash('errors', $validator->errors());
return response->json([
'url' => route('register'),
], Response::HTTP_NOT_ACCEPTABLE);
}
I feel as if I must be doing something incorrectly here to have to use this workaround. I could also manually send the errors back in the response, which may be the right way to structure things in the long run.
when you are calling api from javascript or front end applications like Reactjs,Angular,android etc.. .So it expect return result should be in json format so it should be like
if ($validator->fails()) {
return response()->json( $validator->errors(),422);
}
if you not calling Method from direct laravel blade then pass response in JOSN Format.
like
https://laravel.com/docs/8.x/responses#json-responses
Or
make one ResponseManager File
<?PHP
namespace App\Libraries\utils;
class ResponseManager {
public static $response = array('flag' => true, 'data' => '', 'message' => '', 'code' => 01,);
public static function getError($data = '', $code = 10, $message = '', $flag = false) {
self::$response['flag'] = $flag;
self::$response['code'] = $code;
self::$response['data'] = $data;
self::$response['message'] = $message;
return self::$response;
}
public static function getResult($data = '', $code = 10, $message = '', $flag = true) {
self::$response['flag'] = $flag;
self::$response['code'] = $code;
self::$response['data'] = $data;
self::$response['message'] = $message;
return self::$response;
}}
Define in config/app.php
//custom class
'ResponseManager' => App\Libraries\utils\ResponseManager::class,
and then use in whole project
Error Message Like
if ($validation->fails()) {
$message = $validation->messages()->first();
return Response()->json(ResponseManager::getError('', 1, $message));
}
Success Message Like
return Response()->json(ResponseManager::getResult(null, 10, "Success"));
Unable to get response while response object is empty. Works perfect when the object has data returned.
public function show($id)
{
$associates = Associate::find_by_id($id);
if(count($associates)<1)
{
$output = array('message' => 'No Records Found');
$status = 204;
}
else{
$output = array('message' => 'success','data'=>$associates);
$status = 200;
}
return response()->json($output,$status);
}
There is no response when the $associate object is empty.
Response when $associate is not empty:
{
"message": "success",
"data": [
{
"first_name": "xxx",
"last_name": "xxx",
"mobile": xxxxxxxxxx,
"email": "xxxxxx#xxxxx",
"city": "xxxxx",
"state": "xxxxxx",
"pincode": "xxxxx"
}
]
}
I had the same issue for status code 204 .
I believe this is caused here. The Illuminate\Foundation\Application class is then catching this and throwing an HttpException.
I believe the simplest fix would be to make the controller return the following instead:
return Response::make("", 204);
Returning a empty message.
check status_code in your code to display message in frontend .
It will be easier if you use route model binding to find the ID of the record. For more information check https://laravel.com/docs/5.7/routing#route-model-binding.
I think the snippet below should work.
if ($associates) {
$output = array('message' => 'success','data'=>$associates);
$status = 200;
} else {
$output = array('message' => 'No Records Found');
$status = 204;
}
I've rewrote the function for your reference.
BTW. If the function return only one record, use singular noun for variable name in general.
public function show($id)
{
// Use find() instead of find_by_id()
$associate = Associate::find($id);
// $associate will be null if not matching any record.
if (is_null($associate)) {
// If $associate is null, return error message right away.
return response()->json([
'message' => 'No Records Found',
], 204);
}
// Or return matches data at the end.
return response()->json([
'message' => 'success',
'data' => $associate,
], 204);
}
How do get the related user table of a newly created Contact model and then in the response header content-length out put it toJson().
public function store(Request $request) {
try {
$contact = new Contact();
$contact->email_address = Helper::strip_tags($request->get('email_address'));
$contact->firstname = ucfirst($request->get('firstname'));
$contact->lastname = ucfirst($request->get('lastname'));
$contact->company = ucfirst($request->get('company'));
$contact->phone = $request->get('phone');
$contact->mobile = $request->get('mobile');
$contact->description = Helper::strip_tags($request->get('description'));
if($contact->save()) {
// here is the part I'm having trouble with
$contact = $contact->with('user')->get();
return response()->json($contact, 200, ['Content-Length' => strlen($contact->toJson())]);
} else {
return response()->json(array('error' => true, 'messages' => $contact->errors), 400);
}
} catch(Exception $e) {
return response()->json(array('error' => true, 'type' => 'exception', 'message' => $e->getMessage()), 500, ['Content-Length' => $e->getMessage()]);
}
As you already have the model loaded (when you created it) you wouldn't use with() as it is for eager loading relationships.
If I understand you question correctly, to get the User relationship included in the output you would instead use lazy eager loading which would look like:
$contact->load('user');
Why $this->post('username') can not read input from rest client ?
In my controller for server :
function login_post(){
$data['username']=$this->post('username');
$data['password']=$this->post('password');
if ($this->get('cobak')==1) {
$cek = $this->model_user->ambilPengguna($data);
}
if ($cek) {
$this->response($cek, 200); // 200 being the HTTP response code}
else {
$this->response(array('error' => 'User could not be found'), 404);
}
}
My models :
public function ambilPengguna($data) {
$this->db->select('*');
$this->db->from('tbl_user');
$this->db->where($data);
$query = $this->db->get();
return $query->num_rows();
}
And this is my client controller :
public function proses_login(){
$data = array(
'username' => $this->input->post('username'),
'password' => $this->input->post('password')
);
$cek = $this->rest->post('login/cobak/1/format/php/');
echo $cek;
}
The result from query is 5. It means read all record in database table
You send data by URL method you can send data instead as the following
for more information about URL method you can read this
$cek = $this->rest->post('login', $data, 'php');
you can recieve data in server by two ways
$this->post('username') or $this->input->post('username')
I think it may work
you can get more details from : Here