I'm kinda new to laravel (5.7) and I'm stuck trying to create a registration form. the validation works great but then the page refresh and nothing happens, no errors, nothing changes on the registration form with no records on the database.
Here is my controller, I tweaked the basic form that laravel gives you to start with so it matches my database. And I created a folder for my models, so I changed the path to the "users" model that's all the tweaks I've done on this.
namespace App\Http\Controllers\Auth;
use App\Models\users;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users,User_Email',
'passowrd' => 'required|string|min:2|confirmed',
]);
}
protected function create(array $data)
{
return users::create([
'User_Nom' => $data['name'],
'User_Email' => $data['email'],
'User_pwd' => Hash::make($data['password']),
]);
}
}
I'm guessing that it has something to do with my Model but I can't put my finger in it. so here is my Model :
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class users extends Authenticatable
{
use Notifiable;
protected $primaryKey = 'User_Id';
protected $table = 'users';
protected $fillable = [
'User_Id', 'User_Nom', 'User_Prenom', 'User_pwd', 'User_Email', 'User_Tel', 'User_Fax', 'User_Post'
];
protected $hidden = [
'User_pwd', 'remember_token',
];
}
(Sorry for the indentation the copy - past messed it up)
Thank you
In your model, the namespace should also be changed to match the folder it's in. So: namespace App\Models;. Other than that, you have a typo in your validation: passowrd.
Check out https://laravel.com/docs/5.7/requests to see how you should receive the data in the controller.
How about calling the model like this ?
use App\users;
Related
I'm building a laravel project which is a community platform, so it's gonna need a follower logic (pretty similar to twitter, instagram, etc).
I already created the logic for authentication and profile, but, when researching and writing the code for the followers state and check if the user is following someone, i got the functions on my model, which now is something like:
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 Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array<int, string>
*/
protected $fillable = [
'name',
'email',
'password',
'phone',
'description',
'profilepicture',
'status',
];
/**
* The attributes that should be hidden for serialization.
*
* #var array<int, string>
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array<string, string>
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function following()
{
return $this->belongsToMany('App\Models\User', 'followers', 'follower_user_id', 'user_id')->withTimestamps();
}
public function isFollowing(User $user)
{
return !is_null($this->following()->where('user_id', $user->id)->first());
}
}
And on my Profile Controller, I have:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class Profile extends Controller
{
public function show($id)
{
$user = User::where('id', $id)->firstOrFail();
$me = Auth::user();
$is_edit_profile = (Auth::id() == $user->id);
$is_follow_button = (!$is_edit_profile) && (!$me->isFollowing($user));
return view('profile', ['user' => $user, 'is_edit_profile' => $is_edit_profile, 'is_follow_button' => $is_follow_button]);
}
}
But VSCode says that i have a undefined method isFollowing in my controller, in the line:
$is_follow_button = (!$is_edit_profile) && (!$me->isFollowing($user));
Someone have a clue of why is this happening?
I'm using Laravel 8.
It's one of my first big projects, so previously sorry for any rookie mistake.
Thanks for your time and help!
Auth::user() returns an object of type Illuminate\Contracts\Auth\Authenticatable which does not implement isFollowing
Option 1 : You can add #var annotation to specify the type of your object
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class Profile extends Controller
{
public function show($id)
{
$user = User::where('id', $id)->firstOrFail();
/** #var User $me */
$me = Auth::user();
$is_edit_profile = (Auth::id() == $user->id);
$is_follow_button = (!$is_edit_profile) && (!$me->isFollowing($user));
return view('profile', ['user' => $user, 'is_edit_profile' => $is_edit_profile, 'is_follow_button' => $is_follow_button]);
}
}
Option 2 : You can extends the Auth facade by creating a new facade with the expected return type :
namespace App\Extensions\Facades;
use App\Models\User;
/**
* #method static User user()
*/
class Auth extends \Illuminate\Support\Facades\Auth
{
}
And then you can use this facade instead of the previous one
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Extensions\Facades\Auth;
use App\Models\User;
class Profile extends Controller
{
public function show($id)
{
$user = User::where('id', $id)->firstOrFail();
$me = Auth::user();
$is_edit_profile = (Auth::id() == $user->id);
$is_follow_button = (!$is_edit_profile) && (!$me->isFollowing($user));
return view('profile', ['user' => $user, 'is_edit_profile' => $is_edit_profile, 'is_follow_button' => $is_follow_button]);
}
}
I want to create a model for my project but i don't know what's the different between the original MVC style and laravel default auth model
there's a directory different too. The original MVC was in Model folder, while the defaulth auth is in controller folder. I don't know why make a model inside the Controller folder
This is the code that's work ( laravel default auth model )
source : https://www.5balloons.info/changing-authentication-table-laravel/
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class CustomUser extends Authenticatable
{
use Notifiable;
protected $table = 'customusers';
protected $fillable = [
'name','username','email','passcode','active'
];
protected $hidden = [
'passcode',
];
}
while this code is not work with error Class 'App\Models\Authenticatable' not found
i can create a work around to use the class, but i need to understand why
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class TestUser extends Authenticatable
{
use HasFactory, Notifiable;
protected $table = 'testuser';
protected $fillable = [
'username','password',
];
protected $hidden = [
'password',
];
/*
public funtion getAuthPassword()
{
return $this-> passcode;
}
*/
}
I'm trying to generate a token to authenticate users in my Controller the following way:
namespace App\Http\Controllers\API;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use App\Models\User;
class AuthController extends Controller
{
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
$success['token'] = $user->createToken('myApp')->accessToken;
dd($success['token']);
}
}
Currently, I'm just trying to print out the token. And this is my User's model:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
const USER_FIRST_NAME_FIELD = "first_name";
const USER_LAST_NAME_FIELD = "last_name";
const USER_PREFERRED_NAME_FIELD = "preferred_name";
const USER_EMAIL_FIELD = "email";
const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
const USER_PASSWORD_FIELD = "password";
const USER_REMEMBER_TOKEN_FIELD = "remember_token";
const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
const USER_ACTIVE_FIELD = "active";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
self::USER_FIRST_NAME_FIELD,
self::USER_LAST_NAME_FIELD,
self::USER_PREFERRED_NAME_FIELD,
self::USER_EMAIL_FIELD,
self::USER_PASSWORD_FIELD,
self::USER_RECEIVE_NEWSLETTER_FIELD,
self::USER_ACTIVE_FIELD,
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
self::USER_PASSWORD_FIELD,
self::USER_REMEMBER_TOKEN_FIELD
];
/**
* Automatically creates password hash when password is submitted
*
* #param string $password
* #return void
*/
public function setPasswordAttribute(string $password) : void
{
$this->attributes['password'] = Hash::make($password);
}
}
As you can see I'm using HasApiTokens, Notifiable traits and nonetheless I'm getting an error from my controller saying:
Call to undefined method App\User::createToken()
Passport is installed and configured correctly.
Here's something weird:
When registering an user (I'm using a separate controller and also using a service) a token is created successfully:
Here's my controller:
<?php
namespace App\Http\Controllers\API;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use App\Http\Controllers\Controller;
use App\Http\Requests\RegisterUserRequest;
class UserController extends Controller
{
private $user;
public function __construct(UserService $user)
{
$this->user = $user;
}
public function store(RegisterUserRequest $request) : JsonResponse
{
// TODO: verify message on error
$user = $this->user->register($request->validated());
$token = $user->createToken('MyApp')->accessToken;
dd($token);
return response()->json(['status' => 201, 'user_id' => $user->id]);
}
}
Here's my service:
<?php
namespace App\Services;
use App\Models\User;
use App\Services\BaseServiceInterface;
class UserService implements BaseServiceInterface
{
public function register(array $formValues) : User
{
// 'terms and conditions' should not be saved into the db, hence it's removed
unset($formValues['terms_conditions']);
return User::create($formValues);
}
}
and here's my model again:
<?php
namespace App\Models;
use Illuminate\Notifications\Notifiable;
//use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\Hash;
use Laravel\Passport\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
const USER_FIRST_NAME_FIELD = "first_name";
const USER_LAST_NAME_FIELD = "last_name";
const USER_PREFERRED_NAME_FIELD = "preferred_name";
const USER_EMAIL_FIELD = "email";
const USER_EMAIL_VERIFIED_AT_FIELD = "email_verified_at";
const USER_PASSWORD_FIELD = "password";
const USER_REMEMBER_TOKEN_FIELD = "remember_token";
const USER_RECEIVE_NEWSLETTER_FIELD= "receive_newsletter";
const USER_ACTIVE_FIELD = "active";
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
self::USER_FIRST_NAME_FIELD,
self::USER_LAST_NAME_FIELD,
self::USER_PREFERRED_NAME_FIELD,
self::USER_EMAIL_FIELD,
self::USER_PASSWORD_FIELD,
self::USER_RECEIVE_NEWSLETTER_FIELD,
self::USER_ACTIVE_FIELD,
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
self::USER_PASSWORD_FIELD,
self::USER_REMEMBER_TOKEN_FIELD
];
As I told you, when creating a user the token is being generated correctly.
I'd say that Auth::user() is not calling my Model directly, but I don't know for sure that's what is happening.
Any idea why?
Thanks
Since your guard is returning the wrong User model, App\User, you should check your auth configuration, 'config/auth.php'. In the providers array adjust any provider, usually users, that is using the App\User model to App\Models\User instead.
'providers' => [
'users' => [
'driver' => 'eloquent',
// 'model' => App\User::class,
'model' => App\Models\User::class,
],
...
],
in my case, i missed to use Trait HasApiTokens
thats why laravel was unable to create tokens.
just open User.php
afetr name space include
use Laravel\Passport\HasApiTokens;
then inside class
use HasApiTokens
Pls note : I am using laravel 7.
So, this is not the right way to do it but it's working at the moment:
<?php
namespace App\Http\Controllers\API;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;
class AuthController extends BaseController
{
public function login()
{
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$authenticated_user = \Auth::user();
$user = User::find($authenticated_user->id);
dd($user->createToken('myApp')->accessToken);
}
dd('here');
}
}
Now I'm seeing the token.
I wanna do it the right way so I still would appreciate if any one could help me.
Thanks
you can let the auth.basic middleware do the authentication for you, by calling it in the construct method:
public function __construct()
{
$this->middleware('auth.basic');
}
Then generate the access token for the currently authenticated user, and return the user information along with the access token:
public function login()
{
$Accesstoken = Auth::user()->createToken('Access Token')->accessToken;
return Response(['User' => Auth::user(), 'Access Token' => $Accesstoken]);
}
Now the Controller will look like this:
<?php
namespace App\Http\Controllers\API;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\API\BaseController;
class AuthController extends BaseController
{
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth.basic');
}
public function login()
{
$Accesstoken = Auth::user()->createToken('Access Token')->accessToken;
return Response(['User' => Auth::user(), 'Access Token' => $Accesstoken]);
}
}
i have updated laravel 6 to 8 & i am using sanctum for API auth.
This works for me when i want to get token for API auth.
in User model
use Laravel\Sanctum\HasApiTokens;
and use the traits in function
use HasApiTokens
Model/User.php
<?php
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 Laravel\Sanctum\HasApiTokens;
use Hash;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $fillable = [
'name',
'email',
'password',
'status'
];
/**
* The attributes that should be hidden for serialization.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function setPasswordAttribute($input)
{
if ($input) {
$this->attributes['password'] = app('hash')->needsRehash($input) ? Hash::make($input) : $input;
}
}
public function roles()
{
return $this->belongsToMany(Role::class);
}
public function scopeActive($query){
return $query->where('status', 'ACTIVE');
}
}
So I have 2 User models, one is User and other is OrgUser for company users.
I'm trying to pass OrgUser to a OrgUserController and display single company user in show method. But I always get an empty object.
User Model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'verified', 'verification_token',
];
protected $hidden = [
'password', 'remember_token', 'verification_token',
];
OrgUser Model
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class OrgUser extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password', 'verified', 'verification_token', 'admin'
];
protected $hidden = [
'password', 'remember_token', 'verification_token',
];
OrgUserController
<?php
namespace App\Http\Controllers\OrgUser;
use App\Http\Resources\OrgUserResource;
use App\OrgUser;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
class OrgUserController extends ApiController
{
public function show(OrgUser $orgUser)
{
// OrgUserResource::withoutWrapping();
//
// return new OrgUserResource($orgUser);
return $orgUser;
}
Routes
Route::resource('orgusers', 'OrgUser\OrgUserController', ['only' => ['index', 'show']]);
Is there something that I would need to add to OrgUser model so I could pass data to controller like that? Because it works if I pass $id.
So It seems the problem was with naming in show method. I need to pass $orguser and not $orgUser. Because in my route it was /orgusers/{orguser}.
The show function should be accepting the $id rather than the model. If you change your code to the following, it should work:
public function show(Request $request, $id)
{
$orgUser = OrgUser::find($id);
return $orgUser;
}
I'm trying to build my first Laravel application by following a few guides on the internet and I'm feeling I'm missing something obvious. Here is the code.
Error
BadMethodCallException in Builder.php line 2450: Call to undefined
method Illuminate\Database\Query\Builder::addresses()
User-Model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Sentinel;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'email', 'password',
];
protected $hidden = [
'password',
'remember_token'
];
public function addresses()
{
return $this->hasMany('App\CustomerAddress');
}
}
CustomerAddress-model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerAddress extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
CustomerAddress-controller
<?php
namespace App\Http\Controllers;
use App\CustomerAddress;
use Illuminate\Http\Request;
class CustomerAddressController extends Controller
{
public function create(Request $request)
{
$address = new CustomerAddress();
$address->address = $request['address'];
$request->user()->addresses()->save($address);
}
}
Error appears after this piece of code:
$request->user()->addresses()->save($address);
Any ideas? Thanks and cheers
In .config/cartalyst.sentinel.php, change 'model' => 'Cartalyst\Sentinel\Users\EloquentUser' to 'model' => 'App\User' to use your user model with the addresses relation defined
In ./app/User change User extends Authenticatable to User extends \Cartalyst\Sentinel\Users\EloquentUser to extend sentinel's user to your app's User model
Finally, your controller code should now be
`$address = new CustomerAddress();
$address->address = $request->input('address');
$request->user()->addresses()->save($address);`
and everything should be peachy