I am just learning to use Laravel and so far have set up a basic instance and then ran the php artisan make:auth command which setup the basic user registration etc.
What I want to do now is extend this auth to save an additional field from the registration in to a separate related table from Users called Titles.
I have managed to follow the user guide so far. This is where I am at just now:
In register.blade.php I have added in the additional field:
<div class="form-group">
<label class="col-md-4 control-label">Title</label>
<div class="col-md-6">
<input type="text" class="form-control" name="title" value="">
@if ($errors->has('title'))
<span class="help-block">
<strong></strong>
</span>
@endif
</div>
</div>
Then in the AuthController.php I have added the title field to the validation:
protected function validator(array $data)
{
return Validator::make($data, [
'title' => 'required|max:100',
'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)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
I then created a Title model and related it to the user:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Title extends Model
{
public function user()
{
return $this->belongsTo('User');
}
}
Then I updated the user model:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function title()
{
return $this->hasOne('App\Title');
}
}
The migration for the Titles table looks like this so I think its correct:
public function up()
{
Schema::create('titles', function (Blueprint $table) {
$table->increments('id');
$table->string('title', 100);
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
This is where I am sort of stuck now. How do I actually save the title field to the titles table and have it related to the user?
I see from the documentation that you use a format similar to:
$title = new Title(array('title' => 'test title'));
$title = $user->titles()->save($title);
But I am not sure how to apply it in this situation since the create function in the AuthController just returns a array right away.
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1TIqgdi
via IFTTT
Aucun commentaire:
Enregistrer un commentaire