Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Shiva's avatar

store function not finding the correct table

In my page I have a textbox where you can enter your name and a dropdown where you can select a group that your in. I also have 3 tables, the first table is the user table, then there is the groups table and the last one is called group_user table. The problem I'm having is that when I save it doesn't find the group_user table. Here is the error message

{"error":{"type":"Illuminate\\Database\\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'group_id' in 'field list' (SQL: insert into `users` (`id`, `name`, `surname`, `email`, `group_id`, `password`, `updated_at`, `created_at`) values (, qq, qq, qq@qq.com, 1, y$foOlLh4ND8N190uOlMIJHuijtC6RCaj6yfWhQ1MS1sMkx.o2E\/pEe, 2014-11-26 08:25:13, 2014-11-26 08:25:13))","file":"\/Applications\/MAMP\/htdocs\/test-laravel\/vendor\/laravel\/framework\/src\/Illuminate\/Database\/Connection.php","line":555}}

Here is my controller

public function index()
    {
        setModuleSession("usersPermissions","");
        $usersList = \User::all();
        $group_options = \Groups::lists('name', 'id');
        return \View::make('admin.usersPermissions.index', compact('usersList'))->with('group_options', $group_options);
    }

public function store()
    {
        if(!empty($_POST) && \Request::ajax())
        {
            $user = new \User();
            $input = \Input::all();


            $validation = \Validator::make($input, \User::$rules); //nicole

            if($validation->fails()){
                $usersList = \User::all();
                $html =  \View::make('admin.users.partials.get-users-list', compact('usersList'))->render();
                return \Response::json(array('html' => $html, 'id' => $user->id, 'message' => ' User unsuccessfully saved.'));
            }

            if($validation->passes()){

                // Fields to ignore
                $ignore =   array('_token');

                foreach ($_POST as $key => $value) 
                {
                    if(!in_array($key, $ignore ))
                        $user->{$key} = $value;
                }

                $pw = $user->generatePassword();
                $user->password = \Hash::make($pw);

                // if(isset($_POST['group_id']))
                //  $user->groups()->sync(\Input::get("group_id", []));

                $data = array(
                    'name' => \Input::get('name'),
                    'email' => \Input::get('email'),
                    'password' => $pw,
                    );




                \Mail::send('emails.email', $data, function($message){
                    $message->to(\Input::get('email'), \Input::get('name'))->subject('Login Details');
                });




                if(isset($_POST['group_id']))
                    $user->groups()->sync(\Input::get("group_id", []));

                $user->save();
                //$user->create($input);




                $usersList = \User::all();
                $html =  \View::make('admin.users.partials.get-users-list', compact('usersList'))->render();
                return \Response::json(array('html' => $html, 'id' => $user->id, 'message' => ' User successfully saved.'));
            }
        }
    }

Here is my view

@extends ('admin.layouts.internal')
@section('title', 'Content > Manage users')
@section('template')
    {{ HTML::script("scripts/admin/modules/users.js") }}
    <h2 class="module-heading">Manage users</h2>   
    <div class="panel panel-default">
        <div class="panel-body">
            <button class="btn btn-afis-blue" onclick="showDiv('create');"><i class="fa fa-list"></i> create a new user</button>
            <div id="create" class="border" style="display:none;">
                <div class="white parent-target">
                    <button onclick="showDiv('create');" type="button" class="btn btn-danger btn-xs">cancel</button>
                    <br><br>
                    {{ Form::open(array('id'=>"user-frm", 'class'=>'modify-user-frm', 'url' => 'admin/users/manage')) }}
                        <p>
                            {{ Form::label(null, 'name') }}
                            {{ Form::text('name', null , array(
                                    'class' => 'input_text form-control',
                                    'placeholder' => 'name',
                                    'required' => true,
                                    'id' => 'name'
                                )) 
                            }}
                        </p>
                        <p>
                            {{ Form::label(null, 'surname') }}
                            {{ Form::text('surname', null , array(
                                    'class' => 'input_text form-control',
                                    'placeholder' => 'surname',
                                    'required' => true,
                                    'id' => 'surname'
                                )) 
                            }}
                        </p>
                        <p>
                            {{ Form::label(null, 'email') }}
                            {{ Form::text('email', null , array(
                                    'class' => 'input_text form-control',
                                    'placeholder' => 'email',
                                    'required' => true,
                                    'id' => 'email'
                                )) 
                            }}
                        </p>


                        {{ Form::label('group_id', 'Groups') }}
                        {{ Form::select('group_id', $group_options) }}

                        {{ Form::submit('SAVE', array(
                                'id' => 'submit',
                                'class' => 'btn btn-success submit-user'
                            )) 
                        }}

                    {{ Form::close() }}
                </div>
            </div>
            <br />
            <div id="page_list">       
                @include('admin.users.partials.get-users-list')
            </div>
        </div>
    </div>
    @if($errors->any())             
        {{ implode('', $errors->all('<p class="error">:message</p>')) }}
    @endif
@stop

Here is my model

<?php

use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;

class User extends Eloquent implements UserInterface, RemindableInterface {

    use UserTrait, RemindableTrait;


    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    public static $rules = array(
        'name' => 'required',
        'email' => 'required|email|unique:users'
        );

    public function groups()
    {
        return $this->belongsToMany("Groups")->withTimestamps();
    }

}

I always thought that

$user->groups()->sync(\Input::get("group_id", []));

would some how link the two tables and add the ids to the group_user table

0 likes
17 replies
bestmomo's avatar
$user->groups()->attach(\Input::get("group_id", []));

Are you sure it's "Groups" in your relation and not "Group" ?

Shiva's avatar

Yep it's "Groups". It was one of the things I checked first

bestmomo's avatar

When you make $user->save there is the group_id in Inputs so this field is in request and it fails. You should except it.

bestmomo's avatar

You should save your user before to update the pivot table.

Shiva's avatar

I've tried that and I still got the same problem. What I did was instead of saving the user to the group I would add the user first and the edit the user and save the group that way, but that didn't work either

bestmomo's avatar

When you do that :

foreach ($_POST as $key => $value) 
{
     if(!in_array($key, $ignore ))
     $user->{$key} = $value;
}

You add all fields, including group_id that is not in users table.

On the other hand you should use Input class to get inputs. But if you want to keep your code make that :

$ignore =   array('_token', 'group_id');
arabsight's avatar
$ignore = ['_token', 'group_id'];

and after this line

$user->password = \Hash::make($pw);

save your $user.

Shiva's avatar

I've added

$ignore = array('_token', 'group_id');

I even saved my $user after

$user->password = \Hash::make($pw);

but I still got the same error

bestmomo's avatar

You should populate your user with an explicit code instead of your loop like that :

$user->name = \Input::get('name');
$user->surname = \Input::get('surname');
$user->email = \Input::get('email');

So you can better manage your data.

Shiva's avatar

Even if I did that wouldn't I still be left with the same problem that I'm having now?

bestmomo's avatar

If you dont populate $user with group_id field you wont have your issue.

Shiva's avatar

But I need the group_id so that I can link a user to a group

bestmomo's avatar

You need the group_id in pivot table, not in users table.

Shiva's avatar

Yep that is true, but then how would I link it?

bestmomo's avatar

You link it after you store your user with :

$user->groups()->attach(\Input::get("group_id", []));

Please or to participate in this conversation.