Issue
sorry for the messy title.
So, I have a basic User model and I'm trying to register a new user, the thing is one of my field in the users table is a 'screen_name' that I would like to be filed automatically with the the first 'word' from the name attribute.
How can I do that?
I've tried
public function setScreenNameAttribute($value){
return 'MyFirstName';
}
But as I understand, the set***Attribute will only be fired if I have this field in my form request, but I don't want the user to fill this field I want the model to do that by it's own.
Solution
Model
public function setScreenNameAttribute($value)
{
$this->attributes['screen_name'] = strtolower(strtok($value, ' ')); // First name from the full name as screen name
}
Controller
$user->screen_name = 'John Smith'; // your request value goes here - $request->full_name;
You don't need to have a field for that in the form.
Hope this helps.
Let me know if doesn't work.
Updated / Anohter solution.
protected $attributes = array(
'screen_name' => 'Your name' // Any values
);
public function __construct(array $attributes = array())
{
$this->setRawAttributes(array(
'screen_name' => strtolower(strtok($attributes->first_name, ' '));
), true);
parent::__construct($attributes);
}
Answered By - Kaushik Thakkar Answer Checked By - Willingham (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.