How can I insert the super_admin seeder in laravel? - laravel

SuperAdminSeeder.php
public function run()
{
#Super Admin Seeder
$role = Role::where('name', 'super_admin')->first();
$user = User::create([
'name' => 'Jhon Cena',
'email' => 'jhon#gmail.com',
'password' => Hash::make('jhoncena'),
'remember_token' => Str::random(60),
]);
$user->role()->attach($role->id);
}
This is my SuperAdmin seeder which task is to make a user with role super_admin
DatabaseSeeder.php
public function run()
{
$this->call(RegionSeeder::class);
$this->call(CountrySeeder::class);
$this->call(LocationSeeder::class);
$this->call(ProductSeeder::class);
$this->call(SliderSeeder::class);
$this->call(BannerSeeder::class);
$this->call(SuperAdminSeeder::class); //this is the Super Admin seeder
$this->call(RoleSeeder::class);
$this->call(UserSeeder::class);
$this->call(ShopSeeder::class);
}
This is the database seeder
The error I am getting [php artisan migrate:fresh --seed]
Illuminate\Foundation\Bootstrap\HandleExceptions::handleError("Trying to get property 'id' of non-object", "E:\github\LARAVEL\Deal-Ocean\database\seeds\SuperAdminSeeder.php", [Object(App\User)])
I am new in laravel

It's caused no super_admin role when you run superadmin seeder. You should add SuperAdminSeeder after RoleSeeder.
public function run()
{
$this->call(RegionSeeder::class);
$this->call(CountrySeeder::class);
$this->call(LocationSeeder::class);
$this->call(ProductSeeder::class);
$this->call(SliderSeeder::class);
$this->call(BannerSeeder::class);
$this->call(RoleSeeder::class); //this seeder must have superadmin role
$this->call(SuperAdminSeeder::class); //this is the Super Admin seeder
$this->call(UserSeeder::class);
$this->call(ShopSeeder::class);
}

public function run()
{
$this->call(RegionSeeder::class);
$this->call(CountrySeeder::class);
$this->call(LocationSeeder::class);
$this->call(ProductSeeder::class);
$this->call(SliderSeeder::class);
$this->call(BannerSeeder::class);
$this->call(RoleSeeder::class);
$this->call(SuperAdminSeeder::class); //this is the Super Admin seeder
$this->call(UserSeeder::class);
$this->call(ShopSeeder::class);
}
Just put the RoleSeeder above the SuperAdminSeeder.
Because roles table might have a column value named super_admin. SO you must call the RoleSeeder Because there is a foreign key constriant.. And then you can insert the super admin using SuperAdminSeeder

Related

Why it shows always invalid credentials

I have a seeder so the users that can use the app can just run the seeder at the begining and have that administrator configured. The app only has one administrator. However, Im not undersanding why the login is not working properly it shows always that the credentials are invalid. Do you know what can be the issue?
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
AdministratorSeeder::class,
]);
}
}
class AdmininistratorSeeder extends Seeder
{ public function run()
{
User::create(['name' => 'administrator', 'email' => config('services.administrator.key'), 'password' => bcrypt('password')]);
}
}

Empty table after seeding in laravel8?

I just started working with Laravel and i'm trying to seed my DB. I have a many to many relationship between the users and shops table.
When i'm running php artisan DB:seed the seeder for shops isn't running. And if i run php artisan db:seed --class=ShopsTableSeeder i'm getting an Error SQLSTATE[HY000]: General error: 1364 Field 'user_id' doesn't have a default value
The factory file :
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
use App\Models\Shop;
$factory->define(Shop::class, function () {
$faker = Faker\Factory::create('fr_FR');
return [
'title' => $faker->text($maxNbChars = 20),
'description' => $faker->text(250),
...
'phone' => $faker->phoneNumber,
'active_until' => $faker->dateTimeBetween('+0 days', '+2 years'),
];
});
And the seeding file :
<?php
namespace Database\Seeders;
use App\Models\Shop;
use App\Models\User;
use Illuminate\Database\Seeder;
class ShopsTableSeeder extends Seeder
{
public function run()
{
factory(Shop::class, 10)->create();
foreach (Shop::all() as $shop){
$users = User::inRandomOrder()->take(rand(1,3))->pluck('id');
$shop->users()->attach($users);
}
}
}
how can i set the column user_id in the factory to connect a shop to user ?

Laravel Spatie Roles and permissions - error on Update

I need help for my Laravel application.
I use spatie roles and permissions.
When i create the user, assign roles is no problem. When i will update the same user, there is the following error:
[2019-12-06 08:44:36] local.ERROR: The given role or permission should use guard instead of `web`. {"userId":1,"exception":"[object] (Spatie\\Permission\\Exceptions\\GuardDoesNotMatch(code: 0): The given role or permission should use guard instead of web. at /home/vagrant/code/test/vendor/spatie/laravel-permission/src/Exceptions/GuardDoesNotMatch.php:12)
public function store(StoreUserRequest $request)
{
$user = $this->repo->create( $request->all());
$user->assignRole($request->roles);
return $user;
}
public function update(UpdateUserRequest $request, User $user)
{
$user = $this->repo->update($user, $request->all());
$user->assignRole($request->roles);
return $user;
}
I added protected $guard_name = 'web'; to the User Model but still the same problem.
What is wrong? Is there a problme with the userId?
On update method use syncRoles instead of assignRole
When you assign role for a user the model path App\User insert into table model_has_roles if you change the model folders spatie give you an error. I think this code may help you more.
don't missing add HasRoles
class User extends Authenticatable
{
use Notifiable, HasRoles;
...
}
make sure you import use App\User;
UserController
public function update(Request $request, $id)
{
$this->validate($request, [
'name' => 'required',
'email' => 'required|email|unique:users,email,'.$id,
'password' => 'same:confirm-password',
'roles' => 'required'
]);
$input = $request->all();
if(!empty($input['password'])){
$input['password'] = Hash::make($input['password']);
}else{
$input = array_except($input,array('password'));
}
$user = User::find($id);
$user->update($input);
DB::table('model_has_roles')->where('model_id',$id)->delete();
$user->assignRole($request->input('roles'));
return redirect()->route('users.index')
->with('success','User updated successfully');
}

How to remove Laravel Auth Hashing (to replace it by mysql hashing)?

I added registration, and I don't want to using laravels hash but mysql Hash (because I want existing users to still be able to connect).
So i do it step by step and for now I just try to register and then login without any hashing. The credentials are correct in my table but I get
"message":"The given data was invalid.","errors":{"email":["These credentials do not match our records."]}
I tried setting it in LoginController.php
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
class LoginController extends Controller
{
public function username()
{
return 'email';
}
public function password()
{
return 'email';
}
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
public function Login(Request $request)
{
if(Auth::attempt(['email' => $request->email, 'pwd' => $request->password, 'password' => $request->password])){
$user = Auth::user();
$username = $user->nom;
return response()->json([
'status' => 'success',
'user' => $username,
]);
} else {
return response()->json([
'status' => 'error',
'user' => 'Unauthorized Access'
]);
}
}
}
I guess I should overwrite another function, but can't find out which one.
Could you please give me some help?
Altough what you're trying to achieve is considered unsecure, to remove Laravel's hashing for password, you need to add this to your User model :
public function setPasswordAttribute($password){
$this->attributes['password'] = $password;
}
and not in your controller, and be sure to remove the brcypt() methods in your RegisterController
To add your MySQL own hashing methods, update your controller to insert a RAW query while creating a user upon registration

Laravel - Seeding Many-to-Many Relationship

I have a users table and a roles table that has a many-to-many relationship. These two tables are connected to a junction table called role_user.
This is a model of the tables and its connections.
Below are the Models in my Laravel project:
User
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function roles()
{
return $this->belongsToMany('App\Role');
}
}
Role
namespace App;
use Illuminate\Database\Eloquent\Model;
class Role extends Model
{
public function users()
{
return $this->belongsToMany('App\User');
}
}
Below is the Factory file in the Laravel project:
$factory->define(App\User::class, function (Faker\Generator $faker) {
return [
'name' => $faker->name,
'email' => $faker->unique()->safeEmail,
'password' => $password ?: $password = bcrypt('secret'),
];
});
$factory->define(App\Role::class, function (Faker\Generator $faker) {
return [
'role' => $faker->realText($maxNbChars = 2),
'description' => $faker->realText($maxNbChars = 20),
];
});
Below is the Seed file in the Laravel project:
public function run()
{
factory(App\User::class, 50)->create()->each(function ($u) {
$u->roles()->save(factory(App\Role::class)->make());
});
factory(App\Role::class, 20)->create()->each(function ($u) {
$u->users()->save(factory(App\User::class)->make());
});
}
This should populate the users table and the roles table but how do I go about populating the role_user table? (I don't have a Model file for the junction table.)
I'm very new at this so any help would be appreciated. Thanks.
You can use attach() or sync() method on a many-to-many relationship.
There are multiple ways you can approach this. Here one of them:
// Populate roles
factory(App\Role::class, 20)->create();
// Populate users
factory(App\User::class, 50)->create();
// Get all the roles attaching up to 3 random roles to each user
$roles = App\Role::all();
// Populate the pivot table
App\User::all()->each(function ($user) use ($roles) {
$user->roles()->attach(
$roles->random(rand(1, 3))->pluck('id')->toArray()
);
});
Another way is to use saveMany() function
public function run()
{
factory(App\User::class,3)->create();
$roles = factory(App\Role::class,3)->create();
App\User::All()->each(function ($user) use ($roles){
$user->roles()->saveMany($roles);
});
}
A much cleaner method can be: after you define the factory for App\User and App\Roles you can call the afterCreating method like this:
$factory->define(App\User::class, function ...);
$factory->define(App\Role::class, function ...);
$factory->afterCreating(App\User::class, function ($row, $faker) {
$row->roles()->attach(rand(1,20));
});
Then in Seeds you first create the roles, then the users
public function run()
{
factory(App\Role::class, 20)->create();
factory(App\User::class, 50)->create();
}
Now you have 50 users each of them with one role attached.
Just for a seeder you can use something like this:
for ($i = 0; $i < 50; $i++) {
$user = factory(App\User::class)->create();
$role = factory(App\Role::class)->create();
DB::table('role_user')->insert([
'user_id' => $user->id,
'role_id' => $role->id
]);
}
But normally you need to define relation like has many through https://laravel.com/docs/5.4/eloquent-relationships#has-many-through
Then you will be able to use:
$user->roles()->save($role);
Better to use this structure:
App\Role::factory()->count(20)->create();
// Populate users
App\User::factory()->count(50)->create();
// Getting all roles and saving them to variable is not too good idea.
// Instead, get count of rows.
$rolesCount = App\Role::count();
// Populate the pivot table
App\User::all()->each(function ($user) use ($rolesCount) {
$user->roles()->attach(
App\Role::all()->random(rand(1, $rolesCount))->pluck('id')->toArray()
);
});

Resources