In my code i have a 'User' model and an 'ONG' model, a user has one ong and the ong has an 'user_id', so when the User creates an Ong i want to get the user(that is creating) id and insert into the Ong user_id column
The user can only create an Ong if he is logged in
Ong model
public function user(){
return $this->belongsTo('App\Models\User');
}
Ong migration
Schema::create('ongs', function (Blueprint $table) {
$table->bigIncrements('ong_id');
$table->timestamps();
$table->string('name',100);
$table->smallInteger('user_id');
});
User migration
if(!Schema::hasTable('users')){
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name', 100);
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password', 80);
$table->rememberToken();
$table->timestamps();
});}
User Model
public function ong(){
return $this->hasOne('App\Models\Ong');
}
OngsController has a store method
public function store(Request $request)
{
$request->all();
$request['user_id']= $id;
}
but how can i get the 'user_id' in there?
i'm using Auth from laravel/ui auth
only have this route now but this goes to the form
Route::group(['middleware'=>'web'],function(){
Route::view('/criarOng', 'ongs.create');
});
Create form
{!! Form::open([
'method'=>'post', 'route' => 'ongs.store'
]) !!}
{!! Form::label('name', 'Nome da Ong') !!}
{!! Form::text('name') !!}
{!! Form::select('estado',['SP'=>'SP', 'RJ'=>'RJ'], null) !!}
{!! Form::label('cidade', 'Cidade da ong') !!}
{!! Form::text('cidade') !!}
{!! Form::submit('Criar') !!}
{!! Form::close() !!}
CodePudding user response:
You need to setup foreign key on ong table.
Schema::create('ongs', function (Blueprint $table) {
$table->bigIncrements('ong_id');
$table->timestamps();
$table->string('name',100);
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
Then while creating ong you can use
public function store(Request $request)
{
$request->all();
$user_id = Auth::user()->id;
}
Then in your ONG Model
public function ong(){
return $this->hasMany('App\Models\Ong');
}
