All about laravel authentication is based on users, but I have deleted the user model and replaced that with a company model, so, basically, I want my users (laravel authentication users) to be companies.
Laravel doesn't like this, it gives me
Type error: Argument 1 passed to Illuminate\Auth\SessionGuard::login() must be an instance of Illuminate\Contracts\Auth\Authenticatable, instance of App\company given, called in /home/dhiraj1site/Desktop/Documents/blog/vendor/laravel/framework/src/Illuminate/Auth/AuthManager.p
This error, and if I import authenticable class as suggested in similar questions. Laravel hates this and gives me a blank page.
I have companies model and a companies table, I want the users to sign up as companies, and login as companies. How should I go about this, I am really confused and stuck on this stage, please help me understand how authentication works (I have read authentication documentation several times) and how should I change 'Users' to 'companies'.
There are a couple of ways to skin this cat zuif. The 'Laravel' way would be to edit the settings in app/config/auth.php
In that file you'll need to change the line: 'model' => 'App\User' to 'model' => 'App\Company'.
The 'gotcha' with Laravel is that you must remember to implement the right interfaces in your new 'user' class, Company:
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Company extends \Eloquent implements UserInterface, RemindableInterface
{
...
}
Or for newer versions of Laravel, its' just one interface:
use Illuminate\Foundation\Auth\User as Authenticatable;
class Company extends Authenticatable
I've done this before and it worked well for me. You could also get creative with extending the User class, but I think above is what you are hunting for.
HTH
Related
I have followed the documentation very closely but something isn't working
https://laravel.com/docs/9.x/eloquent-relationships#one-to-many-polymorphic-relations
I am trying to add permissions into my code which will give a User access to a File or a Folder. I understand this needs a one-to-many polymorphic relationship as each Permission has one permissionable, while each File or Folder might have many permissions.
$table->morphs('permissionable'); in a migration adds the permissionable_type(string) and permissionable_id(integer) columns to the permissions table
The Permission model has been created with the relevant fillable columns and the permissionable method containing a morphTo():
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use App\Models\File;
class Permission extends Model
{
use HasFactory, SoftDeletes;
protected $fillable = [
'user_id',
'permissionable_type',
'permissionable_id',
'privilege',
];
/**
* Get the parent object (file or folder).
*/
public function permissionable()
{
return $this->morphTo();
}
}
The Folder and File models have both had the following methods added:
public function permissions()
{
return $this->morphMany(Permission::class, 'permissionable');
}
A Permission is going to be created which will share a File with a User
And then the Permission is found and it's permissionable is requested
dd(Permission::find(1)->permissionable);
Except this is where the area happens:
I have tried to follow the documentation religiously and all the answers I see online just say to check namespace or ensure that all Models have an extends Model which I have already done.
Let me know if there is any more information I need to provide, thanks in advance.
i think you just changes model File class name, it's ok.
because this model's name conflict with Facades File class name
Thanks to Noah and Erik for their answers. You both helped me find the solution which was on the following site.
https://laracasts.com/discuss/channels/general-discussion/polymorphic-relations-gives-class-staff-not-found
The types need to include the paths in the database
I have been struggling with this problem for couple of days and I've searched everywhere but couldn't find a logical solution.
I need multiple types of users in my project(admin, customer) because I need completely different backend logic for each type. So I decided to use multi-auth method in laravel(which AFAIK is the best solution for these cases). So I have multiple user classes for each type(and multiple tables in DB) including Admin and User classes. AdminAuth and UserAuth classes manage the Login and Register logic and routes are handled using middlewares.
Up till now there is no problem. The problem is that I need to use a single user class in another classes. For example consider the messaging logic(and there are many many similar use cases):
a Message class Model should have:
protected $fillable = [
'from_id', 'to_id', 'content', 'state'
];
public function sender(){
return $this->belongsTo(**User::class**);
}
public function receiver(){
return $this->belongsTo(**User::class**);
}
...
In the above model, I need to specify the User::class for senders and receivers, which can be either admins or users. So how can I tell Eloquent to use both models. Is it even possible? If not, what is the solution here?
I thought of using a higher level class named Person, for example, to hold the Admin or User object instances, but this way ORM can't manage to retrieve or store users from/in the appropriate tables automatically.
Any Suggestion is greatly appreciated.
I would advise you to use the following guidelines to handle such functionality; create a model for each user type but all of them should have a relationship with Laravel's default user class by keeping the user's id. Also, keep general properties in the user class and specific properties in each sub class, like customer's can have addresses and admins can have phone numbers, while the common things like the username can be kept in the user model. Then you won't need multiply forms for login, when a user logs in, you redirectly accordingly to the user's type in the default user record. Now for your messaging problem, use user the default user model to establish the relationship in messages as you shown above. Then defenping on the user's type, grant him different priviledges or features in the chat.
My Laravel project involves businesses and their employees. The main Eloquent models are Businesses, Users and Roles. A User can have multiple Roles, each with a different Business.
When it comes to authentication, the Laravel Auth setup is a good fit, with one exception: A User does not have an email address. Instead, each of their Roles has an email address, and the user can log in using any one of these.
My user object has the password and remember_token fields. It seems to me that this object should still implement the Illuminate\Contracts\Auth\Authenticatable interface, and that it should do so by importing the Illuminate\Auth\Authenticatable trait. Does this sound right?
When it comes to the Illuminate\Contracts\Auth\UserProvider interface:
I think that I can extend the Eloquent provider implementation, Illuminate\Auth\EloquentUserProvider, and override only the retrieveByCredentials() method, but I am not sure. Will I need to override other methods as well?
If I do extend the Eloquent provider implementation, how do I go about injecting the $hasher and $model arguments when I register the new user provider in the boot() method of my AuthServiceProvider. Where do these values come from (see below)?
public function boot()
{
$this->registerPolicies();
Auth::provider('role', function ($app) {
$hasher = ''; // ????
$model = ''; // ???
return new UserViaRoleProvider($hasher, $model);
});
}
After some experimentation, I found that it was easier to create my own implementation of the UserProvider interface. The only method which required a bit of thought was retrieveByCredentials(). It searches for the Role, then returns the related user.
Although I was successful in logging in, I ultimately abandoned the approach because there are other parts of the Auth system that assume there is a 1-to-1 relationship between user and email. For example, the Password Reset functionality.
To create a flexible controller and to use the IoC of Laravel, one would do the following (say for a table User)
Create interface UserInterface
Create class EloquentUserRepository implements UserInterface
App::bind the interface to the implement
But, then you also create a model User that extends Eloquent, and your EloquentUserRepository then basically calls this model. Other than the provided Eloquent functions, if you create a custom function or relation in User, then you need to create a function in EloquentUserRepository that simply returns that. Isn't that repetitive? Is there a way to directly have the model implement the interface?
Isn't that repetitive?
Yes. Unless you have a specific need - you can run the risk of 'over engineering' or 'over abstracting' your application.
If you dont plan to swap out your 'users' with anything in the future - there is no need to do so much. Just because you "can" do something doesnt mean you "should".
You could just have UserInterface - then your model does
class User extends Eloquent implements UserInterface
and just skip the Repository completely.
I am doing a simple registration and login in laravel. I had previously built one taking laravel for a test drive prior to deciding to switch from CI. Anyway, the first time everything worked great. Upon reinstalling laravel, my User model does not seem to be loading. I can access User::method() for any properties or methods accessible in the Eloquent base model, but I cannot access any methods or properties declared static in my models/User.php model.
When I try and access a property I get "Access to undeclared static property"
I also tried to set a custom db table name for the users table and the system was not seeing this either. Not sure why it is loading, and not exactly sure how to check.
The User class is as follows:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
public static $rules = array(
'first_name'=>'required|alpha|min:2',
'last_name'=>'required|alpha|min:2',
'email'=>'required|email|unique:users',
'password'=>'required|alpha_num|between:6,12|confirmed',
'password_confirmation'=>'required|alpha_num|between:6,12'
);
/* All other code in this is the standard code. */
}
The route is as follows
Route::get('create', function(){
//include(app_path().'/models/User.php');
print_r(User::$rules);
});
If I leave the comments in I get "Access to undeclared static property: User::$rules"
If I take the comments out I get a the anticipated print.
probably need to run php artisan dump-autoload from the command line