Laravel 9 error route | The GET method is not supported - api

I am having a problem fetching a list of certain customers (authenticated users) via API. When I use this route in Postman I receive the following error.
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException:
The GET method is not supported for this route. Supported methods:
POST. in file
D:\api\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php
on line 118
api.php
Route::post('/register', [UserAuthController::class, 'register']);
Route::post('/login', [UserAuthController::class, 'login'])
->name('login');
Route::apiResource('/customer', CustomerController::class)
->middleware('auth:api');
Controller
class CustomerController extends Controller
{
public function index()
{
$customers = Customer::all();
return response([ 'customers' =>
CustomerResource::collection($customers),
'message' => 'Successful'], 200);
}
public function store(Request $request)
{
$data = $request->all();
$validator = Validator::make($data, [
'first_name'=>'required|max:120',
'email'=>'required|email|unique:users',
'password'=>'required|min:6'
]);
if($validator->fails()){
return response(['error' => $validator->errors(),
'Validation Error']);
}
$customer = Customer::create($data);
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function show(Customer $customer)
{
return response([ 'customer' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function update(Request $request, Customer $customer)
{
$customer->update($request->all());
return response([ 'employee' => new CustomerResource($customer),
'message' => 'Success'], 200);
}
public function destroy(Customer $customer)
{
$customer->delete();
return response(['message' => 'Customer deleted']);
}
}

I solved this problem by adding Accept|json/application in headers of Postman.

Related

How to generate token with JWT on Laravel 9

The problem is that it does not generate the TOKEN, throwing the following error
TypeError: Lcobucci\JWT\Token\Builder::relatedTo(): Argument #1 ($subject) must be of type string, null given
When I make the request through the post verb, it performs all the previous validation but when it comes to generating the token, the error occurs.
`
public function login(Request $request)
{
$credentials = $request->only('usuario', 'password');
$validator = Validator::make($request->all(), [
'usuario' => 'required',
'password' => 'required'
]);
if ($validator->fails()) {
return response()->json([
'message' => $validator->errors(),
'token' => null
], 404);
}
$user = usuarios::where('usuario', $request->usuario)->first();
if (!$user) {
return response()->json([
'message' => 'Usuario no registrado.',
'token' => null
], 401);
}
$isValid = Hash::check($request->password, $user->password);
if (!$isValid) {
return response()->json([
'message' => 'ContraseƱa incorrecta.'
]);
}
$token = JWTAuth::fromUser($user);
return response()->json([
'message' => 'Usuario logueado correctamente',
'token' => $token
]);
}
`
And my code mode is this
`
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
//AƱadimos la clase JWTSubject
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Notifications\Notifiable;
class usuarios extends Model implements JWTSubject
{
use HasFactory, HasApiTokens, Notifiable;
protected $table = 'usuarios';
protected $fillable = [
'tipo_usuario',
'acceso_pv',
'nombre',
'usuario',
'password',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
public $timestamps = false;
}
`

get data value from jsonResponse Laravel 8

I have two controller
the first one has a register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = new User;
$user->email = $request->email;
$user->password = bcrypt($request->password);
$user->type = $request->type;
$user->save();
return $generalTrait->returnData('user',$user);
}
and the second also has register method:
public function register(Request $request)
{
$generalTrait = new GeneralTrait;
$user = (new UserAuthController)->register($request);
$admin = Admin::create([
'admin_name' => $request->admin_name,
//'user_id' => $response->user->user_id,
'user_id' => $user_id
]);
//Admin created, return success response
return $generalTrait->returnSuccessMessage('Admin created successfully');
}
when I try to get data from (JsonResponse) $user I find this error:
ErrorException: Undefined property: Illuminate\Http\JsonResponse::$user
returnDate method in GeneralTrait return:
public function returnData($key, $value, $msg = ""){
return response()->json([
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
]);
}
I find same Error when I try to get the status from the $response
How can I fix it?
I fix it by replacing returnData with:
public function returnData($key, $value, $msg = ""){
return [
'status' => true,
'errNum' => "5000",
'msg' => $msg,
$key => $value
];}
so to get user_id from user I said:
'user_id' => ($response["user"])->user_id
I wish I knew what my mistake was, and how I could have fixed it some other way

Lumen JWT Auth always return 401 in other route after login success

I have lumen + jwt restapi with custom users table (ex : pengguna) with nomor as primary key and tgl_lahir as password..there is no problem with api/login and it's generate a token but when i try with other route such as api/buku, the return always 401 unauthorized although the authorization header contains valid token after login
my models like
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Laravel\Lumen\Auth\Authorizable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements AuthenticatableContract, AuthorizableContract, JWTSubject
{
use Authenticatable, Authorizable;
protected $primaryKey = 'nomor';
protected $table = 'pengguna';
public $timestamps = false;
protected $fillable = [
'nomor','nama','alamat'
];
protected $hidden = [
'tgl_lahir ',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
my BukuController
<?php
namespace App\Http\Controllers;
use App\Buku;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class BukuController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function showAllBuku()
{
return response()->json(Buku::all());
}
}
my routes
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('login', 'AuthController#login');
$router->get('buku', ['uses' => 'BukuController#showAllBuku']);
});
config/auth.php
<?php
return [
'defaults' => [
'guard' => 'api',
'passwords' => 'users',
],
'guards' => [
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => \App\User::class
]
],
];
the existing pengguna table don't allowed created ID field like lumen/laravel auth, if i commented code in Middleware\Authenticate like :
public function handle($request, Closure $next, $guard = null)
{
//if this block commented is working
if ($this->auth->guard($guard)->guest()) {
return response('Unauthorized.', 401);
}
return $next($request);
}
it's working..is there another way for my case?thanks for your help
sorry my mistake, my problem solved by add this in user model
public function getAuthIdentifierName(){
return $this->nomor;
}
public function getAuthIdentifier(){
return $this->{$this->getAuthIdentifierName()};
}

Basic Auth Laravel4 How to use it?

I try to protect my restAPI with credentials and reading about basic-auth laravel I try to implement a basic authentication sytem
User tabel already exists and populated with data
in filter.php I set
Route::filter('auth.basic', function() {
return Auth::basic(); });
than in api Route
// =============================================
// API ROUTES ==================================
// =============================================
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function() {
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::get('products/{id}', 'ProductController#get', array('only' => array('show')));
});
the controller is quite simple
<?php
use App\Models\Product;
class ProductController extends \BaseController {
private $model;
function __construct() {
$this->model = new Product();
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
$model = new Product();
$page = Input::get('pageNumber');
$limit = Input::get('pageNumber');
$ram = Input::get('limit');
$cpu = Input::get('cpu');
$price_range = Input::get('price_range');
$keyword = Input::get('keyword');
return Response::json($model->getProducts($page));
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store() {
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id) {
}
public function get($id) {
$model = new Product();
return Response::json($model->getProduct($id));
}
public function show($id) {
return Response::json($this->model->getProduct($id));
}
public function update($id) {
return Response::json($this->model->getProduct($id));
}
public function pause($id) {
var_dump('pause');
}
public function create(){
}
public function edit(){
var_dump('test_edit');
}
}
calling domain.com/api/products pop up login window. populating fields and submit datas can't log in
How do I check Users credentials?
For backend I use Sentry and it's working
filter.php
Route::filter('auth.admin', function() {
if (!Sentry::check()) {
return Redirect::route('admin.login');
}
});
Route
Route::get('admin/login', array('as' => 'admin.login', 'uses'
=> 'App\Controllers\Admin\AuthController#getLogin'));
Controller
<?php namespace App\Controllers\Admin;
use Auth, BaseController, Form, Input, Redirect, Sentry, View;
class AuthController extends BaseController {
/**
* Display the login page
* #return View
*/
public function getLogin()
{
return View::make('admin.auth.login');
}
/**
* Login action
* #return Redirect
*/
public function postLogin()
{
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
try
{
$user = Sentry::authenticate($credentials, false);
if ($user)
{
return Redirect::route('admin.pages.index');
}
}
catch(\Exception $e)
{
return Redirect::route('admin.login')->withErrors(array('login' => $e->getMessage()));
}
}
/**
* Logout action
* #return Redirect
*/
public function getLogout()
{
Sentry::logout();
return Redirect::route('admin.login');
}
}
It seems that you don't have a login function defined.
by the way, you should change:
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function() {
Route::resource('products', 'ProductController', array('only' => array('index', 'store', 'destroy', 'update', 'show', 'edit')));
Route::get('products/{id}', 'ProductController#get', array('only' => array('show')));
});
to:
Route::group(array('prefix' => 'api', 'before' => 'auth.basic'), function(){
Route::get('products/{id}', 'ProductController#get'));
Route::resource('products', 'ProductController', array('except' => array('show')));
});

call model in zend form using dependencies + zend framework 2

I am trying to fetch my category model in zend form for working out with select element with zend framework 2.
after lot of code searching I found I can either inject or pull dependencies.
Following code I did in my module.php
I want categoryTable.php(model) file in my CategoryForm.php
public function getServiceConfig()
{
return array(
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
'Category\Form\CategoryForm' => function ($sm) {
$service = $sm->get('Category\Model\CategoryTable');
$form = new Form;
$form->setService($service);
return $form;
}
),
);
}
then I put following code in my controller.
$form = $this->getServiceLocator()->get("Category\Form\CategoryForm");
Then I Put following code in my CategoryForm.php
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceLocator();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
And then I call it in same file like this way
public function __construct($name = null)
{
parent::__construct('category');
echo "<pre>";print_r($this->getCategoryTable());die;
.... other code
I found this error
Fatal error: Call to undefined method Category\Form\CategoryForm::getServiceLocator() in D:\wamp\www\zendapp\module\Category\src\Category\Form\CategoryForm.php on line 120
please help. and am I missing something?
I found the solution
Step :1
Here is my module.php code
public function getServiceConfig()
{
return array(
'invokables' => array(
'Category\Form\CategoryForm' => 'Category\Form\CategoryForm',
),
'factories' => array(
'Category\Model\CategoryTable' => function($sm) {
$tableGateway = $sm->get('CategoryTableGateway');
$table = new CategoryTable($tableGateway);
//echo "<pre>";print_r($table);echo "</pre>";
return $table;
},
'CategoryTableGateway' => function ($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$resultSetPrototype->setArrayObjectPrototype(new Category());
return new TableGateway('Of_Restaurants_Category', $dbAdapter, null, $resultSetPrototype);
},
),
);
}
Step :2
Then in controller I made this change
// $form = new CategoryForm();
// Service locator now injected
$form = $this->getServiceLocator()->get('Category\Form\CategoryForm');
Step :3
Then In my categoryForm.php I made below changes
use Zend\ServiceManager\ServiceManager;
use Zend\ServiceManager\ServiceManagerAwareInterface;
protected $serviceManager;
public function getCategoryTable()
{
if (!$this->categoryTable) {
$sm = $this->getServiceManager();
$this->categoryTable = $sm->get('Category\Model\CategoryTable');
}
return $this->categoryTable;
}
protected function getCatList()
{
$groups = $this->getCategoryTable()->fetchAll();
return $groups;
}
public function getServiceManager()
{
if ( is_null($this->serviceManager) ) {
throw new Exception('The ServiceManager has not been set.');
}
return $this->serviceManager;
}
public function setServiceManager(ServiceManager $serviceManager)
{
$this->serviceManager = $serviceManager;
// Call the init function of the form once the service manager is set
$this->init();
return $this;
}
public function __construct($name = null) // constructor I finished immediately
{
parent::__construct('category');
}
I add INIT() function to fetch servicemanager
public function init()
{
$this->setAttribute('method', 'post');
$options = array();
foreach ($this->getCatList() as $cat) {
$options[$cat->id] = $cat->title;
}
$this->add(array(
'type' => 'Zend\Form\Element\Select',
'name' => 'parent_id',
'options' => array(
'label' => 'Parent Category',
'empty_option' => 'Please choose Parent Category',
'value_options' => $options,
),
));
}
Hope this will help who are new ZF2.