Update API in laravel 5.7 - api

I have create API of update my project details, I test it in POSTMAN app it shows the success message but there no effect in the database.
Here are my code:
ProjectsController.php
public function UpdateProject($id)
{
$data = Input::all();
$q = Project::where('id',$id)->update($data);
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}
api.php
Route::post('UpdateProject/{id}','ProjectsController#UpdateProject');
Postman - see image.
output in postman:
{
"code": "200",
"message": "Project data update successfylly"
}
Can anyone help me out?
Thank you

I think you need to check all input details closely , it also comes with token when you submit the form so you need to save all details except token
Change this
$data = Input::all();
to this
$data = Input::except('_token');
I hope this resolves the issue.

in your model add fillable :
protected $fillable = ['name', 'project_group_id','number','ROM','address','city','state','zip','start_date','end_date','duration','description','timeline_type','project_type_id','project_category_id','office_id'];

You have forgotten to run the ->save() method after updating the data:
public function UpdateProject($id)
{
$data = Input::all();
$q = Project::find($id)
$q = $q->fill($data);
$q->save();
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}

You can use this method it will reduce your code
Route (api)
Route::post('UpdateProject/{project}','ProjectsController#UpdateProject');
ProjectsController.php
public function UpdateProject(Request $request, Project $project)
{
$data = $request->all();
$project->update($data);
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}

Related

Lumen Google reCAPTCHA validation

I already seen some tuts and example about it and I have implemented it somehow.
Method in controller looks like this:
The logic used is just php and I would like to use more a lumen/laravel logic and not just simple vanilla php. Also I have tried and did not worked anhskohbo / no-captcha
public function create(Request $request)
{
try {
$this->validate($request, [
'reference' => 'required|string',
'first_name' => 'required|string|max:50',
'last_name' => 'required|string|max:50',
'birthdate' => 'required|before:today',
'gender' => 'required|string',
'email' => 'required|email|unique:candidates',
'g-recaptcha-response' => 'required',
]);
//Google recaptcha validation
if ($request->has('g-recaptcha-response')) {
$secretAPIkey = env("RECAPTCHA_KEY");
// reCAPTCHA response verification
$verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretAPIkey.'&response='.$request->input('captcha-response'));
$response = json_decode($verifyResponse);
if ($response->success) {
//Form submission
//Saving data from request in candidates
$candidate = Candidate::create($request->except('cv_path'));
$response = array(
"status" => "alert-success",
"message" => "Your mail have been sent."
);
} else {
$response = array(
"status" => "alert-danger",
"message" => "Robot verification failed, please try again."
);
}
}
} catch(Exception $e) {
return response()->json($e->getMessage());
}
return response()->json(['id' => $candidate->id, $response]);
}
Okey. Google has an package for this:reCAPTCHA PHP client library
just: composer require google/recaptcha "^1.2"
and in your method inside controller:
$recaptcha = new \ReCaptcha\ReCaptcha(config('app.captcha.secret_key'));
$response = $recaptcha->verify($request->input('g-recaptcha-response'), $_SERVER['REMOTE_ADDR']);
if ($response->isSuccess()) {
//Your logic goes here
} else {
$errors = $response->getErrorCodes();
}
config('app.captcha.site_key') means that I got the key from from config/app.php and there from .env file.
If you have not config folder, you should create it, also create app.php file same as in laravel.

Laravel update record with Passport

Hi all today i have this problem with my api.
I don't update the record on DB.
In postaman the response is true but don.t save in db.
In Postaman i passed with PUT method and set in Body name a text
ProductController:
public function update(Request $request, $id)
{
$product = auth()->user()->products()->find($id);
if (!$product) {
return response()->json([
'success' => false,
'message' => 'Product with id ' . $id . ' not found'
], 400);
}
$updated = $product->fill($request->all())->save();
if ($updated)
return response()->json([
'success' => true
]);
else
return response()->json([
'success' => false,
'message' => 'Product could not be updated'
], 500);
}
You should take a look at your Product Model to see if name is set as a fillable field: $fillable = ['name'];. Also, the key is probably just name instead of "name".

Laravel 5.6 - creation user not working

my application used to working well with registration user but now it dont.
here a portion of my model User
protected $fillable = [
'prenom', 'nom', 'email','photo_path','password',
];
here my validation function :
protected function validator(array $data)
{
return Validator::make($data, [
'prenom' => 'required|string|max:255',
'nom' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'photo_path' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
'password' => 'required|string|min:6|confirmed',
]);
}
here my create function :
protected function create(array $data)
{
dd($data);
$photoInput = request('photo_path');
$userPhotoPath='users';
$storagePhotoPath = Storage::disk('images')->put($userPhotoPath, $photoInput);
return User::create([
'prenom' => $data['prenom'],
'nom' => $data['nom'],
'email' => $data['email'],
'photo_path' => $storagePhotoPath,
'password' => Hash::make($data['password']),
]);
}
- POST request working ( return 302 ) but return back with input value
- Auth Route are declared in web.php
- Validation working well
but the php interpretor didnt get inside create function...
i just see in debugbar that information :
The given data was invalid./home/e7250/Laravel/ManageMyWorkLife/vendor/laravel/framework/src/Illuminate/Validation/Validator.php#306Illuminate\Validation\ValidationException
public function validate()
{
if ($this->fails()) {
throw new ValidationException($this);
}
$data = collect($this->getData())
but my validation working because i have error message near my InputTexte.
so i dont understand that error message ...
Do you have any clue ?
Well, you need to remove the dd(); function before you run something. Other wise it will end the execution of all other operations.
Check if your User Model has a constructor, if so remove it and check if the problem still accours. This fixed it for me.

API returning 400 Bad Request response

I have built an API and an application that uses that API. Everything was working but now, for some reason, I get a 400 Bad Request response. I am not sure if I changed something in the code so I wanted to double check it was correct.
So my API call is this
$client = new GuzzleHttp\Client();
$jsonData = json_encode($data);
$req = $client->request('POST', 'https://someurl.com/api/v1/createProject', [
'body' => $jsonData,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($jsonData),
]
]);
$output = $req->getBody()->getContents();
The API has a route set up correctly which uses post. The function it calls is correct, and I have changed it for testing to simply return
return response()->json(["Success", 200]);
When I test the API out within Postman, I can see that Success is returned. When I test the API within the other application I have built, I dont even see a POST request within the console, I am just displayed a Laravel error 400 Bad Request.
What could be the cause of this issue?
Thanks
Update
I have changed the request to this
$data= json_encode($data);
$req = $client->post('https://someurl.com/api/v1/createProject', [
'body' => $data
]);
If I output $data after it has been encoded, I get something like this
{
"projectName":"New Project",
"clientName":"Test Client",
}
Within the controller function of the API that is being called, I simply do
return response()->json(['name' => $request->input('clientName')]);
The 400 error has now gone, but I now get null returned to me
{#326 ▼
+"name": null
}
Request is being injected into the function as it should be. Should I be returning the data in a different way?
Thanks
Probably you did $ composer update and Guzzle updated.
So if you are using newest Guzzle (guzzlehttp/guzzle (6.2.2)) you do POST request:
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data
]);
You do not need to specify headers.
To read response you do following:
$json_response = json_decode($response->getBody());
My full example (in routes file web.php routes.php)
Route::get('smith', function () {
$client = new GuzzleHttp\Client();
$data = ['name' => 'Agent Smith'];
$response = $client->post('http://example.dev/neo', [
'json' => $data,
]);
$code = $response->getStatusCode();
$result = json_decode($response->getBody());
dd($code, $result);
});
Route::post('neo', function (\Illuminate\Http\Request $request) {
return response()->json(['name' => $request->input('name')]);
});
or you could use following (shortened), but code above is "shorter"
$json_data = json_encode(['name' => 'Agent Smith']);
$response = $client->post('http://example.dev/neo', [
'body' => $json_data,
'headers' => [
'Content-Type' => 'application/json',
'Content-Length' => strlen($json_data),
]
]);
note: If you are running PHP5.6, change always_populate_raw_post_data to -1 (or uncomment the line) in php.ini and restart your server. Read more here.
In my case I was using public IP address in BASE_URL while I should have been using the private IP. From mac you can get your IP by going into system preferences -> network.
This is with Android + Laravel (API)

ActiveDataProvider:"query" property must be instance of a class that implements the QueryInterface

i am using an self-defined func that encapsu findBySql() to return rows .but got the error showed in the title. but if i test to use self-defined func that encapsu find() ,it worked,why?
Here is my action:
public function actionList()
{
$model = new Loan();
$dataProvider = new ActiveDataProvider(
[
'query' => $model->findValid($_GET['type']),//error comes here
'pagination' => [
'pagesize' => '2',
],
]);
return $this->renderPartial('list', ['model' => $model, 'dataProvider' => $dataProvider]);
}
Here is the object loan's findxx function:
public function findValid($type=null)
{
if($type==null){
return static::findBySql("select * from loan where wmstat&1=1 and (wmstat>>2)&1=0")->all();
}else{
return static::findBySql("select * from loan where wmstat&1=1 and (wmstat>>2)&1=0 and origin="."'".$type."'")->all();
}
}
Futher more,can i change the bit operatin using find() and where() and achieve the same effect ?
The error is clear, query expects valid query instance, while you are passing results of query and not the query itself.
Remove ->all() calls in findValid() method and it should work.
P.S. I strongly recommend to refactor your code to better condition.
Official docs:
ActiveDataProvider $query
ActiveQuery
findBySql()
Here is one with basic code example; not using ->all()
$query = User::find();
$dataProvider = new ActiveDataProvider([
'pagination' => ['pageSize' =>5],
'query' => $query,
]);
return $this->render('index', [
'dataProvider' => $dataProvider,
]);