Error trying to insert form in laravel with authenticated user (foreign key to another table)

0

I am trying to insert the data of a form of a Condominium class with the user already logged in and authenticated, the user_id is foreign key to the Condominium table, in my understanding the store method should already bring the user_id in the array to insert the data but this is not happening, and because of this it generates an SQL error saying that the field user_id can not be null (since it is a foreign key as it said). It takes the create and store methods of CondomínioController:

public function create()
    {   
        $condominio = auth()->user()->condominio;
        //$condominio = Condominios::create()->get();
        $title='Cadastrar Condominio';
        return view('admin.condominio.create',compact('title')); 

    }


public function store(Request $request)
{   
    $condominio = auth()->user()->condominio;
    //dd($request->all());

    Condominios::create($request->all());


   return redirect()->route('admin.condominio.index')->with('message', 'condominio criado com sucesso!');

    
asked by anonymous 19.04.2018 / 17:22

1 answer

0

If the user_id field is not explicitly defined in the view it will not be populated, ie it will not be injected automagically.

You can do this:

<input type="hidden" name="user_id" value="{{ Auth()->user()->id }}">

** I do not recommend doing so, since the field can be edited.

It can also be done like this:

public function store(Request $request)
{   
    $condominio = auth()->user()->condominio;

    $request['user_id'] = Auth()->user()->id;

    Condominios::create($request->all());


   return redirect()->route('admin.condominio.index')->with('message', 'condominio criado com sucesso!');
}

In your model you need to declare the fillable property and tell you which fields can be filled via Mass Assignment .

Example:

protected $fillable = ['user_id', 'nome', 'teste'];
    
19.04.2018 / 17:42