Laravel NotFoundHttpException on API - php

I have API URL like:
http://example.com/api/driverAcceptOrder?id=bee74e39-ff38-46a6-9e5d-6db799d2be8c&driverId=3453a3a9-7f58-434a-8dab-95c3469e6238
method is POST and it takes 2 parameter id and driverId
When I try to run this URL in postman I get:
Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException
Route
Route::post('driverAcceptOrder/{id}/{driverId}', 'Api\DriversController#driverAcceptOrder');
Controller
public function driverAcceptOrder(Request $request, $id, $driverId)
{
$order = Order::findOrFail($id);
$defs = OrderDefaultProgress::where('name', 'Driver OTW ke pelanggan')->first();
$driver = Driver::where('id', $driverId)->with('user')->first();
$order->update(['driver_id' => $driverId]);
return response()->json([
'data' => $driver,
'message' => 'Pengemudi Dalam perjalanan menuju pelanggan.'
], 200);
}
Note
Route is not restricted by Auth middleware (its public)
I've added exception to my VerifyCsrfToken file as protected $except = ['/api/*'];
Any idea?

your url is wrong
example.com/api/driverAcceptOrder?id=bee74e39-ff38-46a6-9e5d-6db799d2be8c&driverId=3453a3a9-7f58-434a-8dab-95c3469e6238
here after ? all is query paramter which is used in GET method to send data
Route::get('driverAcceptOrder',"..");
which is not found in your case that's why your getting
NotFoundHttpException
for your case url should be
example.com/api/driverAcceptOrder/bee74e39/3453a3a9-7f58-434a-8dab-95c3469e6238
this will be handel by
Route::post('driverAcceptOrder/{id}/{driverId}', 'Api\DriversController#driverAcceptOrder');
you can learn more about
GET and POST here https://www.w3schools.com/tags/ref_httpmethods.asp

Related

405 Method not allowed with Guzzle POST request in PHP

I'm stuck since several hours on a the consumption of a locale API (which I created) with PHP and Guzzle on a laravel project (8.7).
I've created deux differents laravel projects on the same local server. One is providing some API routes and the second one consume it.
On the first project (which providing APIs) I've created several routes to create, read, update and delete datas from my database.
To access this API routes we need to first consume an API route called "login". This one handle the creation of a token according to a given couple email/password.
This token is needed to call all the others API routes.
The /api/login API is a POST request with email and password datas.
/api/login route declaration : (I would like to specify that this route is into the api.php file into my laravel project so the corresponding url is : http://xxx.xxx.x.xxx/site/public/api/login)
Route::post('login',[AdminController::class,'index']);
Index method for /api/login :
function index(Request $request)
{
if(!($request->ip() == "xxx.xxx.x.xxx")) {
Log::alert('Ip ' . $request->ip() . ' a tenté de se connecter à l\'Api');
return response([
'message' => ['Authentification failed']
], 403);
}
$admin = Admin::where('email', $request->email)->first();
if (!$admin || !Hash::check($request->password, $admin->password)) {
return response([
'message' => ['Email-password couple is incorrect']
], 403);
}
$token = $admin->createToken('my-app-token')->plainTextToken;
$response = [
'admin' => $admin,
'token' => $token
];
return response($response, 201);
}
In my second project I'm using Guzzle to consome my APIs.
/articles route declaration : (http://xxx.xxx.x.xxx/backoffice/public/api/login)
Route::prefix('articles')->group(function () {
Route::any('/', [ArticlesController::class, 'index'])->name('articles-index');
});
Index method for /articles :
public function index() {
$client = new \GuzzleHttp\Client();
$request = $client->request('POST', 'http://xxx.xxx.x.xxx/site/public/api/login/', [
'headers' => ['Content-Type' => 'application/x-www-form-urlencoded'],
'form_params' => [
'email' => 'test#gmail.com',
'password' => 'dAvG454aquysla4'
],
'debug' => true,
]);
$response = $request->getBody()->getContents();
return view('articles.index', [
]);
}
I'm getting this error :
GuzzleHttp\Exception\ClientException Client error: 'POST http://xxx.xxx.x.xxx/site/public/api/login/' resulted in a '405 Method Not Allowed' response: <!doctype html> <html class="theme-light"> <!-- Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException: Th (truncated...)
I don't understand where is my mistake...
The /api/login is correctly define in POST http method and works perfectly with Insomnia.
Does anyone have an idea or will be able to help me using Guzzle? It's the first time I'm using it.
I'm used to consume API with fetch (ajax) in JS.
Thanks ;)

Sending a relational request through api in laravel

How do I send a request like this through an api?
I get this error even though I passed the user's jwt in the headers
ErrorException: Trying to get property 'id' of non-object in file C:\xampp\htdocs\doc\app\Http\Controllers\HistoryApiController.php on line 42
This is the store function
public function store(Request $request)
{
$history = new History;
$history->history = $request->input('history');
$history->admin_id = auth()->user()->id;
$history->save();
return response()->json([
'message' => 'History added',
]);
}
this means the token is not valid , check this middleware ('middleware' => 'api') apply on this routes to check the token validation if you use tymon package

Laravel request url with parameter problem with GET Method

I have a route in api.php which look like this:
Route::get('auth/logout/{token}','UserController.php';
I tested this API endpoint using Postman with these configurations:
Method: GET
Params: key = token; value = $2y$10$Xji0VW1Qq9rtF04QlXDu1ePKNKHpRA2ppjDYWNFX.37C30sd3WSIu
Header: none
URL: localhost:8000/api/v1/logout?token=$2y$10$Xji0VW1Qq9rtF04QlXDu1ePKNKHpRA2ppjDYWNFX.37C30sd3WSIu
Here is my UserController#logout:
public function logout($token){
return response()->json([
'message' => 'Logout Success',
'token' => $token
], 200);
}
As you can see there, I just want to show a message and the $token parameter in Postman. But my problem is, Postman shows me a blank response. I can't access the URL with ? as the parameter separator. But I can access the URL with /, just like host/api/v1/auth/logout/{token_value}. But it is not what I desired. Anyone can help me?
You can remove the token route parameter:
Route::get('auth/logout', 'UserController.php');
And retrieve the token from the request in the controller:
public function logout(Request $request) {
return response()->json([
'message' => 'Logout Success',
'token' => $request->token
], 200);
}

Why does Silex say my route can't be found?

After updating a users profile, this line should redirect me to the page to show his profile:
return $app->redirect($app['url_generator']->generate('user/' . $id));
However, I get the following error:
RouteNotFoundException in UrlGenerator.php line 130: Unable to
generate a URL for the named route "user/1" as such route does not
exist.
And finally, this is the controller I'm trying to redirect to:
$app->match('/user/{id}', function (Request $request, $id) use ($app) {
$user = new User();
$user->find($id);
$team = new Team();
$team->find($user->data()->username);
if($team->exists()){
return $app['twig']->render('user.twig', [
'team_data' => $team->data(),
'user_data' => $user->data()
]);
}
else{
return $app['twig']->render('user.twig', [
'user_data' => $user->data()
]);
}
});
Can anyone tell my why this error is given even though I've defined the route?
Use $app['url_generator']->generate('user', ['id' => $id])
Silex (or rather the URL generator) handles the parameter processing for you.

Laravel cURL POST Throwing TokenMismatchException

I have a problem with POST cURL request to my application.
Currently, I'm building RESTFUL registration function using laravel 5.
The routes for this is example is
localhost:8000/user/create
I pass value using cURL function on terminal
curl -d 'fname=randy&lname=tan&id_location=1&email=randy#randytan.me&password=randytan&remember_token=Y&created_at=2015-03-03' localhost:8000/auth/register/
And this is my routes.php
Route::post('user/create', 'UserController#create');
And this is my function to store the registration user
public function create()
{
//function to create user.
$userAccounts = new User;
$userAccounts->fname = Request::get('fname');
$userAccounts->lname = Request::get('lname');
$userAccounts->id_location = Request::get('id_location');
$userAccounts->email = Request::get('email');
$userAccounts->password = Hash::make(Request::get('password'));
$userAccounts->created_at = Request::get('created_at');
$userAccounts->save();
return Response::json(array(
'error' => false,
'user' => $userAccounts->fname . " " . $userAccounts->lname
), 200);
}
Executing the cURL syntax above, I'm getting this error TokenMismatchException
Do you have any ideas?
Because I'm implementing middleware only in my few urls, and this cURL registration url is not tight into any authentication mechanism.
Thanks before.
In Laravel 5 (latest version) you can specify routes you want to exclude in /app/Http/Middleware/VerifyCsrfToken.php
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'rest-api/*', # all routes to rest-api will be excluded.
];
}
Hope this helps.
Laravel 5 enforces CSFR token authentication in middleware by default.
you can disable CSFR on selected route Here is the link
or you can try some of these solutions. Hope so it will help.
changing your csfr token method /app/Http/Middleware/VerifyCsrfToken.php
public function handle ($request, Closure $next)
{
if ( !$request->is("api/*"))
{
return parent::handle($request, $next);
}
return $next($request);
}
In my case, i needed to add the route on api.php instead of web.php

Categories