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

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']);
});

Related

Laravel edit route for basic CRUD application giving 404

I'm trying to set up a basic Laravel 9 CRUD application, and I cannot get the edit route working for the User Controller.
routes/web.php
Route::get('/dashboard', function () { return view('dashboard'); })
->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{$id}/edit','edit')->middleware('auth');
Route::post('user/{$id}/edit','update')->middleware('auth');
Route::get('user/{$id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
UserController.php
class UserController extends Controller
{
function edit(int $id)
{
echo 123;
}
I'm getting a 404 NOT FOUND page
Also, why don't I see the stack trace for this error?
Also, in some examples, I've seen people using the model class name as the parameter type in the controller method declaration, such as:
function edit(User $id)
{
echo 123;
}
However, I've also seen other examples using int instead. So which is the correct one?
First, inside your .env filte you should put
APP_ENV=local
APP_DEBUG=true
and change your web.php to:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
Then, try to run
php artisan route:list
and check if your routes are correct.
And try to remove middlewares inside user files, maybe you do not have login page and it redirects you there.
Be sure you are in the correct url like localhost/user/1/edit
Parameters in routes don't take a starting $. Change all occurrences of {$id} in your routes to just {id}:
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
More on Route Parameters
Edit: you might also want to take a look at Resource Controllers. Something like Route::resource('users', UserController::class); will manage all of the required routes

Route group prefix not working in Laravel 8

I was trying to make a group routing with a prefix in Laravel 8. But when I tested it in http://localhost/mysite/admin/test/, it always throws error 404.
Here is the code in web.php:
Route::prefix('/admin', function() {
Route::get('/test', [Admin\LoginController::class, 'index']);
});
I created a controller in app/Http/Controller/Admin/ as the controller is inside Admin folder.
Here is the code in LoginController:
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class LoginController extends Controller
{
public function __construct()
{
//
}
public function index()
{
echo "Please login";
}
}
Can anybody show me what I am doing wrong to get it working?
You have to group the routes as stated in the documentation like:
Route::prefix('admin')->group(function () {
Route::get('/test', function () {
// Matches The "/admin/users" URL
});
});
In your case it would be:
use App\Http\Controllers\Admin\LoginController;
Route::prefix('admin')->group(function () {
Route::get('/test', [LoginController::class, 'index']);
});
I think it should be 'admin' not '/admin'.
That slash makes it:
http://localhost/mysite//admin/test
=>
http://localhost/admin/test
You can check all your routes using: php artisan route:list
Try this
use App\Http\Controllers\Admin\LoginController;
Route::prefix('admin')->group(function () {
Route::get('test', ['LoginController::class, index'])->name('test'); });

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;

How to call an Api Controller from API route in 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
});

Laravel-Lumen get request with parameter doesn't work

I'm facing a strange issue with lumen, all post and get request are working fine but only the get requests with parameter is not with below error
NotFoundHttpException
in RoutesRequests.php line 229
at Application->Laravel\Lumen\Concerns\{closure}(object(Request))
in RoutesRequests.php line 416
Here is my Web.php
$router->get('/', function () use ($router) {
return $router->app->version();
});
$router->group(['prefix' => 'api'], function () use ($router) {
$router->post('login','UserController#login');
$router->post('signup','UserController#signup');
$router->patch('profile','UserController#update');
$router->post('verfiy','UserController#verfiy');
$router->post('order','OrderController#store');
$router->get('userorders/{$uid}','OrderController#userOrder');
$router->get('locations/{$province}','LocationController#list');
$router->get('offers/{$province}','OfferController#list');
});
And this is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Offer;
class OfferController extends Controller
{
public function list($province)
{
$offers = Offer::where('province',$province)
->orderBy('num_orders', 'desc')
->paginate(20);
return response()->json(['status_code'=>1000,'data'=>$offers , 'message'=>null],200);
}
}
If i remove the parameter from the route and the controller it works and I have another Lumen project on same device and its works all fine with all requests !!??
Im on mac and apache
Any help will be much appreciated
You should define a route like:
$router->get('offers/{province}','OfferController#list');
and not like:
$router->get('offers/{$province}','OfferController#list');
Note the {province} difference.

Resources