Basically I have a groups table with id and name,
I have another table with users_groups with id, group_id and user_id
I'm try to save when a user is created to the users_groups table, but when I use this code it saves what it can in the groups table. Is there something I'm doing wrong?
Account controller (saving user to db and set group to id 1)
$user = User::create(array(
'firstName' => $firstName,
'lastName' => $lastName,
'dateOfBirth' => $dateOfBirth,
'gender' => $gender,
'email' => $email,
'username' => $username,
'password' => Hash::make($password),
'code' => $code,
'active' => 0
));
Group::create([
'user_id' => $user->id,
'group_id' => '1' //1 is not assigned
]);
Group Model
class Group extends Eloquent
{
protected $fillable = array('name');
// DEFINE RELATIONSHIPS --------------------------------------------------
// define a many to many relationship
// also call the linking table
public function users() {
return $this->belongsToMany('User', 'users_groups', 'group_id', 'user_id');
}
}
User Model
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $fillable =array('email', 'username', 'password', 'password_temp', 'code', 'active', 'firstName','lastName','gender','dateOfBirth');
use UserTrait, RemindableTrait;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = array('password', 'remember_token');
// Each User BELONGS to many Groups
// Define our pivot table also
public function groups() {
return $this->belongsToMany('Group', 'users_groups', 'user_id', 'group_id');
}
}
All information about saving relations can be found here
You need attach()
$user = User::create(array(
'firstName' => $firstName,
// ...
));
$user->groups()->attach(1); // 1 being the group_id
Related
I generated a different table to store users for my website. Name of the table is tblusers. I am registering new users with a controller method register(), in which i added this code
public function register(){
return User::create([
'User_Email' => 'test#example.com',
'User_UserName' => 'test#example.com',
'User_Password' => bcrypt('123'),
'User_Address' => 'ABCD....',
'User_IsActive' => 1,
'User_FullName' => 'Burhan Ahmed',
'User_AppID' => 1,
'User_IsVerified' => 1
]);
}
It adds above dummy data successfully in Database. Then i tried to login with above given credentials using below code:
dd(Auth::attempt(['User_UserName' => 'test#example.com', 'User_Password' => '123']));
But above statement always returns false, Why? Am i missing something. I tried to pass actual bcrypt code instead '123' in above array it returns the same result always. Below is my Model Class
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
//class User extends Authenticatable
class User extends Authenticatable
{
use Notifiable;
protected $table = 'tblusers';
protected $primaryKey = 'User_ID';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'User_UserName', 'User_Email', 'User_Password', 'User_Address', 'User_FullName', 'User_IsActive', 'User_IsVerified'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'User_Password'
];
}
I am using Laravel 5.4, i followed all the authentication steps but not matter what i pass it always return false.
if You want to Change the default table of login folow the steps
For Example You are Changing it to login_table
Step1:
change the table property in User.php (User Model)
/**
* The table associated with the model.
*
* #var string
*/
protected $table = 'login_table';
Step1:
IF YOU ARE BEGGINER
Now You need to change the table name users to login_table
IF PROJECT IS TEAM COLLBRATION MAKE THE MIGRATION WITH login_table
php artisan make:migration create_login_table_table
and add the columns available in the users table
Step3:
Now open the file app\Http\Controllers\Auth\RegisterController.php
You will find method validator as
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:6|confirmed',
]);
}
Now You need to change unique:users to unique:login_table
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:login_table',
'password' => 'required|string|min:6|confirmed',
]);
}
Hope it helps and it works fine for me # Md.Sukel Ali
Comment if it not works
in my web application i have this models:
InstagramAccount.php
UserPageFeed.php
each InstagramAccount has one record into UserPageFeed and each UserPageFeed belongs to one record into InstagramAccount, then that's one to one relationship,
PROBLEM:
my below code couldn't update existing row on table and create again
$userSelectedPage = InstagramAccount::whereUsername('my_page')->first();
$userPageFeeds = new UserPageFeed();
$userSelectedPage->account()->updateOrCreate([
'instagram_account_id' => $userPageFeeds->id, //exsiting row
'page_name' => 'test',
'feeds' => 'test',
'cache_time' => Carbon::now()->addHour(6),
]);
or this code:
$userSelectedPage = InstagramAccount::whereUsername('content.world')->first();
$salam = $userSelectedPage->account()->updateOrCreate([
'instagram_account_id' => $userSelectedPage->id,
'page_name' => 'aaaaaaa',
'feeds' => 'ddd',
'cache_time' => Carbon::now()->addHour(6),
]);
user_page_feeds table structure:
id ->Primary
instagram_account_id ->Index
feeds
page_name
cache_time
created_at
updated_at
with this index:
"Keyname":user_page_feeds_instagram_account_id_foreign "Column":instagram_account_id
instagram_accounts table structure:
id ->Primary
user_id ->Index
uid
fid
proxy
avatar
username
password
checkpoint
account_data
people_data
status
created_at
updated_at
InstagramAccount model:
class InstagramAccount extends Model
{
protected $guarded = ['id'];
protected $casts = [
'account_data' => 'array',
'people_data' => 'array'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function account()
{
return $this->hasOne(UserPageFeed::class);
}
}
UserPageFeed model:
class UserPageFeed extends Model
{
public $incrementing = false;
protected $guarded = ['id'];
protected $casts = [
'feeds' => 'array'
];
public function account()
{
return $this->belongsTo(InstagramAccount::class,'instagram_account_id');
}
}
You have to use updateOrCreate() with two separate parameters:
$userSelectedPage->account()->updateOrCreate(
['instagram_account_id' => $userPageFeeds->id],
[
'page_name' => 'test',
'feeds' => 'test',
'cache_time' => Carbon::now()->addHour(6),
]
);
The first parameter contains the attributes that Laravel uses to find the existing
account.
The second parameter contains the attributes that Laravel uses to create or update the account.
I have a problem with inserting rows in Laravel.
Theory: I use simple Laravel authentication and have two tables.
users: id, name, password.
user_details: id, userID, email
After the registration it would be useful to insert rows into both tables, and the userID = id (in users table).
RegisterController.php
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
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|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'e_r' => $data['e_r'],
]);
$details = UserDetails::create([
'firstname' => 'joco',
'lastname' => 'nagy',
'email' =>$data['email'],
'position' => 'cleaner',
'salary' => '250000',
'amount_holiday' => '40'
]);
return $user;
}
}
(I have just tried to insert fake datas. There are default values in migration files.)
Models:
User.php
<?php
namespace App;
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', 'e_r',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function user_detail(){
return $this->hasOne("App\UserDetails");
}
}
Error:
FatalThrowableError in RegisterController.php line 74: Class
'App\Http\Controllers\Auth\UserDetails' not found
I do not understand why should be my model in Auth directory.
Have you include your model UserDetails?
Include it on top:
use App\User;
use App\UserDetails;
or
Change UserDetails to App\UserDetails.
$details = App\UserDetails::create([
'firstname' => 'joco',
'lastname' => 'nagy',
'email' =>$data['email'],
'position' => 'cleaner',
'salary' => '250000',
'amount_holiday' => '40'
]);
You should use use statement eg. use Your\Name\Space\UserDetails;
Without this declaration PHP is looking for UserDetails class in your current namespace, in your case App\Http\Controllers\Auth. That's why you get
'App\Http\Controllers\Auth\UserDetails' not found
Hello everyone who's trying to help,
im trying to create the factory file to seeding my database and i have a question how can i insert a foreign key from a table already seeded ?
and the factory code is to have all in same file? any good pratice to this ?
Files
Model User
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'user'; //name of the table in database
protected $primaryKey = 'Id'; //Primary Key of the table
/**
* Relations between tables
*/
public function GetLoginInfo()
{
return $this->hasMany('App\Models\LoginInfo', 'UserId');
}
public function getStatus()
{
return $this->belongsTo('App\Models\AccountStatus');
}
}
Model Account status
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AccountStatus extends Model
{
protected $table = 'account_status'; //name of the table in database
protected $primaryKey = 'Id'; //primary Key of the table
public $timestamps = false; //true if this table have timestaps
/**
* Relations between tables
*/
public function GetUsers()
{
return $this->hasMany('App\Models\Users', 'StatusId');
}
}
factory file:
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
//Factory for Account Status table
$factory->define(App\Models\AccountStatus::class, function (Faker\Generator $faker) {
return [
'Description' => $faker->word,
];
});
//Factory for user table
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => Factory(App\Models\AccountStatus::class)->create()->id,
];
});
This is what im trying to do as you can see : Factory(App\Models\AccountStatus::class)->create()->id but don't work
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => factory(App\Models\AccountStatus::class)->create()->id,
];
});
i see an uppercase F in factory..
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
$accountStatus = factory(App\Models\AccountStatus::class)->create()
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => $accountStatus->id,
];
});
Edit (Improvement)
If you have one model that depend on another model. you can do it this way, using a callback function to create with the related.
Like this
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => function () {
return factory(App\Models\AccountStatus::class)->create()->id;
}
];
});
One thing you need to keep in mind is that this will go to an endless loop if the related(Status Model) has a model that depends on the parent(User Model).
Table 1(users):
id username password role created_at updated_at
1 jhon yz 1 sometime sometime
Table 2(role):
id role created_at updated_at
1 employee sometime sometime
what I want
id username password role created_at updated_at
1 jhon yz employee sometime sometime
Users Model:
class User extends Eloquent implements UserInterface, RemindableInterface {
public function role()
{
return $this->hasOne('role', 'id', 'role');
}
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
}
Roles Model:
class Role extends Eloquent {
protected $table = 'roles';
}
how do i get the role name in the view ? Is my relationship right
one role can be used by many users, like:
user1 can be admin
user2 can be admin too
user3 is a manager
user4 is a manager too
if thats the case then,..
Users Model:
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'users';
protected $hidden = array('password', 'remember_token');
public function role()
{
return $this->belongsTo('Role');
}
}
Roles Model:
class Role extends Eloquent {
protected $table = 'roles';
public function users()
{
return $this->hasMany('User');
}
}
then use:
User::with('role')->whereRole(1)->get(); // assuming that 1 = employee; this is eager loading
this will yield something like:
[
new User([
'id' => 1,
'username' => 'blahblah',
'password' => 'pass',
'role' => 1,
'created_at' => '0000-00-00',
'updated_at' => '0000-00-00',
'role' => new Role([
'id' => 1,
'role' => 'employee',
'created_at' => '0000-00-00',
'updated_at' => '0000-00-00'
])
])
]