Error when trying to enter form in the authenticated user’s Language (foreign key to another table)

Asked

Viewed 68 times

0

I am trying to enter the data of a form of a class Condominium with the user already logged in and authenticated , user_id is foreign key to the table Condominium, 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 generates an SQL error saying that the user_id field cannot be null (because it is a foreign key as said). Follow the create and store method of the Condominium:

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!');

inserir a descrição da imagem aqui

1 answer

0

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

You can do it like 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 property fillable and indicate which fields can be filled in via Mass Assignment.

Example:

protected $fillable = ['user_id', 'nome', 'teste'];
  • Keeps making the same mistake

  • edited the answer

  • David in the fillable array I can not insert user_id because it is not an input field for user , earlier had managed doing this way but is ganbiarra, I have to get by going through the same Auth , I know it is possible.

  • This is not gambiarra, it’s the way the framework works. If you want to do otherwise you will have to instantiate the model and set the attributes 1 by 1 and at the end of a $model->save()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.