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

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;

Related

I am getting target class does not exist error in laravel 8

The routing process has changed in Laravel version 8. I did as in the internet but it gives an error. Where am I doing wrong?
Route file
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Backend\BackendHomeController;
Route::get('/', function () {
return view('welcome');
});
Route::get('/admin', [BackendHomeController::class, 'index'])->name("index");
Controller file
<?php
namespace App\Http\Controllers\Backend;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class HomeController extends Controller
{
public static function index()
{
return view("backend.index");
}
}
BackendHomeController also like this. Everything seems to be correct, but am I doing something wrong with using?
Error says
target class does not exist error
Class is referenced as BackendHomeController but your file is named HomeController. These should align for autoloading to be working.

Laravel - forgetParameter

My project is multi language, so in most route I add parameter "locale". But latter I do not need to pass "locale" parameter to my controllers. I try to remove this parameter using forgetParameter() method but when I use this method then I have error "Route not bound".
So what I'm doing wrong.
How to remove "locale" from all routes?
Laravel 5.8
My route file.
Route::group(['prefix' => '{locale}','where' => ['locale' => '[a-zA-Z]{2}']], function() {
Auth::routes([app()->getLocale()]);
Route::get('/', 'HomeController#index')->name('mainPage');
Route::get('/user/{id}','UserController#showUser')->name('getUserProfile')->forgetParameter('locale');
Route::get('/user/{id}/edit','UserController#editUser')->name('editUserProfile')
->middleware('can:editUser,App\User,id')->forgetParameter('locale');
Route::patch('/user/{id}/edit','UserController#updateUser')->name('updateUserProfile')
->middleware('can:updateUser,App\User,id')->forgetParameter('locale');
});
It's not duplicate with this question - Laravel 5.4: How to DO NOT use route parameter in controller
Solution in that question doesn't work in my case. And my question is why "forgotParamter()" throw an error?
Other question is, why I can't use this construction in middleware:
$request->route()->forgetParameter('locale')
I have following error:
Call to a member function is() on null
Thank you.
Try to forget the parameter in an inline middleware in the controller's constructor. Actually, I would use a base controller: 1, get the route value; 2, set to a protected property, so inherited controllers can access to the value; 3, forget the parameter.
<?php
// Localized/Controller.php
namespace App\Http\Controllers\Localized;
use App\Http\Controllers\Controller as ControllerBase;
use Illuminate\Http\Request;
class Controller extends ControllerBase
{
protected string $currentLocale;
public function __construct()
{
$this->middleware(function ($request, $next) {
// If you need to access this later on inherited controllers
$this->currentLocale = $request->route('locale') ?? 'en';
// Other operations, like setting the locale or check if lang is available, etc
$request->route()->forgetParameter('locale');
return $next($request);
});
}
}
<?php
// Localized/UserController.php
namespace App\Http\Controllers\Localized;
use Illuminate\Http\Request;
// Extends the our base controller instead of App\Http\Controllers\Controller
class UserController extends Controller
{
public function show(Request $request)
{
// No need of string $locale arg
dd($this->currentLocale);
}
}

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

Error on finding controller from Laravel API Router

I created a fresh Laravel framework.
I created a controller named PostsController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Http\Controllers\Controller;
class PostsController extends Controller
{
public function index()
{
$posts = Post::get();
return response()->success(compact('posts'));
}
}
Then I created a route in the file api.php:
Route::get('posts', 'PostsController#index');
I ran the command
$ php artisan serve`
and I tested the URL
localhost:8000/api/posts
This error occurs:
BadMethodCallException
Method Illuminate\Routing\ResponseFactory::success does not exist.
file: vendor/laravel/framework/src/Illuminate/Support/Traits/Macroable.php
line: 100
throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
I can't understand why this happened. Please help me.
There is no success method on the ResponseFactory. You can find the available methods here.
You are calling a macro function that is not registerd to the responseFactory.To use success method,Create your custom responseServiceProvider and write this inside boot()
Response::macro('success',function($data){
return Response::json([
'data'=>$data,
]) ;
});
And then register your ResponseServiceProvider to app.php by adding your Class name to the array called providers. This is how you add to the array
App\Providers\ResponseMacroServiceProvider::class

Passing a variable to a master template in laravel

In laravel i have defined a route like this
Route::get('/', array(){
'as' => 'index',
'uses' => 'HomeController#index'
});
The function index() in the HomeController contains
public function index(){
$index = new ExampleModel;
$data = $index->getExampleList();
return View::make('public.index');
}
Now the problem is i have a master layout called happypath inside layouts folder in my views which yields this public.index content and i need to pass this $data to layouts.happypath. How do i do this ?
You can use a view composer for example:
namespace App\Providers;
use App\ExampleModel;
use Illuminate\Support\ServiceProvider;
class ComposerServiceProvider extends ServiceProvider
{
protected $exampleModel;
public function __construct(ExampleModel $exampleModel)
{
$this->exampleModel = $exampleModel;
}
public function boot()
{
view()->composer('layouts.happypath', function ($view) {
$view->with('publicIndex', $this->exampleModel->getExampleList());
});
}
public function register()
{
//
}
}
So, every time you use/render the layouts.happypath the $publicIndex variable will be attached within the layout. Also you need to add the ComposerServiceProvider class in your config/app.php file in the providers array. You may access/reference the data using $publicIndex variable in your layout. There are other ways like global shared $information using view()->share(...) method to share a peace of data all over the views but this may help you.
I could not figure out the ComposerServiceProvider View::composer thing. So i basically solved it like this in Laravel 4.2. Added this code to the BaseController.php
protected $menuList;
public function __construct() {
$response = API::pool([
['GET', API::url('level')],
]);
$index = new Index();
$index->setCourseList($response[0]->json()['Category']);
$result = $index->getCourseList();
View::share('result', $result); //This line shares the $result globally across all the views in laravel 4.2
}
This can be done with a Service Provider. You can either use an existing one or create a new one.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\ExampleModel;
class ViewServiceProvider extends ServiceProvider
{
public function boot()
{
$index = new ExampleModel;
$data = $index->getExampleList();
view()->share('public.index', $data);
}
public function register()
{
}
}
Source: EasyLaravel.com

Resources