mirsahib
3 months ago
466
6
Laravel

Inserting row with foriegn key

Posted 3 months ago by mirsahib

I have two tables Tenant and House. here is my Tenant table migration file:


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateTenantsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tenants', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name',50);
            $table->string('nid',50);
            $table->string('nid_img')->default("https://via.placeholder.com/150");
            $table->string('phone',50);
            $table->integer('exp_rent');
            $table->integer('paid_rent')->default(0);
            $table->integer('dues')->default(0);
            $table->date('reg_date');
            $table->date('pay_date')->default("2020-01-01");
            $table->string('comment')->default("Earum eligendi reprehenderit impedit eveniet. Omnis et optio voluptatem dolorum non.");
            $table->integer('house_id')->unsigned();
            $table->string('status',10)->default('NULL');
            $table->date('exit_date')->default('2020-01-01');
            $table->timestamps();

            $table->foreign('house_id')->references('id')->on('houses');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('tenants');
    }
}

House table


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateHousesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('houses', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('hrid');
            $table->timestamps();

        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('houses');
    }
}

TenantController


<?php

namespace App\Http\Controllers;

use App\Tenant;
use App\House;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;


class TenantController extends Controller
{
   
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
        
        $validateData = Validator::make($request->all(),[
            'name'=>'required',
            'nid'=>'required',
            //'nid_img'=>'required',
            'phone'=>'required',
            'exp_rent'=>'required',
            'reg_date' =>'required',
            //'paid_rent'=>'required',
            //'dues'=>'required',
            //'pay_date'=>'required',
            //'comment'=>'required',
            'house_id'=>'required',
            //'status'=>'required',
            //'exit_date'=>'required',
        ]);
        if($validateData->fails()){
            return response()->json([
                'message'=>'Invalid input'
            ]);
        }else{
            $tenant = new Tenant;
            $house  = House::find($request->house_id);
            if($request->nid_img){
                $tenant->name = $request->name;
                $tenant->nid = $request->nid;
                $tenant->nid_img = $request->nid_img;
                $tenant->phone = $request->phone;
                $tenant->reg_date = $request->reg_date;
                $tenant->exp_rent = $request->exp_rent;
                //$tenant->house_id = $request->house_id;
                $tenant->house()->associate($house);

                $tenant->save();
                return response()->json([
                    'message'=>'Tenant Created Successfully','tenant'=>$tenant
                ]);
            }else{
                $tenant->name = $request->name;
                $tenant->nid = $request->nid;
                $tenant->phone = $request->phone;
                $tenant->reg_date = $request->reg_date;
                $tenant->exp_rent = $request->exp_rent;
                //$tenant->house_id = $request->house_id;
                $tenant->house()->associate($house);
                $tenant->save();
                return response()->json([
                    'message'=>'Tenant Created Successfully','tenant'=>$tenant
                ]);
            }
        }
    }
    
}

House Model

<?php

namespace App;

use App\Tenant;
use App\motherMeter;
use Illuminate\Database\Eloquent\Model;

class House extends Model
{
    //
    public function tenant(){
        return $this->hasOne(Tenant::class);
    }
    public function motherMeter(){
        return $this->hasOne(MotherMeter::class);
    }
}

Tenant model

<?php

namespace App;
use App\House;
use Illuminate\Database\Eloquent\Model;

class Tenant extends Model
{
    //
    protected $fillable = ['name','nid','nid_img','phone','exp_rent','paid_rent',
                            'dues','pay_date','comment','status','exit_date'];

    public function house()
    {
        return $this->belongsTo(House::class);
    }

    
}

I am getting this error while inserting a new Tenant

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'house_id' cannot be null (SQL: insert into `tenants` (`name`, `nid`, `phone`, `reg_date`, `exp_rent`, `house_id`, `updated_at`, `created_at`) values (Mir, 2334, 234, 2020-07-08, 234, ?, 2020-07-14 06:20:47, 2020-07-14 06:20:47))

Please sign in or create an account to participate in this conversation.