Codeigniter Rest API : Put request doesn't get passed id - php

I developed a REST API using REST Library for Phil Sturgeon,
GET and POST requests working fine ,
Now when I try to access the passed params with PUT request, I get null.
class ApiItems extends REST_Controller
{
function __construct() {
//
}
public function items_get(){ // //}
public function items_post(){ // //}
public function items_put()
{
if(!$this->put('id')) //My issue : I can't get the id here
{
$this->response(array('error' => 'Item id is required'), 400);
}
$data = array(
'id' => $this->put('id'),
'code'=> $this->put('code'),
'name' => $this->put('name'),
'quantity' => $this->put('quantity')
);
$this->item_model->update_item($this->put('id'), $data);
$message = array('success' => $id.' Updated!');
$this->response($message, 200);
}
}
I tested it using POSTMAN and I get this :
POSTMAN PUT Call screenshot
I dont understand why $this->get(id) or $this->post(id) are working fine,and not the case for $this->put(id) ?

It's working ,I ve done a stupid mistake when filling the parameters with POSTMAN, I checked form-data instead of x-www-form-url-encoded

Related

validation getting failed in Laravel API

In laravel controller validation getting failed, please help.
Repository: https://github.com/dhawlesudhir/basic_app.git
ProductController.php:
protected function validateRequest()
{
return request()->validate([
'name' => 'required|min:10|max:255',
'price' => 'required|integer|min:100',
'category_id' => 'required|exists:categories,id'
]);
}
public function store()
{
$data = $this->validateRequest();
$product = Product::create($data);
return new ProductResource($product);
}
api.php:
Route::apiResource('/products', ProductController::class);
Laravel throwing validation because you haven't set json in postman.
I can see currently you have set Text.
Set type to json like in screenshot
Otherwise Laravel receives empty array from request()->all()
Also make sure to set header Accept:application/json .

How to remove parameter from a URL in laravel 5.2

How can I remove the parameters from a URL after processing in my controller? Like this one:
mydomain/mypage?filter%5Bstatus_id%5D
to
mydomain/mypage
I want to remove the parameters after the ? then I want to use the new URL in my view file. Is this possible in laravel 5.2? I have been trying to use other approaches but unfortunately they are not working well as expected. I also want to include my data in my view file. The existing functionality is like this:
public function processData(IndexRequest $request){
//process data and other checkings
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I want it to be like:
public function processData(IndexRequest $request){
//process data and other checkings
// when checking the full url is
// mydomain/mypage?filter%5Bstatus_id%5D
// then I want to remove the parameters after the question mark which can be done by doing
// request()->url()
// And now I want to change the currently used url using the request()->url() data
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I'm stuck here for days already. Any inputs are appreciated.
You can use request()->url(), it will return the URL without the parameters
public function processData(IndexRequest $request){
$url_with_parameters = $request()->url();
$url= explode("?", $url_with_parameters );
//avoid redirect loop
if (isset($url[1])){
return URL::to($url[0]);
}
else{
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
}
add new url to your routes and assuming it will point to SomeController#SomeMethod, the SomeMethod should be something like :
public function SomeMethod(){
// get $data and $persons
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
I hope this helps

Laravel test response with The given data was invalid

I'm doing unit test with laravel, so I called controller function and I get like a respnse an array
I have been response with this
return back()->with('success', 'Lots was generated')
and
return $this->lots_available;
The test give me as response this:
There was 1 error:
Tests\Feature\LotTest::test_lots
Illuminate\Validation\ValidationException: The given data was invalid.
I don't understand the reazon to this response, I'm beginning with the test
This is my function test
public function test_lots()
{
$this->withoutExceptionHandling();
$product = factory(Product::class)->create([
'size' => 20
]);
$lots = factory(Lot::class, 10)->create([
'product_id' => $product->id,
]);
$admin = factory(User::class)->create([
'role_id' => 3
]);
$client_request = 500;
$this->actingAs($admin)
->post(route('lots.distribution'), [$product, $client_request])
->assertStatus(200);
}
And this my called method
public function distribute(ProductRequest $product, $client_order)
{
$this->lots = $product->lots;
$this->client_order = $client_order;
$this->getLotAvailable();
return $this->lots_available;
}
Assuming your route is something like Route::post('/distribute/{product}/{client_order}')
route('lots.distribution') needs the parameters inside the function call
route('lots.distribution', [$product, $client_request])
Then you need to send the data that passes your rules in ProductRequest otherwise you will get a validation error. If you try a dd(session('errors')) after the post, you will probably see errors about missing fields.
->post(
route('lots.distribution', [$product, $client_request]),
['title => 'unique_title', 'sap_id' => 'unique_id']
)
Finally in your method, I'm assuming that the request ProductRequest is different than the Model Product:
public function distribute(ProductRequest $request, Product $product, $client_order)
Put the response in a variable and use dd() to print it.
You will find it on the messages method.
Worked for me.
dd($response);

Laravel 5.4 testing route protected by $request->ajax(), how to make test ajax request?

I am trying to test a route that does something different in the controller whether or not the request is ajax or not.
public function someAction(Request $request)
{
if($request->ajax()){
// do something for ajax request
return response()->json(['message'=>'Request is ajax']);
}else{
// do something else for normal requests
return response()->json(['message'=>'Not ajax']);
}
}
My test:
public function testAjaxRoute()
{
$url = '/the-route-to-controller-action';
$response = $this->json('GET', $url);
dd($response->dump());
}
When I run the test and just dump the response I get back 'Not ajax' - which makes sense I guess cause $this->json() is just expecting back a json response, not necessarily making an ajax request. But how can I correctly test this? I have been commenting the...
// if($request->ajax(){
...need to test this code
// }else{
// ...
// }
every time I need to run the test on that portion of code. I'm looking for how to make an ajax request in my test case I guess...
In Laravel 5.4 tests this->post() and this->get() methods accept headers as the third parameter.
Set HTTP_X-Requested-With to XMLHttpRequest
$this->post($url, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
I added two methods to tests/TestCase.php to make easier.
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extends BaseTestCase
{
use CreatesApplication;
/**
* Make ajax POST request
*/
protected function ajaxPost($uri, array $data = [])
{
return $this->post($uri, $data, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
}
/**
* Make ajax GET request
*/
protected function ajaxGet($uri, array $data = [])
{
return $this->get($uri, array('HTTP_X-Requested-With' => 'XMLHttpRequest'));
}
}
Then from within any test, let's say tests/Feature/HomePageTest.php, I can just do:
public function testAjaxRoute()
{
$url = '/ajax-route';
$response = $this->ajaxGet($url)
->assertSuccessful()
->assertJson([
'error' => FALSE,
'message' => 'Some data'
]);
}
Try $response = \Request::create($url, 'GET', ["X-Requested-With" => "XMLHttpRequest"])->json();
This is what worked for me
$result = $this->actingAs($user)->json('delete', '/order/' . $order->id, ['id' => $order->id, "_method" => "DELETE"], ['X-Requested-With' => 'XMLHttpRequest']);
$this->assertEquals(403, $result->response->status());

ROUTE PARAMETER DISAPPEAR AFTER SAVE DATA

Hi everyone I need help with this problem. I am programming an application using php with laravel framework. My current laravel framework version is 4.2.11
I have this route to handle POST & GET actions
Route::any("/myaccount2/ausersave/{code?}", array("as" => "ausersave",
"uses" => "PrivateController#ausersave"))->before('auth_admin');
When I use Get action with mydomain/myaccount2/ausersave/90
I get list all data ok. But when I post all data to save the url change to mydomain/myaccount2/ausersave (parameter 90 is missing)
I guest this change is before the data is saved because the {code?} or 90 parameter is missing.
So I was looking for a function that allowed my application to post data and keeps the old url (mydomain/myaccount2/ausersave/90)
I find this function Redirect::back() but some post don't recommend to use it
I will apreciate your help. Thanks
My controller function is:
public function ausersave($code = 'null') {
$messg = null;
if(Input::get("userid") != null && Input::get("personid") != null) {
return View::make('PrivateController.ausersave', array('message' =>'Ok',
'user' => null, 'children' => null));
}
else if(isset($code)) {
return View::make('PrivateController.ausersave',
$this->ausersaveGet($code) );
}
return View::make('PrivateController.ausersave',
array('message' => '', 'user' => null,
'children' => null));
}
$this->ausersaveGet($code) -> this function bring me data form database and return me an array with thosse values array('message' => '', 'user' => $user, 'children' => $children); where user has info about user and children is an array of data. All this data return ok.
I would try taking the the ? out of the route parameter. i.e. change this:
Route::any("/myaccount2/ausersave/{code?}", array(......
to this:
Route::any("/myaccount2/ausersave/{code}", array(......

Categories