Luiz Wynne
Luiz Wynne

Reputation: 500

Trying to execute multiple queries on same function

I am trying to execute 2 queries at the same time on the same function on my application. This function on the controller registers a new house in the system and at the same time, its suppose to feed a field in the Users table that has been null, and this field will then be updated with the new id of the house i have just created. For some reason, the first query works fine but i have been struggling with the second. I believe my logical is fine, maybe the Laravel syntax is making me a bit confused. Can someone help me?

This is my controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\House;
use App\User;

class AdminHouseController extends Controller
{

    public function index(){




    }


    public function create($role_id){

        if($role_id == 1){

            return view('admin.house.create');

        }else{

            return redirect('home');

        }

    }


    public function store(Request $request){

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

        $house_admin = Auth::user()->id;

        $house = House::where('house_admin', $house_admin)->first();

        User::findOrFail($house_admin)->update(['house_id' => $house->id]);


        return redirect('home');

    }

    public function show($id){

    }

    public function edit($id){

    }

    public function update(Request $request, $id){

    }

    public function destroy($id){

    }
}

This is my form //i believe the problem is not here, but anyway

@extends('layouts.app')


@section('content')



    <p><b>Register your house</b></p>


            {!! Form::open(['method'=>'post', 'action'=>'AdminHouseController@store']) !!}

                {!! Form::text('house_address', null,['placeholder'=>'House Address']) !!}

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

                {!! Form::number('nflatmates', null, ['placeholder'=>'How many flatmates']) !!}

                {!! Form::submit('Register', ['class'=>'ui-btn buttonDefault']) !!}

            {!! Form::close() !!}




@stop

And finnaly, this my router web.php //i also believe the problem is not here, but in my controller

use App\User;

Route::get('/', function () {
    return view('welcome');
});


Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/house/{role_id}', 'AdminHouseController@create')->name('house');

Route::post('store', [
    'uses' => 'AdminHouseController@store'
]);

Upvotes: 1

Views: 676

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163748

You need to add the house_id field to the $fillable array in the User model:

protected $fillable = ['house_id', 'other_fields'];

Also, you have two foreign keys instead of one which is redundant. You might want to keep only house_admin foreign key.

Upvotes: 2

Related Questions