Skip to content
Advertisement

How shall i concatenate two or more values/variables to a new variable in laravel

I am pretty much new to laravel(5.2), here i want to concatenate two values say first name and last name during user registration and save it to database, honestly as am new to this whole concept i have very little idea of doing it…it would be great if i could get some help….

User.php

class User extends Authenticatable
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'first_name', 'last_name', 'email'
    ];

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password', 'remember_token',
    ];
}

AuthController.php

class AuthController extends Controller
{
  protected function validator(array $data)
    {
        return Validator::make($data, [
            'first_name' => 'required|max:255',
            'last_name' => 'required|max:255',
            'email' => 'required|email|max:255|unique:users',
            'password' => 'required|min:6|confirmed',
             ]);
    }

protected function create(array $data)
    {
        return User::create([
            'first_name' => $data['first_name'],
            'last_name' => $data['last_name'],
            'email' => $data['email'],
            'password' => bcrypt($data['password']),
             ]);
    }
}

Advertisement

Answer

if you want to save the new value to data base you must register it in you fillable, also to alter the database to accept the new column

protected $fillable = [
    'user_name', 'first_name', 'last_name', 'email'
];


protected function create(array $data)
{
    return User::create([
        'user_name' => $data['first_name'].' '.$data['last_name'],
        'first_name' => $data['first_name'],
        'last_name' => $data['last_name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
         ]);
}

you may want to remove first_name and last_name.. and store only full name, or you can ignore storing the full name, and in User.php model you can override the toArray() method and make it returns the full name which you can concatenate just like above

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement