Laravel phpunit api return 405 - php

I can not test the api with phpunit testing. I have created a testcase and a test route. But it gives me an error like Expected status code 200 but received 405.
My User controller test:-
<?php
namespace Tests\Feature\API\Medical\V1;
use Tests\TestCase;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;
use App\User;
class UserControllerTest extends TestCase
{
/**
* A basic test example.
*
* #return void
*/
public function testLogin()
{
$user = User::find(1);
$response = $this->actingAs($user,'api')->json('POST','/api/test');
$response->assertStatus(200);
}
}
I have not done anything to testCase base class.
My api routes:-
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::post('/test',function(){
return response()->json([
'success'=>true
]);
});
But this route is working on postman. When i change http method to GET it gives me my default route on routes/web.php. How to get my actual json to my testcase? thanks in advance.

I faced the same problem.
The project was raised in docker. In the .env file, you need to write:
APP_URL=http://localhost

Related

Method App\Http\Controllers\CategoryController::manage_category does not exist

I am a new learner of laravel. I face problem while running my code. Method App\Http\Controllers\CategoryController::manage_category does not exist.
Here is my code:
<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
return view('admin/category');
}
public function manage_category()
{
return view('admin/manage_category');
}
}
Here is my web route code:
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AdminController;
use App\Http\Controllers\CategoryController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', function () {
return view('welcome');
});
Route::get('admin',[AdminController::class,'index']);
Route::post('admin/auth',[AdminController::class,'auth'])->name('admin.auth');
Route::group(['middleware'=>'admin_auth'],function(){
Route::get('admin/dashboard',[AdminController::class,'dashboard']);
Route::get('admin/category',[CategoryController::class,'index']);
Route::get('admin/manage_category',[CategoryController::class,'manage_category']);
});
Ahmad your code looks fine try below to clear the cache
php artisan cache:clear
php artisan route:clear
php artisan config:clear
php artisan view:clear

Why am I getting this error: "class app\Laptop not found?"

I am trying different methods to resolve it for 5 hours but can't may any method work.
This is my web.php file:
<?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'LaptopController#show');
This is Laptop.php(Model):
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Laptop extends Model
{
//
}
This is LaptopController.php (Controller):
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use app\Laptop;
class LaptopController extends Controller
{
public function show(){
$laptop=Laptop::all();
echo $laptop->name;
}
}
Inside the controller you are using
use app\Laptop;
but instead it should be
use App\Laptop;
In addition to this there is the problem that you are trying to access name of a Collection: if you want just the first one you should do Laptop::first()

How to use GATE facades in LUMEN (Laravel 6.2)

I'm trying to create an ACL with Lumen.
I want to use the built-in gates/policies to do so.
I've been following the official Lumen Docs:
https://lumen.laravel.com/docs/6.x/authorization
and Laravel Docs:
https://laravel.com/docs/6.x/authorization
to do so. They say I need to register both facades and the gate facade in order to use Gates.
I have the following code inside my AuthServiceProvider.php:
<?php
namespace App\Providers;
use App\User;
use Firebase\JWT\JWT;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Gate;
//use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Http\Request;
class AuthServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
//
}
/**
* Boot the authentication services for the application.
*
* #return void
*/
public function boot()
{
// Here you may define how you wish users to be authenticated for your Lumen
// application. The callback which receives the incoming request instance
// should return either a User instance or null. You're free to obtain
// the User instance via an API token or any other method necessary.
$this->app['auth']->viaRequest('api', function ($request) {
$key = 'pawifjopawiejfpoaiwejfpoji';
$jwt = preg_replace('/^Bearer (.*)/', '$1', $request->header('Authorization'));
$decoded = JWT::decode($jwt, $key, ['HS256']);
return User::where('email', $decoded->email)->first();
});
$this->registerPolicies();
Gate::define('edit-settings', function($user){
return $user->isAdmin;
});
}
}
And I have the bootstrap/app.php set like so, with $app->withFacades() uncommented:
<?php
require_once __DIR__.'/../vendor/autoload.php';
(new Laravel\Lumen\Bootstrap\LoadEnvironmentVariables(
dirname(__DIR__)
))->bootstrap();
/*
|--------------------------------------------------------------------------
| Create The Application
|--------------------------------------------------------------------------
|
| Here we will load the environment and create the application instance
| that serves as the central piece of this framework. We'll use this
| application as an "IoC" container and router for this framework.
|
*/
$app = new Laravel\Lumen\Application(
dirname(__DIR__)
);
$app->withFacades();
$app->withEloquent();
/*
|--------------------------------------------------------------------------
| Register Container Bindings
|--------------------------------------------------------------------------
|
| Now we will register a few bindings in the service container. We will
| register the exception handler and the console kernel. You may add
| your own bindings here if you like or you can make another file.
|
*/
$app->singleton(
Illuminate\Contracts\Debug\ExceptionHandler::class,
App\Exceptions\Handler::class
);
$app->singleton(
Illuminate\Contracts\Console\Kernel::class,
App\Console\Kernel::class
);
/*
|--------------------------------------------------------------------------
| Register Middleware
|--------------------------------------------------------------------------
|
| Next, we will register the middleware with the application. These can
| be global middleware that run before and after each request into a
| route or middleware that'll be assigned to some specific routes.
|
*/
// $app->middleware([
// App\Http\Middleware\ExampleMiddleware::class
// ]);
$app->routeMiddleware([
'auth' => App\Http\Middleware\Authenticate::class,
]);
/*
|--------------------------------------------------------------------------
| Register Service Providers
|--------------------------------------------------------------------------
|
| Here we will register all of the application's service providers which
| are used to bind services into the container. Service providers are
| totally optional, so you are not required to uncomment this line.
|
*/
// $app->register(App\Providers\AppServiceProvider::class);
$app->register(App\Providers\AuthServiceProvider::class);
// $app->register(App\Providers\EventServiceProvider::class);
/*
|--------------------------------------------------------------------------
| Load The Application Routes
|--------------------------------------------------------------------------
|
| Next we will include the routes file so that they can all be added to
| the application. This will provide all of the URLs the application
| can respond to, as well as the controllers that may handle them.
|
*/
$app->router->group([
'namespace' => 'App\Http\Controllers',
], function ($router) {
require __DIR__.'/../routes/web.php';
});
return $app;
And when I now run any http-request with RESTClient (www.restclient.net) against my Lumen API, I get the following error:
Call to undefined method App\Providers\AuthServiceProvider::registerPolicies()
I googled quite a lot on this issue and found some solutions, but none of them worked for me.
Please help
Your provider doesn't have that method. This is the entire AuthServiceProvider that Laravel uses as its base for AuthServiceProvider:
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* #var array
*/
protected $policies = [];
/**
* Register the application's policies.
*
* #return void
*/
public function registerPolicies()
{
foreach ($this->policies() as $key => $value) {
Gate::policy($key, $value);
}
}
/**
* Get the policies defined on the provider.
*
* #return array
*/
public function policies()
{
return $this->policies;
}
}
registerPolicies isn't doing anything special. It just spins through $policies and registers them; you can do this yourself.
"Unlike Laravel, Lumen does not have a $policies array on its AuthServiceProvider. However, you may still call the policy method on the Gate facade from within the provider's boot method" - Lumen 6.x Docs - Authorization - Defining Policies

API Routing Laravel 5.5

I have basic controller, where I want it to receive any json request. Am new to api routing. I get Sorry No Page Found When I use POST MAN. First I tested it on GET and made it call a simple return but throws the error."Sorry, the page you are looking for could not be found."
I removed the api prefix in the RouteServiceProvider.php and to no success.I put my demo controller
Routing api.php
<?php
use Illuminate\Http\Request;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
Route::get('/test_api/v1', 'TestController#formCheck');
TestController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class TestController extends Controller
{
public function formCheck(){
return "YES !!!";
}
public function formPost(Request $request)
{
$formData = $request->all();
return response()->json($formData, 201);
}
}
In the app/Providers/RouteServiceProvider.php.
Remove prefix('api') & it shuld look like this.
protected function mapApiRoutes()
{
Route::middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}

"Target [App\Http\Controllers\Controller] is not instantiable."

I'm trying to follow laracasts tutorial on laravel fundamentals but after getting composer and laravel installed with no problems I can't get my routes file to work with the controller I've reinstalled laravel copied it exactly how laracasts has his but still nothing, anyone see anything wrong with these two files?
routes.php files
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/', 'Controller#index');
Route::get('contact', 'Controller#contact');
controller.php file
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController
{
use DispatchesJobs, ValidatesRequests;
public function ___construct()
{
$this->middleware('guest');
}
public function index()
{
return 'hello world!';
}
public function contact()
{
return 'Contact me!';
}
}
I have it hosted on localhost:8888 using phps server command if that is any help.
The reason might be that your controller class is abstract, hence it's not instantiable. Remove the abstract keyword.
if your route is get or post and actually you have implemented resource, so you get this type of error

Categories