How to call an Api Controller from API route in laravel? - laravel

I have installed jwt authentication & I have created a controller i.e., AuthController Inside Api Directory. I have defined the in routes/api.php as:
Route::group(['prefix'=>'v1', 'namespace' => 'Api'],function($app){
Route::get('/test', function(){
return "HEllo";
});
Route::get('test', 'AuthController#test');
});
When I hit the url as: http://localhost:8000/api/v1/test then I am getting error as Class Cotrollers\Api\AuthController does not exist.
AuthController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
public function test() {
return "Hello";
}
}
RouteServiceProvider.php:
Route::prefix('api')
// ->middleware('api')
// ->namespace($this->namespace) ->group(base_path('routes/api.php'));

Uncomment the ->namespace($this->namespace) line.

In your Route::group statement you have defined the namespace of the route group as 'Api'.
But the AuthController resides in the App\Http\Controllers namespace, and not the Api namespace.
To fix this add an Api namespace in your App\Http\Controllers and refer it there (best practice is creating a directory in the Controllers directory named Api so the directory structure follows the namespace):
AuthController.php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class AuthController extends Controller
{
public function test() {
return "Hello";
}
}

Here you need to make changes to,
App\Providers\RouteServiceProvider.php
In the RouteServiceProvider.php add
protected $namespace = 'Path\To\Controllers';
Like:
protected $namespace = 'App\Http\Controllers';
Thats it!
Please let me know if this solved your problem.

Change the Auth controller namespace definition to:
namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\AuthController;
// you need to use your controller top of the api.php file
Route::group([
'namespace' => 'Customers', //namespace App\Http\Controllers\Customers;
'middleware' => 'auth:api', // this is for check user is logged in or authenticated user
'prefix' => 'customers' // you can use custom prefix for your rote {{host}}/api/customers/
], function ($router) {
// add and delete customer groups
Route::get('/', [CustomerController::class, 'index']); // {{host}}/api/customers/ this is called to index method in CustomerController.php
Route::post('/create', [CustomerController::class, 'create']); // {{host}}/api/customers/create this is called to create method in CustomerController.php
Route::post('/show/{id}', [CustomerController::class, 'show']); // {{host}}/api/customers/show/10 this is called to show method in CustomerController.php parsing id to get single data
Route::post('/delete/{id}', [CustomerController::class, 'delete']); // {{host}}/api/customers/delete/10 this is called to delete method in CustomerController.php for delete single data
});

Related

Issues with Middleware | Too few arguments to function App\Http\Middleware\HasPermission::handle()

This is the error I'm receiving when I try to load my index page
Too few arguments to function App\Http\Middleware\HasPermission::handle(), 2 passed in /app/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php on line 180 and exactly 3 expected
I'm using Spatie's Roles and Permissions Package, and have created a custom middleware HasPermission, to check if the user has the permissions to access and utilise the page they are trying to view.
This is the middleware
namespace App\Http\Middleware;
use Closure;
use Spatie\Permission\Models\Permission;
class HasPermission
{
public function handle($request, Closure $next,$permissions)
{
$permissions_array = explode('|', $permissions);
foreach($permissions_array as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
}
The controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use Spatie\Permission\Models\Role;
use DB;
use Hash;
use Illuminate\Support\Arr;
use App\Http\Middleware\HasPermission;
class UserController extends Controller
{
public function __construct() {
$this->middleware('permission:usermgmt.users|usermgmt.users.create|usermgmt.users.edit|users.delete', ['only' => ['index','store']]);
$this->middleware('permission:usermgmt.users.create', ['only' => ['create','store']]);
$this->middleware('permission:usermgmt.users.edit', ['only' => ['edit','update']]);
$this->middleware('permission:users.delete', ['only' => ['destroy']]);
}
And my routes
Route::middleware('HasPermission')->group(function() {
Route::get('/usermgmt/users', [App\Http\Controllers\UserController::class, 'index'])->name('usermgmt.users');
Route::resource('users', UserController::class);
Route::get('add-user', [App\Http\Controllers\UserController::class, 'create'])->name('usermgmt.users.create');
Route::delete('users/{user}',[App\Http\Controllers\UserController::class, 'destroy'])->name('users.destroy');
Route::get('users/{user}/edit', [App\Http\Controllers\UserController::class, 'edit'])->name('usermgmt.users.edit');
});
I have added the HasPermission middleware class to the Kernel.php, but am struggling to understand why I am receiving that error.
Any help would be appreciated, cheers.
I tried initially removing the Route Middleware Group and instead trying to do everything in the controller, and tried something like the below
$this->middleware(HasPermission::class, ['usermgmt.users','usermgmt.users.create','usermgmt.users.edit','users.delete'], ['only' => ['index','store']]);
But this would give me the same error as before.
Did you try this way:
public function handle(Request $request, Closure $next, ...$permissions)
{
foreach($permissions as $permission){
if (!$request->user()->hasPermission($permission)){
return redirect()->back();
}
}
return $next($request);
}
The in your controller, change the syntax:
$this->middleware('permission:usermgmt.users,usermgmt.users.create,usermgmt.users.edit,users.delete', ['only' => ['index','store']]);

Target class [PostController] does not exist. but it dose

The error I am getting is: Target class [PostController] does not exist but it does.
Route web.php
Route::get('/post', 'PostController#index');
Route::post('/post', 'PostController#store');
Route::get('/', function () {
return view('create');
});
PostController.php
namespace App\Http\Controllers;
use App\Post;
use Redirect,Response;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index()
{
return view('create');
}
public function store(Request $request)
{
$data = json_encode($request);
Post::create($data);
return back()->withSuccess('Data successfully store in json format');
}
}
This error comes in Laravel new version because there is no namespace prefix being applied to your route groups that your routes are loaded into. In the old version of Laravel, the RouteServiceProvider contained a $namespace property which would automatically be prefixed onto the controller route.
To solve this, you either can go to RouteServiceProvider and uncomment the line:
protected $namespace = 'App\\Http\\Controllers';
Or you can use closure-based syntax:
use App\Http\Controllers\PageController;
Route::get('/page', [PageController::class, 'index']);
Another way would be to use the fully qualified class names for your Controllers:
Route::get('/page', 'App\Http\Controllers\PageController#index');
use this line on the top of the (web.php) maybe your problem will resolve
use App\Http\Controllers\PostController;

Laravel 8 (version 8.35.1): Target class does not exist

I'm using laravel 8.35.1 version. I have a api-resource controller "ProductController". At my route file api.php. I define the route this:
api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResource('/products', 'App\Http\Controllers\ProductController');
Route::group(['prefix' => 'products'], function () {
Route::apiResource('/{product}/review', 'App\Http\Controllers\ReviewController');
});
NOTE:
It's work fine but, when i remove the complete path of controller like just write Route::apiResource('/products', 'ProductController'); it show error
Target class [ProductController] does not exist.
Before first clearing the cache. I want to get rid of the complete path. and second want to place the controllers in Api folder, so how to define route for that also.
I have also tried ProductController::class but not work fine
Updated
when I use the route according the laravel 8 doc. https://laravel.com/docs/8.x/controllers#resource-controllers it is working fine. but when move the controller file to Api folder then declare the route name space like use App\Http\Controllers\Api\ProductController; show error again
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ProductController;
use App\Http\Controllers\ReviewController;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResource('/products', ProductController::class);
Route::group(['prefix' => 'products'], function () {
Route::apiResource('/{products}/reviews', ReviewController::class);
});
You dont have to use class on declare controller in routing.
You may change 'ProductController' instead ProductController::class
When i try this then it work fine for me.
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ReviewController;
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
Route::apiResource('/products', 'App\Http\Controllers\ProductController');
Route::group(['prefix' => 'products'], function () {
Route::apiResource('/{product}/reviews', [ReviewController::class, 'ReviewController']);
});

Invalid route action: [ProductController]

I have my view as follow resources/views/shop/index.blade.php
I have a controller named ProductController.
In the route, I have the following
Route::get('/', [
'uses' => 'ProductConroller',
'as' => 'product.index'
]);
There is an error;
ProductController` is not invokable.
The controller class ProductController is not invokable. Did you forget to add the __invoke method or is the controller's method missing in your routes file?
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
//
public function getIndex()
{
return view('shop.index');
}
}
Please, I don't know what to do else. I have tried everything. Laravel 8
I finally got it by using
use App\Http\Controllers\ProductController;
Route::get('/', [ProductController::class, 'getIndex']);
It is funny though, it took me several hours to figure what is needed to be done.

Laravel controller / store

I am new to laravel, i am trying to store a tweet to database and i need to insert user id, but this gives me an error
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Tweet;
class TweetController extends Controller
{
public function store(Request $request){
return Tweet::create([ 'tweet' => request('tweet'), 'user_id' => Auth::id()]);
}
}
error i recive:
App\Http\Controllers\Auth' not found in file
/Applications/AMPPS/www/Twitter/Twitter/app/Http/Controllers/TweetController.php
Any idea?
Yes, you are missing the import, that's why it tries to find it in the Controller location, so put
use Illuminate\Support\Facades\Auth;
// or
use Auth; // you must have the Auth alias in the config/app.php array
as an import, or use the helper function auth()->id() instead.
So instead of mass-assigning the user, you can do the following, in your User model add this:
public function tweets()
{
return $this->hasMany(Tweet::class);
}
Then in your controller just do this:
auth()->user()->tweets()->create([ 'tweet' => request('tweet') ]);
You can use auth() helper to get user id:
auth()->user()->id

Resources