Fill extra column for User - laravel

I have a user table with a referral column and this code in controller/auth:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'referral' => md5($data['email']),
]);
}
It adds a name, email and password but not referral.
There is no error or notice. What should I do to fill also referral column?

Open your User model (probably app/User.php, and change:
protected $fillable = [
'name', 'email', 'password',
];
into
protected $fillable = [
'name', 'email', 'password', 'referral'
];
You need to add column to fillable to save it.

Related

Data not saved in database in real after model created

I am using CREATE method for mass assignment in laravel eloquent, the result also printed and showing, but when i check table in database, no data inserted.
I am using laravel 5.6, It showing successful, but in real no data saved in table.
here is my code
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
protected $table = 'users';
public $primaryKey = 'user_id';
public $timestamps = false;
protected $fillable = [
'first_name','middle_name', 'last_name', 'role_id', 'email', 'mobile', 'telephone'
];
.... and other code
Here is my insert function
$users = User::create([
'first_name' => $row[1],
'middle_name' => $row[2],
'last_name' => $row[3],
'email' => $row[4],
'role_id' => 6,//$row[5],
'telephone' => $row[6],
'mobile' => $row[7],
]);
var_dump($users);// this shows result.
$users prints data. There is no error showing. BUT when i check database, table is empty. I expect the same data in users table.

Laravel forgen key not passing tests

I am working through TDD in Laravel. I have a Location factory that looks like this:
LocationFactory
$factory->define(Location::class, function (Faker $faker) {
return [
'owner_id' => function () {
return factory(User::class)->create()->id;
},
'name' => $faker->company,
...
];
});
My test looks like this:
LocationTest
// Allow Laravel to handle the exception.
$this->withExceptionHandling();
// Create an authenticated user instance.
$user = factory(User::class)->create();
// Create the location instances via a factory.
$location = factory(Location::class)->create();
// An authenticated user can send a POST request to /locations to create a new location.
$response = $this->actingAs($user)->post('/locations', $location->toArray());
// Assert the system should persist the data to the database.
$this->assertDatabaseHas('locations', [
'id' => $location->id,
'owner_id' => $location->owner_id,
'name' => $location->name,
'description' => $location->description,
'address' => $location->address,
'address2' => $location->address2,
'city' => $location->city,
'state' => $location->state,
'zip' => $location->zip,
'created_at' => $location->created_at,
'updated_at' => $location->updated_at,
'deleted_at' => null,
]);
// Assert the response.
$response->assertSessionHasNoErrors();
$response->assertStatus(200);
The error I am getting is pretty obvious:
[
"The owner id field is required."
]
Failed asserting that true is false.
However, I know I'm getting an owner_id in my tests:
dd($location);
#original: array:12 [
"owner_id" => 665
...
Here is a snippet of my controller - how I'm saving the location.
LocationController
$attributes = $request->validate([
'owner_id' => 'required',
'name' => 'required',
...
]);
$location = Location::create($attributes);
$location->owner_id = auth()->id();
$location->save();
My Location model looks like this:
protected $fillable = [
'name', 'description', 'address', 'address2', 'city', 'state', 'zip',
];
/**
* The attributes that aren't mass assignable.
*
* #var array
*/
protected $guarded = [
'owner_id',
];
Using telescope I can see that owner_id is not in the array. I am not sure what I am doing wrong.
Thank you for any suggestions!
Edit
Checking my migration to make sure the field is there:
$table->unsignedInteger('owner_id');
While looking right at the raw database, I can see the column exists and has data.

Hashing a fillable password

I have no idea how to hash fillable password input. I'm trying to hash it then gets stored to the database. Here's what I've done so far
use App\User;
use Illuminate\Http\Request;
class RegistrationController extends Controller
{
public function store()
{
$this->validate(request(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required|confirmed'
]);
$pass = bcrypt(request()->password);
$user = User::create(request(['name', 'email', $pass]));
auth()->login($user);
return redirect()->home();
}
}
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password'
];
protected $hidden = [
'password', 'remember_token',
];
}
It gives me a QueryException:
SQLSTATE[HY000]: General error: 1364 Field 'password' doesn't have a default value (SQL: insert into users (name, email, updated_at, created_at) values (the name i inserted, email inserted, date timestamp, date timestamp)
When using: $user = User::create(request(['name', 'email', $pass]));, you are passing an array to the request method and one of the elements ($pass) is not a key of $request.
I believe it should look more like:
$user = User::create([
'name' => request('name'),
'email' => request('email'),
'password' => $pass
]);
EDIT
Also, remember that Laravel provides a Hash facade to help you with encryption:
You can also use the Hash facade to do the same as bcrypt.
Thanks to lagbox for the correction.
$hashedPassword = Illuminate\Support\Facades\Hash:make(request('password'));

updated table and related table in Laravel

In Laravel I have relation:
class Address extends Model
{
protected $fillable = [
'street', 'city', 'post_code', 'country', 'state',
];
public function companies() {
return $this->hasMany('App\Company');
}
}
class Company extends Model
{
protected $fillable = [
'name', 'nip', 'email', 'phone', 'address_id'
];
public function address() {
return $this->belongsTo('App\Address');
}
}
and in CompaniesController.php I want to do update tables. My code looks like this:
public function update(Request $request, $id)
{
Company::where('id', $id)->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'nip' => $request->nip,
]);
}
How to also update the address associated with this company?
If the ID is your primary key, you should use find instead of where, as the former will guarantee that you only retrieve one row.
You can then query the relationship of your Company model, using the following code:
$company = Company::find($id);
$company->update([
'name' => $request->name,
'email' => $request->email,
'phone' => $request->phone,
'nip' => $request->nip,
]);
$company->address()->update([
'street' => 'street value',
'city' => 'city value',
'post_code' => 'post_code value',
'country' => 'country value',
'state' => 'state value',
]);
Please refer to the laravel docs

Laravel - How to add value not listed in $fillable

In my User model I have this rule:
protected $fillable = ['name', 'email', 'password'];
And I want to add in my model one more field "role_id", that could be assigned only inside controller or model, but should be ignored in other cases.
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'role_id' => $this->role_id
]);
}
Try this:
$user = new User();
$user->fill([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password'])
]);
$user->role_id = $this->role_id;
$user->save();
return $user->id;

Resources