Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

YuraLons's avatar

How can I edit fields from another data table?

FullController House

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\House;
use App\Models\Otchet;
use Validate;

class HouseController extends Controller
{
    function index()
    {
        $houses = House::all();
        return view('house.list', compact('houses'));
    }
    public function show($id)
    {
        $house = House::with(['getOtchetsForHouse','getDogovorsForHouse','getProtocolsForHouse','getPassportsForHouse'])->find($id);
        $house->getOtchetsForHouse;
        $house->getDogovorsForHouse;
        $house->getProtocolsForHouse;
        $house->getPassportsForHouse;
        
        return view('house.show', compact('house'));
    }
    function create(Request $request)
    {
        return view('house.create');
    }
    function store(Request $request)
    {
        $this->validate($request, [
            'name'=>'required',
        ]);

        $house = House::query()->create([
            'name' => $request->get('name'),
            'description' => $request->get('description'),
        ]);
       
        // foreach($request->getOtchetsForHouse as $index => $otchets) {

        //     $house->otchets()->create([
        //         'file_name' => $otchet['file_name'],
        //         'link_file' => $otchet['link_file'],
        //      ]);

        // }

        // $house->getOtchetsForHouse()->
        // create([
        //     'otchet_name' => $request->get('otchet_name'),
        //     'otchet_link' => $request->get('otchet_link')
        // ]);
        // $house->getDogovorsForHouse()->
        // create([
        //     'dogovor_name' => $request->get('dogovor_name'),
        //     'dogovor_link' => $request->get('dogovor_link')
        // ]);
        // $house->getProtocolsForHouse()->
        // create([
        //     'protocol_name' => $request->get('protocol_name'),
        //     'protocol_link' => $request->get('protocol_link')
        // ]);
        // $house->getPassportsForHouse()->
        // create([
        //     'passport_name' => $request->get('passport_name'),
        //     'passport_link' => $request->get('passport_link')
        // ]);


        foreach($request->get('otchet_name') as $key => $otchetName) {
            $house->getOtchetsForHouse()
            ->create([
                'otchet_name' => $otchetName,
                'otchet_link' => data_get($request->get('otchet_link'), $key),
            ]);
        }
        foreach($request->get('dogovor_name') as $key => $dogovorName) {
            $house->getDogovorsForHouse()
            ->create([
                'dogovor_name' => $dogovorName,
                'dogovor_link' => data_get($request->get('dogovor_link'), $key),
            ]);
        }
        foreach($request->get('protocol_name') as $key => $protocolName) {
            $house->getProtocolsForHouse()
            ->create([
                'protocol_name' => $protocolName,
                'protocol_link' => data_get($request->get('protocol_link'), $key),
            ]);
        }
        foreach($request->get('passport_name') as $key => $passportName) {
            $house->getPassportsForHouse()
            ->create([
                'passport_name' => $passportName,
                'passport_link' => data_get($request->get('passport_link'), $key),
            ]);
        }

        dd($request->all());

        // return redirect()->route('house.index');
    }
    function edit(Request $request, $id)
    {
        $house = House::find($id);
        return view('house.edit', compact('house'));
    }
    function update(Request $request, $id)
    {
        $house = House::findOrFail($id);
        $house->name                 =   $request->get('name');
        $house->description          =   $request->get('description');
        
        $house->save();
        foreach ($request->get('passport', []) as $passportId => $passportAttributes) {
            $house->getPassportsForHouse()->where('id', $passportId)->update($passportAttributes);
            }
        foreach ($request->get('otchet', []) as $otchetId => $otchetAttributes) {
            $house->getOtchetsForHouse()->where('id', $otchetId)->update($otchetAttributes);
        }
        foreach ($request->get('dogovor', []) as $dogovorId => $dogovorAttributes) {
            $house->getDogovorsForHouse()->where('id', $dogovorId)->update($dogovorAttributes);
        }
        foreach ($request->get('protocol', []) as $protocolId => $protocolAttributes) {
            $house->getProtocolsForHouse()->where('id', $protocolId)->update($protocolAttributes);
        }
        return redirect()->route('house.index');
    }
}
function update(Request $request, $id)
    {
        $house = House::findOrFail($id);
        $house->name            =   $request->get('name');
        $house->description     =   $request->get('description');
        $house->getOtechetForHouse = $request->get('otchet_name');
        $house->getOtechetForHouse = $request->get('otechet_link');

        $house->save();
        return redirect()->route('house.index');
    }

view

<div align="center">
<form method="post" action="{{ route('house.update', ['house' => $house->id]) }}">
    @csrf
    @method('PUT')
    <div>
        <label for="name">Name</label>
        <input type="text" name="name" value="{{ $house->name }}">
    </div>
    <div>
        <label for="">Description</label>
        <input type="text" name="description" value="{{ $house->description }}">
    </div>
    <div>
        <label for="">Report</label>
        <input type="text" name="otchet_name" value="{{ $house->otchet_name }}">
    </div>
    <button type="submit">Save</button>
</form>
</div>

Everything works in the controller, all data is displayed according to the ID of the house, but here's the problem with getting data that is outside the house table, I have 4 tables that are connected via hasMany, there are no problems with adding, but there were big problems with editing. I tried to output through: $house -> getPassportsForHouse = $request -> get('passport_name'); It just did not show anything, in principle, there is nothing surprising in this. The table looks like this: passport table

 Schema::create('passports', function (Blueprint $table) {
            $table->id();
            $table->text('passport_name');
            $table->text('passport_link');
            $table->unsignedBigInteger('house_id')->index();
            $table->foreign('house_id')->references('id')->on('houses');
            $table->timestamps();
        });

house table

Schema::create('houses', function (Blueprint $table) {
            $table->id();
            $table->string('name')->nullable();
            $table->text('description')->nullable();
            $table->timestamps();
        });

How to correctly add the code so that I can edit the records belonging to the house in the tables passport, contract, report, protocols

0 likes
31 replies
tykus's avatar

What is getPassportsForHouse supposed to represent?

YuraLons's avatar

I didn't understand much of your question. I will answer in terms of my guesses He should receive a list of passports in which the home_id field has the id of the house being edited.

Model Passport

use App\Models\House;

class Passport extends Model
{
    use HasFactory;

    protected $table = 'passports';

    protected $fillable = [
        'passport_name',
        'passport_link'
    ];

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

I meant what is getPassportsForHouse; which I suppose is the name of the hasMany relation method? Generally, this would simply be named passports - which I will use for the example below.

Anyway, to the problem. If you want to update a resource - a Passport associated with the House - you need to provide the identifier for that Resource. You can easily achieve this using the form input array syntax to group the fields by the id of each Passport:

<form method="post" action="{{ route('house.update', ['house' => $house->id]) }}">
    @csrf
    @method('PUT')
	<!-- house specific fields -->

	<!-- iterate over the associated Passport model -->
    <div>
        <label for="">Passports</label>
		@foreach ($house->passports as $passport)
	        <input type="text" name="passport[$passport->id][name]" value="{{ $passport->name }}">
	        <input type="text" name="passport[$passport->id][description]" value="{{ $passport->description }}">
		@endforeach
    </div>

    <button type="submit">Save</button>
</form>

Then in the Request, you will have a passports field indexed by the id with all of the fields to be updated:

function update(Request $request, $id)
{
	$house = House::findOrFail($id);
	$house->name            =   $request->get('name');
	$house->description     =   $request->get('description');
	$house->getOtechetForHouse = $request->get('otchet_name');
	$house->getOtechetForHouse = $request->get('otechet_link');

	$house->save();


	foreach ($request->get('passports', []) as $passportId => $passportAttributes) {
		$house->passports()->where('id', $passportId)->update($passportAttributes);
	}

	return redirect()->route('house.index');
}
YuraLons's avatar

That is, as I understand it, the code is referring directly to the table? It's just that my model has four belongsTo getPassportForHouse getDogovorsForHuse getReportForHouse getProtocolForHouse. On creation, I refer to them this way:

foreach($request->get('passport_name') as $key => $passportName) {
            $house->getPassportsForHouse()
            ->create([
                'passport_name' => $passportName,
                'passport_link' => data_get($request->get('passport_link'), $key),
            ]);
        }

And if I understand correctly, then the model you have given can be changed somehow so that later you will not be confused where and where there was no mess in the code

function update(Request $request, $id)
{
	$house = House::findOrFail($id);
	/// code#
	$house->getOtchetForHouse = $request->get('otchet_name');
	$house->getOtchetForHouse = $request->get('otchet_link');
	$house->getProtocolForHouse = $request->get('protocol_name');
	$house->getProtocolForHouse = $request->get('protocol_link');
	$house->getPassportForHouse= $request->get('passport_name');
	$house->getPassportForHouse= $request->get('passport_link');
	$house->getDogovorForHouse= $request->get('dogovor_name');
	$house->getDogovorForHouse= $request->get('dogovor_link');

	$house->save();

	foreach ($request->get('passport', []) as $passportId => $passportAttributes) {
		$house->getPassportForHouse()->where('id', $passportId)->update($passportAttributes);
	}
foreach ($request->get('otchet', []) as $otchetId => $otechetAttributes) {
		$house->getOtchetForHouse ()->where('id', $otchetId)->update($otechetAttributes);
	}
foreach ($request->get('dogovor', []) as $dogovorId => $dogovorAttributes) {
		$house->getDogovorForHouse()->where('id', $dogovorId)->update($dogovorAttributes);
	}
foreach ($request->get('protocol', []) as $protocolId => $protocolAttributes) {
		$house->getProtocolForHouse ()->where('id', $protocolId)->update($protocolAttributes);
	}

View

<div>
        <label for="">Passports</label>
		@foreach ($house->getPassportForHouse as $passport)
	        <input type="text" name="passport[$passport->id][passport_name ]" value="{{ $passport->passport_name }}">
	        <input type="text" name="passport[$passport->id][passport_link]" value="{{ $passport->passport_link}}">
		@endforeach
    </div>
<div>
        <label for="">dogovor</label>
		@foreach ($house->getDogovorForHouseas $dogovor)
	        <input type="text" name="dogovor[$dogovor->id][dogovor_name ]" value="{{ $dogovor->dogovor_name }}">
	        <input type="text" name="dogovor[$dogovor->id][dogovor_link]" value="{{ $dogovor->dogovor_link}}">
		@endforeach
    </div>
<div>
        <label for="">Othcet</label>
		@foreach ($house->getOtchetForHouse as $otchet)
	        <input type="text" name="otchet[$otchet->id][otchet_name ]" value="{{ $otchet->otchet_name }}">
	        <input type="text" name="otchet[$otchet->id][otechet_link]" value="{{ $otchet->otechet_link}}">
		@endforeach
    </div>
<div>
        <label for="">Protocols</label>
		@foreach ($house->getProtocolForHouse as $protocol)
	        <input type="text" name="protocol[$protocol->id][protocol_name]" value="{{ $protocol->protocol_name}}">
	        <input type="text" name="protocol[$protocol->id][protocol_link]" value="{{ $protocol->protocol_link}}">
		@endforeach
    </div>

Is the given code correct? or contains errors?

tykus's avatar

The field names should echo the related ids because they are dynamic, i.e.

name="passport[{{ $passport->id }}][passport_name]"

This was my fault from previous post. Otherwise, I believe that should be working, yes.

YuraLons's avatar

I got an error while editing at home ErrorException Undefined array key 1

tykus's avatar

I don't immediately see where that could be coming from; where is the error happening in the code?

YuraLons's avatar

As I understand it, everything refers to blade files. The stack is the first to display error 95 line in the file Foundation \ Bootstrap \ HandleExceptions :: handleError, $iteratee = trim ($matches [1]); Then all the mistakes are repeated Illuminate\View\Compilers\BladeCompiler::compileStatements

tykus's avatar

Don't know that this is the source of the exception but fix this and see if it changes:

@foreach ($house->getDogovorForHouseas $dogovor)

should be

@foreach ($house->getDogovorForHouse as $dogovor)
YuraLons's avatar

A new error, but now all the fields are filled in as needed, the entire list of fields that I filled out for the house is displayed, but after editing the following:

lluminate\Database\QueryException
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'getOtchetsForHouse' in 'field list' (SQL: update `houses` set `name` = Test house, `description` = Test house, `getOtchetsForHouse` = ?, `getProtocolsForHouse` = ?, `getPassportsForHouse` = ?, `getDogovorsForHouse` = ?, `houses`.`updated_at` = 2021-04-19 13:25:49 where `id` = 1)
tykus's avatar

Missed this earlier; this is not how you update the relations 🤦‍♂️

Delete all of these lines:

	$house->getOtchetForHouse = $request->get('otchet_name');
	$house->getOtchetForHouse = $request->get('otchet_link');
	$house->getProtocolForHouse = $request->get('protocol_name');
	$house->getProtocolForHouse = $request->get('protocol_link');
	$house->getPassportForHouse= $request->get('passport_name');
	$house->getPassportForHouse= $request->get('passport_link');
	$house->getDogovorForHouse= $request->get('dogovor_name');
	$house->getDogovorForHouse= $request->get('dogovor_link');

You should only update/modify House attributes here (if relevant):

	$house = House::findOrFail($id);
	$house->name =   $request->get('name');
	$house->description =   $request->get('description');
	$house->save():
YuraLons's avatar

Damn - for sure, my fault .. I forgot myself that these fields are not there, but even after deleting these fields, the error remained in place

tykus's avatar

Which error exactly?

Can you also post the full Controller action as it currently is written?

YuraLons's avatar

Added a full controller to the first post

YuraLons's avatar
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'passport_name ' in 'field list' (SQL: update `passports` set `passport_name ` = $house->save();, `passport_link` = $house->save();, `passports`.`updated_at` = 2021-04-19 13:34:37 where `passports`.`house_id` = 1 and `passports`.`house_id` is not null and `id` = $passport->id)
tykus's avatar

It is not the same error as before. Why (if the earlier migration showed otherwise) is the passport_name field not available on the passports table; did you share an incorrect migration?

The update query is a mess; why is the value of passport_name and passport_linkbeing set to literally $house->save();, and why is the id constraint literally $passport->id.

Can you please show a dump(request()->all() in the update action?

YuraLons's avatar

I add dump($request()->all()); but I still have the same error on the page. Added like this

function update(Request $request, $id)
    {
        $house = House::findOrFail($id);
        $house->name                 =   $request->get('name');
        $house->description          =   $request->get('description');
        
       // #code

        dump($request()->all());
        // return redirect()->route('house.index');
    }

All the migrations that were added in the first post are exactly the same as those that I use.

tykus's avatar

Why not at the top of the method?

YuraLons's avatar
array:8 [▼
  "_token" => "cPsdUSvu8k4Py713OOId2xUAyroFFqWkQ3ApVvqL"
  "_method" => "PUT"
  "name" => "Test new house UPD"
  "description" => "Description house test"
  "passport" => array:1 [▼
    "$passport->id" => array:2 [▼
      "passport_name " => "Passport 2"
      "passport_link" => "Link passport 2 UPD"
    ]
  ]
  "dogovor" => array:1 [▼
    "$dogovor->id" => array:2 [▼
      "dogovor_name " => "Dogovor 2 UPD"
      "dogovor_link" => "Link dogovor2"
    ]
  ]
  "otchet" => array:1 [▼
    "$otchet->id" => array:2 [▼
      "otchet_name" => "Report 2 UPD"
      "otchet_link" => "Link Report 2"
    ]
  ]
  "protocol" => array:1 [▼
    "$protocol->id" => array:2 [▼
      "protocol_name" => "Protocol 2"
      "protocol_link" => "Link protocol 2 UPD"
    ]
  ]
YuraLons's avatar

As far as I can understand, it tries to update several records, but it can't, it only issues an update of the second field

tykus's avatar

You didn't change the form input names like I described earlier:

<input name="passport[{{ $passport->id }}][passport_name]" value="{{ $passport->passport_name }}" />
YuraLons's avatar

As I understand it now, there is an error in the date fields in the reports, contracts, protocols and passports tables ?

SQLSTATE[22007]: Invalid datetime format: 1292 Truncated incorrect DOUBLE value: '$passport->id' (SQL: update `passports` set `passport_name` = Passport 2 UPD, `passport_link` = Link passport 2 UPD, `passports`.`updated_at` = 2021-04-19 15:17:40 where `passports`.`house_id` = 2 and `passports`.`house_id` is not null and `id` = $passport->id)
tykus's avatar

This is the snippet of code we are currently dealing with:

foreach ($request->get('passport', []) as $passportId => $passportAttributes) {
	$house->getPassportsForHouse()->where('id', $passportId)->update($passportAttributes);
}

For some reason, the string literal $passport->id is the value of $passportId. The only reason possible for this is once again because there is a badly named input. Can you please show me again the view template as it is currently written?

YuraLons's avatar

edit blade.php

@extends('index')

@section('content')

<div align="center">
<form method="post" action="{{ route('house.update', ['house' => $house->id]) }}">
    @csrf
    @method('PUT')
    <div>
        <label for="name">name</label>
        <input type="text" name="name" value="{{ $house->name }}">
    </div>
    <div>
        <label for="">description </label>
        <input type="text" name="description" value="{{ $house->description }}">
    </div>
    <div>
        <label for="">Passports</label>
		@foreach ($house->getPassportsForHouse as $passport)
	        <input type="text" name="passport[$passport->id][passport_name]" value="{{ $passport->passport_name }}">
	        <input type="text" name="passport[$passport->id][passport_link]" value="{{ $passport->passport_link }}">
		@endforeach
    </div>
<div>
        <label for="">dogovor</label>
		@foreach ($house->getDogovorsForHouse as $dogovor)
	        <input type="text" name="dogovor[$dogovor->id][dogovor_name]" value="{{ $dogovor->dogovor_name }}">
	        <input type="text" name="dogovor[$dogovor->id][dogovor_link]" value="{{ $dogovor->dogovor_link }}">
		@endforeach
    </div>
<div>
        <label for="">Othcet</label>
            @foreach ($house->getOtchetsForHouse as $otchet)
                <input type="text" name="otchet[$otchet->id][otchet_name]" value="{{ $otchet->otchet_name }}">
                <input type="text" name="otchet[$otchet->id][otchet_link]" value="{{ $otchet->otchet_link }}">
            @endforeach
    </div>
<div>
        <label for="">Protocols</label>
		@foreach ($house->getProtocolsForHouse as $protocol)
	        <input type="text" name="protocol[$protocol->id][protocol_name]" value="{{ $protocol->protocol_name }}">
	        <input type="text" name="protocol[$protocol->id][protocol_link]" value="{{ $protocol->protocol_link }}">
		@endforeach
    </div>
    <button type="submit">Save</button>
</form>
</div>

@endsection
tykus's avatar
tykus
Best Answer
Level 104

Twice already I have told you that you must echo the relation instance ids:

<input type="text" name="passport[{{ $passport->id }}][passport_name]" value="{{ $passport->passport_name }}">

And so on for each one:

<input type="text" name="passport[{{ $passport->id }}][passport_link]" value="{{ $passport->passport_link }}">

I am not rewriting your template, but hopefully you understand that you should expand this for each relation???

<input type="text" name="dogovor[{{ $dogovor->id }}][dogovor_name]" value="{{ $dogovor->dogovor_name }}">

And so on,

1 like
YuraLons's avatar

great, tomorrow I won't get a blow on the head from the director). Thank you so much for your help and I apologize for taking the time to solve my problems.

YuraLons's avatar

Okay, I'll watch the video, but after I solve the problem with editing the fields in the cards at home, as now our company is suffering from this problem. I apologize for the inconvenience

Please or to participate in this conversation.