I use postman to add user or to login , user has added with sucess but I get this error
"Argument 1 passed to Tymon\JWTAuth\JWT::fromUser() must be an
instance of Tymon\JWTAuth\Contracts\JWTSubject, instance of App\User
given, called in C:\Users\Web
WorkStation\Desktop\laravelapp\jwtlaravel\vendor\tymon\jwt-auth\src\JWTAuth.php
on line 54"
and I found in this ligne this founction
public function attempt(array $credentials)
{
if (! $this->auth->byCredentials($credentials)) {
return false;
}
return $this->fromUser($this->user());
}
and this my user model :
<?php
namespace App;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','username','lastname','tel','tel',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
and this my register controller
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\User;
use JWTFactory;
use JWTAuth;
use Validator;
use Response;
class APIRegisterController extends Controller
{
//
public function register( Request $request){
$validator = Validator::make($request -> all(),[
'email' => 'required|string|email|max:255|unique:users',
'username' =>'required',
'tel' => 'required',
'name' => 'required',
'lastname' => 'required',
'adress' => 'required',
'password'=> 'required'
]);
if ($validator -> fails()) {
# code...
return response()->json($validator->errors());
}
User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'tel' => $request->get('tel'),
'username' => $request->get('username'),
'lastname' => $request->get('lastname'),
'adress' => $request->get('adress'),
'password'=> bcrypt($request->get('password'))
]);
$user = User::first();
$token = JWTAuth::fromUser($user);
return Response::json( compact('token'));
}
}
Implement the JWTSubject in your User model:
class User extends Authenticatable implements JWTSubject
This requires that the User Model implements this contract in your model:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements JWTSubject {
Or
you have to update your User model to implement the Tymon\JWTAuth\Contracts\JWTSubject interface:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Model implements JWTSubject{
/**
* Get the identifier that will be stored in the subject claim of the JWT.
*
* #return mixed
*/
public function getJWTIdentifier()
{
return $this->getKey();
}
/**
* Return a key value array, containing any custom claims to be added to the JWT.
*
* #return array
*/
public function getJWTCustomClaims()
{
return [];
}
}
Related
In my laravel 8 app I am trying to create two files CreateUserRequest and updateUserRequest to use personalized validations.
In the method rules I´m calling my model's variable $createRules but when I send my form, this don´t send, don´t show messages, error... Nothing.
I have attached CreateUserRequest, my model and controller's store method:
CreateUserRequest
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use App\Models\User;
class CreateUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return User::$createRules;
}
}
Model
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable, HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name',
'email',
'password',
'surname',
'experience',
'skills',
'education',
'location',
'profesion',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public static $createRules = [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|min:4|max:10|confirmed',
];
public static $updateRules = [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
];
}
Controller's store method
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use App\Http\Requests\CreateUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Models\Role;
use App\Models\User;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Str;
use Intervention\Image\ImageManagerStatic as Image;
use JamesDordoy\LaravelVueDatatable\Http\Resources\DataTableCollectionResource;
use Prettus\Validator\Exceptions\ValidatorException;
public function store(CreateUserRequest $request)
{
try {
$data = array(
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => password_hash($request->get('password'), PASSWORD_BCRYPT),
'api_token' => Str::random(60),
);
$user = User::create($data);
$roles = $request->get('roles');
// We assign the Client's role
if(empty($roles)) {
$user->assignRole(2);
} else {
foreach($roles as $rol){
$user->assignRole($rol);
}
}
} catch (ValidatorException $e) {
Flash::error($e->getMessage());
}
Flash::success('This is a message!');
return redirect()->route('users.index');
}
In the blade I have #include('flash::message') for getting flashed messages, and this view it´s included in other #include('admin.layouts.alertMessage').
I don´t know what I am doing wrong.
Thanks for help me and sorry for my bad English.
UPDATED
my problem i think that i don´t arrive to my controller. I´m doin echo in my function with one exit and load all my page without message echo
attach my form and my routes:
<form action="{{ route('users.store') }}" method="POST">
#csrf
#include('admin.users.fields')
</form>
routes
/** USERS BLOQ ROUTES */
Route::resource('users', UserController::class);
TBH, i didn't know that you can get validation logic from their Model. My advice is just copy paste your validation logic to the request. Since Request is only for Validation purpose ( CMIIW )
CreateRequest
public function rules()
{
return [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
'password' => 'required|min:4|max:10|confirmed',
];
}
UpdateRequest
public function rules()
{
return [
'name' => 'required|string|max:191',
'email' => 'required|string|email|max:191|unique:users',
];
}
UPDATE
Just combine it to one Requests, give RequiredIf for password request, in case your update route contains update
use Illuminate\Validation\Rule;
...
public function rules()
{
return [
'password' => Rule::requiredIf(str_contains(url()->current(), 'update')) . '|min:4|max:10|confirmed',
]
}
I have two completely separate code bases: React.js on the frontend and Laravel on the backend
I'm trying to verify the currently logged in user in order to store the filename that's being uploaded associated with the currently logged in user into my db.
In my logs I'm getting this error: local.ERROR: Call to a member function photos() which means auth()->user() is the problem but I just can't see how. I've tried too many ways to list here in terms of trying to rectify this problem. What am I doing wrong?
I'll list some things I've tried:
in the if() condition inside FileUploadController - if(auth()->user()), if(Auth::guard(api)->check()), if(Auth::check()).
Here's my FileUploadController code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class FileUploadController extends Controller {
public function uploadTest(Request $request) {
if($request->bearerToken()) {
auth()->user()->photos()->create([
'file_path' => $request->file('fileToUpload')->getClientOriginalExtension()
]);
return "file uploaded";
}
return "failed uploading";
}
}
Here's my User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use Notifiable, HasApiTokens;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function photos() {
return $this->hasMany(Photo::class);
}
}
Here's my Photo model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Photo extends Model
{
public function user() {
return $this->belongsTo(User::class);
}
}
Here's code for logging in the user inside my AuthController:
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean'
]);
$credentials = request(['email', 'password']);
if(!Auth::attempt($credentials))
return response()->json([
'message' => 'Unauthorized'
], 401);
$user = $request->user();
$tokenResult = $user->createToken('Personal Access Token');
$token = $tokenResult->token;
if ($request->remember_me)
$token->expires_at = Carbon::now()->addWeeks(1);
$token->save();
$request->session()->put("user", $user);
return response()->json([
'access_token' => $tokenResult->accessToken,
'token_type' => 'Bearer',
'expires_at' => Carbon::parse(
$tokenResult->token->expires_at
)->toDateTimeString(),
$user
]);
}
Error Message:
Call to undefined method App\User::roles()
I'm Tring to assign default role to new user But I failed to assigned it. All user information stored in database but Role can't stored in table. Where i mistaked in this code. Help me.My English not good, Sorry for miss-communication.
This is My Code of User.php, Role.php, RegisterController.php and HomeController.php Files. See and tell me "where i doing wrong?"
This is User.php File
namespace App;
use App\Role;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* #param string|array $roles
*/
public function authorizeRoles($roles)
{
if (is_array($roles)) {
return $this->hasAnyRole($roles) ||
abort(401, 'This action is unauthorized.');
}
return $this->hasRole($roles) ||
abort(401, 'This action is unauthorized.');
}
/**
* Check multiple roles
* #param array $roles
*/
public function hasAnyRole($roles)
{
return null !== $this->roles()->whereIn('name', $roles)->first();
}
/**
* Check one role
* #param string $role
*/
public function hasRole($role)
{
return null !== $this->roles()->where('name', $role)->first();
}
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
This is Role.php File
<?php
namespace App;
use App\User;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany(User::class);
}
}
This RegisterController.php File.
<?php
namespace App\Http\Controllers\Auth;
use App\Role;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
'password' => ['required', 'string', 'min:8', 'confirmed'],
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user
->roles()
->attach(Role::where('name', 'student')->first());
return $user;
}
This is my role_user database Table
User Database Table
Role Database Table
Refactor your create method in RegisterController.php file like this:
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$user
->roles()
->attach(Role::where('name', 'student')->first());
return $user;
}
your rest of the code will not run after return.
and add roles relation to User model like this:
public function roles()
{
return $this->belongsToMany(User::class);
}
You can update your create function with this
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role = new App\Role(['role' => 'student']);
$user->roles()->save($role);
return $user;
}
Source: https://laracasts.com/discuss/channels/laravel/attach-role-to-a-user-upon-registration?page=1
You don't currently have a roles() relation in your user model. Add the following
public function roles()
{
return $this->hasMany('App\Role');
}
When I try to register a user, I am getting an error:
Call to undefined method App\Models\User::create()
here is my User model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'first_name', 'last_name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
protected $table = 'users';
}
I have used the User model that is shipped with Laravel 5.5, but just moved it to the Models folder. I updated the config/auth file to point to App\Models\User. I have ran php artisan optimize and composer dump-autoload several times, to no avail.
Here is my Register Controller:
<?php
namespace App\Http\Controllers\Auth;
use App\Models\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller {
public $titles = [];
public $title = 'Registration';
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/home';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return \App\User
*/
protected function create(array $data)
{
return User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
public function showRegistrationForm() {
return view('auth.register')
->with('env', $this->env)
->with('titles', $this->titles)
->with('title', $this->title);
}
}
When extending Laravel User model from the Auth package, you should extend the User class from that package. The abstract class from package extends the Model and then you will have access to all model methods.
From Illuminate\Foundation\Auth\User:
class User extends Model implements
AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
}
I am trying to make register and log in in laravel 5.2, but am receiving
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Model::create() must be of the type array, null given, called in /Applications/XAMPP/xamppfiles/htdocs/blogs/app/Http/Controllers/RegisterationController.php on line 30
Here is my registerationcontroller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\User;
class RegisterationController extends Controller
{
//
public function create(){
return view('sessions.create');
}
public function store(){
//validate form
$this->validate(request(),[
'name' => 'required',
'email' => 'required|email',
'password' => 'required'
]);
//store the data
$user = User::create(request(['name','email','password']));
//login
auth()->login($user);
//redirect
return redirect()->home();
}
}
and here is the user model:
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function posts(){
return $this->hasMany(Post::class);
}
}
i am following video for laravel 5.4, not sure if this is the problem.
You are not passing an array to the function you are passing the result of a function called request() which probably does not exist.
So amend the call something like this
//$user = User::create(request(['name','email','password']));
$user = User::create(
[
$request->input('name'),
$request->input('email'),
$request->input('password')
]
);
or
$params = [ $request->input('name'),
$request->input('email'),
$request->input('password')
];
$user = User::create( $params );
or
User::create($request->only(['name','email','password']);