Home error while saving data in relational tables in laravel
Reply: 1

error while saving data in relational tables in laravel

AL-zami
1#
AL-zami Published in 2016-03-03 00:52:43Z

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>
Carl Groner
2#
Carl Groner Reply to 2016-03-03 00:58:02Z

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;
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.296705 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO