AL-zami
AL-zami

Reputation: 9076

error while saving data in relational tables in laravel

This is the first time i am working with relational queries in laravel.I Have two tables here .Users and Phones.An user can have multiple phone.I have a form to register a user with a phone number. I want to save the user data in users table and the phone number in phones table.But whenever i attempt to save the data in tables i get the following error:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'phone_no' cannot be null (SQL: insert into phones (phone_no, user_id, updated_at, created_at) values (, 8, 2016-03-03 00:49:01, 2016-03-03 00:49:01))

The controller method which deals with data insertion in the tables is the following :

public function store(Request $request)
{
    //
    $data = $request->all();

    $rules = array(
       'name' => 'unique:users,name|required|alpha_num',
       'password'=>'required|alpha_num',
       'phone'=>'required'
    );

    // Create a new validator instance.
    $validator = Validator::make($data, $rules);
    if($validator->fails()){

        $errors=$validator->messages();
        return Redirect::route('user.create')->withErrors($validator);

    }else{

        $user=new User();
        $user->name=$request->name;
        $user->password=bcrypt($request->password);
        $user->save();

        $phone = new Phone();
        $phone->phone_no = $request->phone1;
        $phone->user()->associate($user);
        $phone->save();

        return Redirect::route('user.index');

    }

}

the registration form is the following :

 {!!Form::open(array('url'=>'user','method'=>'POST', 'files'=>true)) !!}

   {!!Form::label('name','Your name')!!}
   {!!Form::text('name')!!}
   </br>
   {!!Form::label('password','input password')!!}
   {!!Form::password('password')!!}
   </br>

    {!!Form::label('phone','enter phone')!!}
    {!!Form::text('phone','',array('placeholder'=>'enter phone'))!!}
    </br>

Upvotes: 0

Views: 61

Answers (1)

Carl Groner
Carl Groner

Reputation: 4359

The error is telling you that the value for phone_no cannot be blank.

I suspect that you meant $request->phone instead of phone1 in the following code:

    $phone->phone_no = $request->phone1;

Upvotes: 3

Related Questions