Laravel 5.1 throws ReflectionException after upgrade from 5.0 - laravel

I have recently upgraded Laravel to version 5.1 from 5.0, but whenever I send an API response to the server, it throws an exception like the following:
ReflectionException in RouteDependencyResolverTrait.php line 57: Class App\Http\Requests\User\GetRequest does not exist
Before upgrading everything was working fine.
This is the autoload section of my composer.json file:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/",
"Bloom\\" : "library/Bloom"
}
}
Could it be that I did something went wrong during the upgrade procedure?
This is how the GetRequest class is declared:
<?php namespace App\Http\Requests\User;
use App\User;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Auth;
/**
* Class GetRequest
* #package App\Http\Requests\User
*/
class GetRequest extends Request {
Update: I just reinstalled Laravel 5.1 and moved all the old files to the new installation but I still receive the same error.
Update 2: After running php composer dump-autoload -o I can notice that the file vendor/composer/autoload_classmap.php contains the class that Laravel is unable to find:
'App\\Http\\Requests\\User\\GetRequest' => $baseDir . '/app/Http/Requests/User/GetRequest.php',
Update 3: I tried also to create a new request using
php artisan make:request TestRequest
and then using the TestRequest in the UserController.php
/**
* #param GetRequest $request
* #return \Symfony\Component\HttpFoundation\Response
*/
public function get(TestRequest $request)
{
if(!$this->userRepository->getUser()) return $this->respondOK('User not found.');
$user = $this->userRepository->getUser();
return $this->respondOK('', (new UserTransformer())->transform($user->toArray()));
}
but I still receive the same error.

OK, I found the solution.
I noticed that if in GetRequest class I swap use App\Http\Requests\Request; with use Request; then the GetRequest class is found and the ReflectionException is not thrown anymore.
So the problem is not in the App\Http\Requests\User\GetRequest class but in the abstract class App\Http\Requests\Request.
After looking at the App\Http\Requests\Request class, to which I made changes, I decided to replace it with the dist version from Laravel and then I reapplied my changes.
Long story short: The problem was in App\Http\Requests\Request because I made changes to it and something changed with the update to Laravel 5.1.

I've got the same problem. Currently I found the solution as specify "use" in the controller that used new request class.
Set "use" in controller for right path to the request files:
use App\Http\Requests\Request;
use App\Http\Requests\YOUR_NEW_REQUEST_CLASSRequest;

Related

Laravel Package: How to register a third party facade inside a custom package?

I'm creating a package that uses internally this hashid package.
How can I register a third party facade inside a custom package?
I tried three options and none of them worked.
Version - Composer
"aliases": {
"Hashids": "Vinkla\\Hashids\\Facades\\Hashids"
}
Version - inside my ServiceProvider with alias
class MyPackageServiceProvider extends ServiceProvider
{
public function register()
{
...
$this->app->alias(\Vinkla\Hashids\Facades\Hashids::class, 'Hashids');
}
Version - inside my ServiceProvider with AliasLoader
class MyPackageServiceProvider extends ServiceProvider
{
public function register()
{
...
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Hashids', \Vinkla\Hashids\Facades\Hashids::class);
}
When I'm testing the code, I get the error:
Error: Call to undefined method Vinkla\Hashids\Facades\Hashids::encode()
inside
/** #test */
public something_to_test()
{
dd(\Hashids::encode(1));
}
Ok I found one solution, but I am still confused why it is like that.
In my "MyPackageServiceProvider" I need to add:
$this->app->register(HashidsServiceProvider::class);
Why do I need to register a Provider? I thought the composer is handling the work.
At the end only this works:
$this->app->register(HashidsServiceProvider::class);
$loader = \Illuminate\Foundation\AliasLoader::getInstance();
$loader->alias('Hashids', \Vinkla\Hashids\Facades\Hashids::class);
The other versions doesn't work as well :(

Does defaults() method exist in Password?

i made a service provider to validate the password in Laravel 8, but i get this error:
Call to undefined method Illuminate\Validation\Rules\Password::defaults()
PasswordRuleServiceProvider was added in app.php
// Custom Service Providers
App\Providers\PasswordRuleServiceProvider::class,
This is the provider:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
class PasswordRuleServiceProvider extends ServiceProvider
{
public function register()
{
//
}
public function boot()
{
Password::defaults(function () {
$rule = Password::min(8)->letters()->mixedCase()->numbers()->symbols()->uncompromised(3);
return $rule;
});
}
}
I followed the Laravel doc to do this but it doesn't work, does the defaults method exist in Password? Thanks.
As you can see in the commit history of that Password class, this method did not exist until Laravel v8.42.0 (released on May 18th 2021). Make sure that you are using at least that version if you want to call such a method.
Next time, you should check the source code in your project for such methods, and not any other version on the internet. The source code you've linked might be newer than that

JWTGenerateCommand::handle() does not exist

I am using Laravel 5.4 and JWT Auth Library for user authentication in API development. After installation while i am running php artisan jwt:generate then it throws me error of
Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist
Any idea what i am missing ?
This error generally display when you install jwt package in laravel 5.5 version. then after you set service providers and run following command.
php artisan jwt:generate
then you seen this error message in terminal.
how to resolve it? simple follow this step
Step - 1 Re-install package
composer require tymon/jwt-auth:dev-develop --prefer-source
or the following is a new release package use laravel 6.X
composer require tymon/jwt-auth:1.0.*
in this developement version this errors fixed.
Step - 2 Set Service Provider
'providers' => [
....
Tymon\JWTAuth\Providers\JWTAuthServiceProvider::class to
Tymon\JWTAuth\Providers\LaravelServiceProvider::class
],
Step - 3 Generate key
php artisan jwt:secret
i found this solution from here https://laravelcode.com/post/method-tymonjwtauthcommandsjwtgeneratecommandhandle-does-not-exist
Go to JWTGenerateCommand.php file located in vendor/tymon/src/Commands and paste this method
public function handle() { $this->fire(); }
It's never a great idea to change anything in the vendor folder but the there's two ways to deal with this ...
Generate a random string yourself and just change the value in the JWT config file.
Go to Tymon\JWTAuth\Commands\JWTGenerateCommand and change the fire method to handle.
go to given file path
vendor/tymon/jwt-auth/src/Commands/JWTGenerateCommand.php
change function name
public function fire() to public function handle()
run command:
php artisan jwt:generate
I'm publishing this answer because I have crash in this error more than one time.
The only solution I found that it works with Laravel 5.6 is the following:
Add "tymon/jwt-auth": "1.0.0-rc.1" to composer.json and run composer update
Open config/app.php and add the following:
config/app.php:
'providers' => [
/*
* JWT Service Provider...
*/
Tymon\JWTAuth\Providers\LaravelServiceProvider::class,
],
'aliases' => [
'JWTAuth' => Tymon\JWTAuth\Facades\JWTAuth::class,
'JWTFactory' => Tymon\JWTAuth\Facades\JWTFactory::class,
],
Execute:
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Finally, execute: php artisan jwt:secret
After all that, when I hit my endpoint for login I got the following exception:
Class Tymon\JWTAuth\Providers\JWT\NamshiAdapter does not exist
This was fixed by:
Open config/jwt.php and change the following:
config/jwt.php:
'jwt' => Tymon\JWTAuth\Providers\JWT\Namshi::class,
'auth' => Tymon\JWTAuth\Providers\Auth\Illuminate::class,
'storage' => Tymon\JWTAuth\Providers\Storage\Illuminate::class,
Finally, note that in order to work your User model should be defined as follows:
class User extends Authenticatable implements JWTSubject
{
...
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
...
}
I can advise one solution. Go to JWTGenerateCommand.php file located in vendor/tymon/src/Commands and paste this part of code public function handle() { $this->fire(); }
I know this is not an elegant solution, but it works. I hope this might help until official fix arrive.
see here for more info
Change fire() function to handle() in this path
vendor/tymon/jwt-auth/src/commands/JWTGenerateCommand.php
In the file path: /vendor/tymon/jwt-auth/src/Commands/JWTGenerateCommand.php
Add public function
public function handle()
{
$this->fire();
}

Subclassing Migrator not working for namespaced migration

I have some namespaced migrations, and I can't get past the Class Not Found errors due to namespacing. In an earlier question, Antonio Carlos Ribeiro stated:
Laravel migrator doesn't play nice with namespaced migrations. Your best bet in this case is to subclass and substitute the Migrator class, like Christopher Pitt explains in his blog post: https://medium.com/laravel-4/6e75f99cdb0.
I have tried doing so (followed by composer dump-autoload, of course), but am continuing to receive Class Not Found errors. I've got the project files set up as
inetpub
|--appTruancy
|--database
|--2015_04_24_153942_truancy_create_districts.php
|--MigrationsServiceProvider.php
|--Migrator.php
The migration file itself is as follows:
<?php
namespace Truancy;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class TruancyCreateDistricts extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('districts', function($table) {
$table->string('id')->unique()->primary()->nullable(false);
$table->string('district');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('districts');
}
}
Migrator.php is as follows:
namespace Truancy;
use Illuminate\Database\Migrations\Migrator as Base;
class Migrator extends Base{
/**
* Resolve a migration instance from a file.
*
* #param string $file
* #return object
*/
public function resolve($file)
{
$file = implode("_", array_slice(explode("_", $file), 4));
$class = "Truancy\\" . studly_case($file);
return new $class;
}
}
MigrationServiceProvider.php is as follows:
<?php
namespace Truancy;
use Illuminate\Support\ServiceProvider;
class TruancyServiceProvider extends ServiceProvider{
public function register()
{
$this->app->bindShared(
"migrator",
function () {
return new Migrator(
$this->app->make("migration.repository"),
$this->app->make("db"),
$this->app->make("files")
);
}
);
}
}
The lines generated in autoload_classmap.php are as expected:
'Truancy\\Migrator' => $baseDir . '/appTruancy/database/migrations/Migrator.php',
'Truancy\\TruancyCreateDistricts' => $baseDir . '/appTruancy/database/migrations/2015_04_24_153942_truancy_create_districts.php',
'Truancy\\TruancyServiceProvider' => $baseDir . '/appTruancy/database/migrations/MigrationsServiceProvider.php'
I'm calling php artisan migrate --path="appTruancy/database/migrations" and I receive the error:
PHP Fatal error: Class 'TruancyCreateDistricts' not found in
C:\inetpub\laravel\vendor\laravel\framework\src\Illuminate\Database
\Migrations\Migrator.php on line 297
I know I must be doing something dumb (my instinct is $class = "Truancy\\" . studly_case($file); in Migrator.php is wrong), but I can't unscrew this lightbulb. The migrate command is obviously successfully finding my migrations file, and the correct classname is in the classmap, so it has to be somewhere in the process of resolving the classname itself from the file, which the subclass and substitution is supposed to address. Any suggestions as to where I've gone wrong?
Ok, I've gotten this working. It turns out that the Medium.com article assumes you'd just know where to put the files he talks about, which I didn't. I've made several changes, and now everything is working correctly:
I created a new appTruancy\providers subfolder, and add it to composer.json
I moved both Migrator.php and MigrationServiceProvider.php into the new folder
I changed the namespace in both of those files to Truancy\Providers to match the directory structure
I added 'Truancy\Providers\MigrationsServiceProvider' to the providers array in appTruancy\config\app.php
I added a \ in front of Schema in the migration file to reference the base namespace.
I ran dump-autoload to update the classmap
This is one of those cases where I'm not 100% certain that all of the changes were required, but the layout does make sense so I'm happy with it. So, in a nutshell, if you're trying to namespace your migrations, you need to subclass the Migrator class as described in the Medium.com article listed above, but you then need to register the service provider in config\app, making sure the class names in both files are consistent.

How to register a namespace in laravel 4

The problem:
class PostRepostioryInterface not found for line 4 in PostController.php
or in tinkering with the namespace I've even got class
App\Models\Interfaces\PostRepositoryInterface not found
The questions: How to register a namespace in laravel 4? What do I need to do to get L4 to recognise the classes/interfaces at this namespace?
Larave 3 had a $namespaces static object in ClassLoader where you could add namespaces by
Autoloader::namespaces(array(
'App\Models\Interfaces' => path('app').'models/interfaces',
));
I'm not sure if I have that right for laravel 3 but either way, AutoLoader doesn't exist in Laravel 4 and ClassLoader exists but the method namespaces doesn't exist in ClassLoader in Laravel 4.
I've looked at this but it doesn't seem to work without registering the namespace somehow.
Using namespaces in Laravel 4
Example structure:
app/models/interfaces
PostRepostitoryInterface.php
app/models/repositories
EloquentPostRepository.php
namespaces:
App\Models\Repositories;
App\Models\Interfaces;
the files:
PostRepositoryInterface.php
<?php namespace App\Models\Interfaces;
interface PostRepositoryInterface {
public function all();
public function find($id);
public function store($data);
}
EloquentPostRepository.php
<?php namespace App\Models\Repositories;
use App\Models\Interfaces\PostRepositoryInterface;
class EloquentPostRepository implements PostRepositoryInterface {
public function all()
{
return Post::all();
}
public function find($id)
{
return Post::find($id);
}
public function store($data)
{
return Post::save($data);
}
}
PostController.php
<?php
use App\Models\Interfaces\PostRepositoryInterface;
class PostsController extends BaseController {
public function __construct( PostRepositoryInterface $posts )
{
$this->posts = $posts;
}
Thanks
You probably forgot to do composer dump-autoload. This updates the list of classes Laravel autoloads.
You can read more on composer documentation.
On the laravel irc channel I found out the namespaces should work in L4 without a need for registering them anywhere. This is because the composer dump-autoload adds them to the composer/autoload file for me. So that was not an issue.
The issue turned out to be a typo apparently(I can't find it in the code above but after going through every line copy/pasting the class names and namespaces something changed), and also somehow in my real code I left out the 'use' statement for EloquentPostRepository.php
use App\Models\Interfaces\PostRepositoryInterface;
Now I've hit another wall trying to use the namespaced interface with ioc and the controller constructor (target interface App\Models\Interfaces\PostRepositoryInterface is not instantiable) but I guess that should be a different question.

Resources