Laravel 8: undefined method 'createToken' intelephense(1013) - laravel-8

I have a problem with PHP intelephense, the method createToken is undefined. i don't know how to fix it. but when I run it in postman it works. i don't know why vscode doesnt recognize it. i also add the use Laravel\Passport\HasApiTokens; and use HasApiTokens in user model. please help me, I'm running out of options. thank you guys
public function login(Request $request)
{
$login = $request->validate([
'email' => 'required',
'password'=> 'required',
]);
if (!Auth::attempt($login)){
return response()->json(['message' => 'error']);
}
$user = Auth::user();
$token = $user->createToken('Token Name')->accessToken;
return response()->json(['user' => $user, 'token' => $token]);
}

I encountered the same problem and solved by adding the line. For my case.
/** #var \App\Models\MyUserModel $user **/
$user = Auth::user();
I think the annotation line tell PHP intelephense that $user variable is not Illuminate\Foundation\Auth\User type but \App\Models\MyUserModel type. Please try it.

in the model User add
use Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens;
}
try and tell me

Related

How can is possible to attach different roles to users in the exact moment of registration?

before starting I premise and humbly apologize: I am a neophyte regarding the use of Laravel framework. I Searched eveywhere even the documentation but without results.
My question is if it is possible to assign a role at registration time using the Laratrust library. We want for example that the first 4/5 users who register are administrators, from the fifth onwards are normal users with restricted permissions.
This is the code regarding the Controller for registration.
RegisterController.php
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\Models\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
if(Auth::id() < 4 ){
$user->attachRole('administrator');
}
else{
$user->attachRole('user');
}
return $user;
}
This is the method that aims to register the user from the form, for some reason when I go to take the current id of the user, the condition in the if statement is bypassed, in fact in the database in the table roles i always have users that are administrators. I am thinking that maybe the real problem is Auth Class beacuse if i understood correctly this class is used when a user is already logged.
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$checklatestid = User::latest()->pluck('id')->first();
if($checklatestid < 4 ){
$user->attachRole('administrator');
//Ruolo amministratore impianto scii
}
else{
$user->attachRole('user');
//Ruolo cliente impianto scii
}
return $user;
}
If understand you correctly

Update API in laravel 5.7

I have create API of update my project details, I test it in POSTMAN app it shows the success message but there no effect in the database.
Here are my code:
ProjectsController.php
public function UpdateProject($id)
{
$data = Input::all();
$q = Project::where('id',$id)->update($data);
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}
api.php
Route::post('UpdateProject/{id}','ProjectsController#UpdateProject');
Postman - see image.
output in postman:
{
"code": "200",
"message": "Project data update successfylly"
}
Can anyone help me out?
Thank you
I think you need to check all input details closely , it also comes with token when you submit the form so you need to save all details except token
Change this
$data = Input::all();
to this
$data = Input::except('_token');
I hope this resolves the issue.
in your model add fillable :
protected $fillable = ['name', 'project_group_id','number','ROM','address','city','state','zip','start_date','end_date','duration','description','timeline_type','project_type_id','project_category_id','office_id'];
You have forgotten to run the ->save() method after updating the data:
public function UpdateProject($id)
{
$data = Input::all();
$q = Project::find($id)
$q = $q->fill($data);
$q->save();
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}
You can use this method it will reduce your code
Route (api)
Route::post('UpdateProject/{project}','ProjectsController#UpdateProject');
ProjectsController.php
public function UpdateProject(Request $request, Project $project)
{
$data = $request->all();
$project->update($data);
return response()->json([
'code' => SUCCESS,
'message' => 'Project data update successfully'
]);
}

Laravel 5.6 - creation user not working

my application used to working well with registration user but now it dont.
here a portion of my model User
protected $fillable = [
'prenom', 'nom', 'email','photo_path','password',
];
here my validation function :
protected function validator(array $data)
{
return Validator::make($data, [
'prenom' => 'required|string|max:255',
'nom' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'photo_path' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:10000',
'password' => 'required|string|min:6|confirmed',
]);
}
here my create function :
protected function create(array $data)
{
dd($data);
$photoInput = request('photo_path');
$userPhotoPath='users';
$storagePhotoPath = Storage::disk('images')->put($userPhotoPath, $photoInput);
return User::create([
'prenom' => $data['prenom'],
'nom' => $data['nom'],
'email' => $data['email'],
'photo_path' => $storagePhotoPath,
'password' => Hash::make($data['password']),
]);
}
- POST request working ( return 302 ) but return back with input value
- Auth Route are declared in web.php
- Validation working well
but the php interpretor didnt get inside create function...
i just see in debugbar that information :
The given data was invalid./home/e7250/Laravel/ManageMyWorkLife/vendor/laravel/framework/src/Illuminate/Validation/Validator.php#306Illuminate\Validation\ValidationException
public function validate()
{
if ($this->fails()) {
throw new ValidationException($this);
}
$data = collect($this->getData())
but my validation working because i have error message near my InputTexte.
so i dont understand that error message ...
Do you have any clue ?
Well, you need to remove the dd(); function before you run something. Other wise it will end the execution of all other operations.
Check if your User Model has a constructor, if so remove it and check if the problem still accours. This fixed it for me.

ZF2 / doctrine ORM authentication different Entity

in my application (ZF2 / ORM) i have 3 Entities (with Single Table inheritance)
User
Owner extends User
Agent extends User
i want to make one single Authentication (Login) for the 3 Entity using
doctrine.authenticationservice.orm_default
module.config.php
//other doctrine config
'authentication' => array(
'orm_default' => array(
'object_manager' => 'Doctrine\ORM\EntityManager',
'identity_class' => 'Application\Entity\User',
'identity_property' => 'email',
'credential_property' => 'password',
'credential_callable' => function(User $user, $passwordGiven) {
return $user->getPassword() == md5($passwordGiven);
},
),
),
and the process of login
//LoginController.php
// ..data validation
$this->authService = $this->getServiceLocator()->get('doctrine.authenticationservice.orm_default');
$AuthAdapter = $this->authService->getAdapter();
$AuthAdapter->setIdentity($this->request->getPost('email'));
$AuthAdapter->setCredential(md5($this->request->getPost('password')));
$result = $this->authService->authenticate();
if($result->isValid()){
$identity = $result->getIdentity();
//continue
}
how can i do this process without caring about object type,
when i try to login with email of an Agent, i get this error
Catchable fatal error: Argument 1 passed to Application\Module::{closure}() must be an instance of User, instance of Application\Entity\Owner given
The error you mention is due to the type hint on:
function(User $user) {
Which leads me to believe that you have a missing namespace declaration in your config file; in which case you can either add it or use the FQCN.
function(\Application\Entity\User $user) {
Nevertheless, I don't think it's actually the problem. You can only define one 'identity_class' with doctrine authentication (which the adapter will use to load the entity from the entity manager). If you have multiple entity classes there is no way to have each of these tested with one adapter.
However, the configuration is really just creating a new authentication adapter, specifically DoctrineModule\Authentication\Adapter\ObjectRepository. One solution would be to create multiple ObjectRepository adapters, each with the correct configuration for the different entities and then loop through each of them while calling authenticate() on the Zend\Authentication\AuthenticationService.
For example :
public function methodUsedToAutheticate($username, $password)
{
// Assume we have an array of configured adapters in an array
foreach($adapters as $adapter) {
$adapter->setIdentity($username);
$adapter->setCredential($password);
// Authenticate using the new adapter
$result = $authService->authenticate($adapter);
if ($result->isValid()) {
// auth success
break;
}
}
return $result; // auth failed
}
As previously mentioned is the doctrine config will not allow for more than one adapter, so you would need to create them manually and remove your current configuration.
Another example
public function getServiceConfig()
{
return [
'factories' => [
'MyServiceThatDoesTheAuthetication' => function($sm) {
$service = new MyServiceThatDoesTheAuthetication();
// Assume some kind of api to add multiple adapters
$service->addAuthAdapter($sm->get('AuthAdapterUser'));
$service->addAuthAdapter($sm->get('AuthAdapterOwner'));
$service->addAuthAdapter($sm->get('AuthAdapterAgent'));
return $service;
},
'AuthAdapterAgent' => function($sm) {
return new DoctrineModule\Authentication\Adapter\ObjectRepository(array(
'object_manager' => $sm->get('ObjectManager'),
'identity_class' => 'Application\Entity\Agent',
'identity_property' => 'email',
'credential_property' => 'password'
));
},
'AuthAdapterOwner' => function($sm) {
return new DoctrineModule\Authentication\Adapter\ObjectRepository(array(
'object_manager' => $sm->get('ObjectManager'),
'identity_class' => 'Application\Entity\Owner',
'identity_property' => 'email',
'credential_property' => 'password'
));
},
// etc...
],
];
}
Hopefully this gives you some ideas as to what is required.
Lastly, if you would consider other modules, ZfcUser already has a 'chainable adapter' which actually does the above (but uses the event manager) so It might be worth taking a look at even if you don't use it.

Laravel 4 Authentication attempt() fails

I have a problem with Laravel authentication system:
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password'),
'active' => 1
);
if(Auth::attempt($credentials)){
echo "fine";
}else{
echo "fail";
}
Auth::attempt()always return false.
Therefore, I tried to authenticate an other way:
$user = User::where('email','=',Input::get('email'))->firstOrFail();
if ($user->active && Hash::check(Input::get('password'), $user->password)){
echo "fine";
}else{
echo "fail";
}
This one works.
Would you know what could possibly make the attempt method not working?
Your code is correct, but I think you have edited User model ( check if you still implement UserInterface and RemindableInterface for exemple)
https://github.com/laravel/laravel/blob/master/app/models/User.php