Laravel Auth::user() has no code completion for User model functions - laravel

I am using Laravel and PHPStorm.
The auto completion works for all models, just not for the 'User', when I call it with Auth::user().
When I call the Auth::user() I get the right user object, but the return type of Auth::user() is Authenticatable and not User. So I get no code completion for my user object which is very anoying because I use it very often. I think the problem has something to do with the return type of Auth::user() because it is Authenticatable and not User.
In the config/auth.php I already set the model to app/User::class.
Can you tell me how to cast the return value to the User model?
In this example you can see the behaviour.

Add laravel-ide-helper package to your project - https://github.com/barryvdh/laravel-ide-helper.
The package generates a help file for the IDE with all the Facades and their functions.
It fixes the Facades auto-completion so Auth::user() is fixes too

I know this is an old post, but I'm still seeing the issue, in spite of using ide-helper.
In my Laravel app, Eloquent model App\User is set for "User Providers" in /config/auth.php:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
I just rebuilt the file _ide_helper.php by running:
php artisan ide-helper:generate
and this is what I see for Auth()::user()
* Get the currently authenticated user.
*
* #return \App\User|null \\this is desired
* #static
*/
public static function user()
{
/** #var \Illuminate\Auth\SessionGuard $instance */
return $instance->user();
}
Looking in the _ide_helper.php file, I see this:
Which results in undesired type hinting:
The end result, is that even with using the ide-helper, I'm still seeing the completion problems described by the OP.
The solution presented here solved a lot of related problems (the ide-helper package is a godsend), but I still have the OP's problem and the provided answer does not help.

Auth::user()
Auth is an Alias from ServiceProviders array in config/app.php if you directly use use Illuminate\Support\Facades\Auth;
you will get a nice completion in PHPstorm as well as Sublime but it depends on the IDE.

Related

Laravel 5.8 throws "Target [Illuminate\Database\Seeder] is not instantiable." on db:seed

The title basically summarises the question, but here's what I tried.
database/seeds/DatabaseSeeder.php is truncated to it's bare form - no uses and the call() method is commented. Still, I cannot run the command successfully. The problem seems to be coming from use Illuminate\Database\Seeder; at the top (link to laravel/laravel).
Running composer dump-autoload (even with -o option) doesn't resolve the issue. The version of Laravel I'm using is 5.8, which (as I've seen the bare DatabaseSeeder class on github) doesn't need to be namespaced, so namespacing turns out not to be the solution.
As a "stock Laravel utility" (if I may say so), it shouldn't need any additional setting-up (I mean adding to providers, bind()-ing and so on). Not sure if that's a direction I should take.
Edit: The seeder runs correctly when I set a --class argument. If I run php artisan db:seed --class=UsersTableSeeder it returns a success message. The thing is that I have more than 30 seeder classes and running them one by one everytime (I need to seed the table quite often because some of the configuration files are stored in the database with seeding) is not an option.
Edit 2: As I am not allowed to post the original contents of the DatabaseSeeder.php file, here is a stripped down version of it:
<?php
use Illuminate\Database\Seeder;
use CustomLocalPackage\Database\Seeds\UsersTableSeeder;
/* About 30 more use-s */
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call([
UsersTableSeeder::class,
/* About 30 more classes */
]);
}
}
Would be glad, if anyone can tell me what might be causing this issue and give me some directions on resolving it.

Is the '#' syntax in laravel routes depreciated?

Long time since i last coded in laravel, and when i tried registering a simple route in the API routes:
Route::post('/register', 'AuthController#register');
I got "Target class [AuthController] does not exist." error. I made it work by registering with:
use App\Http\Controllers\AuthController;
Route::post('/register', [AuthController::class, 'register']);
Confused, i gave a look at the docs and didn't find any reference to the first syntax. Is it gone and i am not knowing or i am doing something wrong?
The change was introduced in Laravel 8. Previously, routes were namespaced in the RouteServiceProvider:
// ...
protected $namespace = 'App\Http\Controllers';
That value comes set as null since v8+. That's why you have that error response. So you have two options:
A) Add the prefix in the RouteServiceProvider
B) Use the FQCN and import classes as you solved it (recommended, helps IDEs and static analysis AFAIK)

Suggestions on how to pragmatically allow one Laravel user to add another

I need on my Laravel set-up (which uses the standard Auth models/controller) to allow a logged-in user to create another user account on the site. As a shot in the dark, on my "add user" page, I did an include of the form from auth.register, and it showed up fine on the page (great!), but when I filled out the form and submitted it, it just reloaded the page, with no errors and the new user was not added to the database.
The things I'd need different than the standard auth.register are
1) There will be a column in the users table pairing the two users.
2) I want the verification email to be different than if they signed up on their own.
3) I was also thinking to not let the creating user choose a password, but have the new user reset their password via the initial email.
Is there any Laravel way of doing all this or will I have to write it myself?
1) There will be a column in the users table pairing the two users.
Take a look in your RegisterController and check out the use RegisterUsers trait included. Whatever you copy from this trait and move it to RegisterController, it gets overwritten by your logic rather than trait logic.
For the pairing, you can utilise create() method. A really pseudo way:
protected function create(array $data) {
$pair = // find a random user
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
'pair_id' => $pair->id
]);
}
2) I want the verification email to be different than if they signed up on their own.
For this, I am not sure where you trigger it already, but the email event lives in EventServiceProvider by default:
protected $listen = [
Registered::class => [
SendEmailVerificationNotification::class,
]
];
Change it your custom email and you should be good.
3) I was also thinking to not let the creating user choose a password, but have the new user reset their password via the initial email.
Again, in create() method, you can just assign a random password, and with your email, redirect them to the ResetPassword actions somehow. This needs some time to figure out for me now but see reset-password routes (with php artisan route:list), so what it accepts and in your custom email, place the button with necessary link.
Make sure you don't login the user right after registering in that case.
So, bottomline - the auth default logics live in their traits, and if you want to overwrite some, just copy/paste the method to your controller and tweak it as you wish.

Laravel 4.2 use Sentinel with Jenssegers MongoDB

Is it possible to use Cartalyst/Sentinel with Jenssegers/MongoDB on Laravel 4.2?
I'm currently using Sentry, but I want to try Sentinel with new features.
After installation, I tried this:
$user = Sentinel::register([
'email' => $email,
'password' => $password,
]);
But I've got the following error:
Argument 2 passed to Illuminate\Database\Query\Builder::__construct()
must be an instance of Illuminate\Database\Query\Grammars\Grammar,
null given, called in
/home/vagrant/shared/muzza/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
on line 1853 and defined
Sentinel doesn't have integration with Jenssegers MongoDB lib.
Dan Syme commented on 2 Jul:
You would have to write the implementations for the different models
used throughout Sentinel.
Then switch out the models for the different entities on the config
file with your own implementations, Sentinel should take care of
everything else.
Maxime-BHA commented on 3 Jul:
As #jenssegers already did for Sentry package, you have to create your
own Models extending the originals models from Sentinel and bind the
attributes defined in those models for relationships/persistances to
the new models etc.. like static $usersModel =
'Cartalyst\Sentinel\Users\EloquentUser'; and also change the config
file.
See exemple for Sentry there :
https://github.com/jenssegers/laravel-mongodb-sentry
I think it's the exact same procedure.
More information you can find here.

How can I render a twig template in a custom controller in Silex?

I'm playing with Silex microframework to build a very simple app.
The Silex documentation briefly illustrates how to keep your code organised using controller as class and I've also found this useful article talking about the same practice:
https://igor.io/2012/11/09/scaling-silex.html
but still can't solve my problem
The issue:
in my app.php I'm using
$app->get('/{artist}', 'MyNamespace\\MyController::getAlbum');
This is working. MyController is a class correctly loaded through composer using psr-4.
At the moment the return method of getAlbum($artist) is return $player;
What I'd like to do instead, is returning a twig view from getAlbum, something like:
return $app['twig']->render('player.twig', $player);
To do so, what I've tried to do in my custom class/controller is:
use Silex\Application;
use Symfony\Component\HttpFoundation\Request;
[...]
public function getAlbum(Request $request, Application $app, $artist)
but this is generating the following error when I try to access the routed pages:
ReflectionException in ControllerResolver.php line 43:
Class MyNamespace\Request does not exist
Whic made me think that there's a namespace conflict between myNamespace and the Silex namespaces?!
What am I doing wrong?
Is this the right way to make $app visible in my custom controller in order to use return $app['twig']... ?
Thank you in advance!
EDIT
After several other tries still didn't get to the point (replies still welcome!) but I've found a workaround solution that could be useful to anyone will incur in a similar issue. Directly in my app.php I added this
$app->get('/{artist}', function (Silex\Application $app, $artist) use ($app)
{
$object = new MyNamespace\MyController();
$player = $object->getAlbum($artist);
return $app['twig']->render('player.twig',
array(
//passing my custom method return to twig
'player' => $player,));
});
then in my player.twig I added:
{{player | raw}}
And this basically means that I still need an anonymous function to get use of my custom method which is a working solution I'm not really happy with because:
I'm using 2 functions for 1 purpose.
The return value of getAlbum is dependent from the use of "raw" in twig.
SOLVED
The workflow described works fine. It was a distraction error: I've placed the namespace of my custom class after use Symfony\Component\HttpFoundation\Request;
namespace declaration in PHP needs always to be at the top of the file, Silex wasn't able to injects $app and $request for this reason.

Resources