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

chris J's avatar

Find() returns collection instead of single element

I made some changes and starting watching the lessons that you recommended (didn't change the table names neither the column names in order to much laravel "rules") . My issue is caused because find($id) returns a collection instead of one element.

public function update(Request $req, $id){
        $input = $req->all();
        $testInfo = testInfo::find($id);
        $testInfo->NAME = $input['Name'];;
        $testInfo->TIME = $input['Time'];;
        $testInfo->OBSERVER_ID = $req->observer_id; 
        dd($id,testInfo::find($id),$testInfo->NAME = $input['Name'],$testInfo->TIME = $input['Time'],$testInfo->OBSERVER_ID = $req->observer_id, $testInfo->LOCATION_ID = $req->LOCATION_ID);
        $testInfo->LOCATION_ID = $req->LOCATION_ID;
        $testInfo->save();
    }

The result of the dd() is

"4"
App\Models\testInfo {#284 ▼
  #table: "infotest"
  +timestamps: false
  #fillable: array:5 [▶]
  #connection: "mysql"
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  +preventsLazyLoading: false
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #escapeWhenCastingToString: false
  #attributes: array:5 [▶]
  #original: array:5 [▶]
  #changes: []
  #casts: []
  #classCastCache: []
  #attributeCastCache: []
  #dates: []
  #dateFormat: null
  #appends: []
  #dispatchesEvents: []
  #observables: []
  #relations: []
  #touches: []
  #hidden: []
  #visible: []
  #guarded: array:1 [▶]
}
"GEORGE"
"18:30"
"1"
"2"

How can I prevent find from creating a collection and return one element?

0 likes
29 replies
Sinnbeck's avatar

That is a single element? The type is App\Models\testInfo which is the model..

tykus's avatar

It is not returning a Collection; you find one testInfo instance with an ID of 4

chris J's avatar

@tykus When I call this functions despite getting all values from the form it doesn't update the database. Is this issue coming from the result of find() ?

tykus's avatar

@chris J it is not an issue of find. It is getting a Model instance and that model instance exists. What do you mean it doesn't update the database?

To ensure you do get a valid record; use findOrFail - this will throw a ModelNotFoundException is there is no record for the given $id:

public function update(Request $req, $id)
{
    $testInfo = testInfo::findOrFail($id);
    $testInfo->NAME = $req->input('Name');
    $testInfo->TIME = $req->input('Time');
    $testInfo->OBSERVER_ID = $req->input('observer_id'); 
    $testInfo->LOCATION_ID = $req->input('LOCATION_ID');
    $testInfo->save();
}
chris J's avatar

@tykus I get the values from the form but when submitting it doesn't update the table.

tykus's avatar

@chris J without the dd (which kills execution)???

Anyway, see my code example above - it will work.

tykus's avatar

@chris J what does your update method look like right now?

chris J's avatar

@tykus My route:

Route::put('formInfo.edit/{ID}', 'App\Http\Controllers\testInfoController@update');

My Controller function:

public function update(Request $req, $id){
        $input = $req->all();
        $testInfo = testInfo::findOrFail($id);
        $testInfo->NAME = $input['Name'];;
        $testInfo->TIME = $input['Time'];;
        $testInfo->OBSERVER_ID = $req->observer_id; 
        $testInfo->LOCATION_ID = $req->LOCATION_ID;
        $testInfo->save();
    }

My view

<form action="{{url('formInfo.edit/'.$testInfo->ID) }}" method="POST" style="display: grid">
                    {{-- url('formInfo.edit/'.$testInfo->ID) --}}
                    {{-- <form action="{{ route('tasks.update', $task->id) }}" method="POST"> --}}
                    {{-- {{ method_field('PUT') }} --}}
                    {{-- <input type="hidden" name="_method" value="PUT" /> --}}
                    @method('PUT')
                    @csrf
                    <input type="text" name="Name" value="{{ old('NAME') ?? $testInfo->NAME}}" placeholder="Name" class="form-control" style="margin-bottom: 8px">
                    <input type="text" name="Time" value="{{ old('TIME') ?? $testInfo->TIME}}" placeholder="Time" class="form-control" style="margin-bottom: 8px">
                    <select name='observer_id' class='form-control mt-2 mb-2'>
                        @foreach($observer as $observer)
                            <option value="{{ $observer->ID }}" {{ $testInfo->OBSERVER_ID == $observer->ID ? 'selected' : ''  }}>{{ $observer->NAME}}</option>
                        @endforeach
                    </select>
                    <select name='LOCATION_ID' class='form-control mt-2 mb-2'>
                        @foreach($locations as $location)
                            <option value="{{ $location->id }}">{{ $location->Onoma_Perioxis}}</option>
                        @endforeach
                    </select>
                    {{-- <input type="text" name="parasites_anomalies" placeholder="Parasites Anomalies" value="{{ old('parasites_anomalies') ?? $testInfo->parasites_anomalies}}" class="form-control" style="margin-bottom: 8px"> --}}
                    <button type="submit" class="btn btn-primary">Post</button>
                </form>

Location model:

class location extends Model
{
    protected $table="locations";
    protected $fillable=['id','kodikos','Onoma_Perioxis','Kodikos2','wee'];
    public $timestamps = false;

}

testinfo Model:

class testInfo extends Model
{
    protected $table = "infotest";
    public $timestamps = false;
    protected $fillable=['ID','NAME','TIME', 'OBSERVER_ID', 'LOCATION_ID'];
}

observer model:

class observer extends Model
{
    protected $table="observer";
    protected $fillable = ['ID','NAME','LAST_NAME'];
    public $timestamps = false;
}
tykus's avatar

@chris J I asked about the update action in the Controller!

Aside, what kind of ugly URL is this producing: url('formInfo.edit/'.$testInfo->ID)?

Sinnbeck's avatar

@chris J You really need to consider your naming. For instance you tell laravel that the variable is named {ID} yet, in the controller you name it $id. Case matters in most of laravel/php. I can imagine that this issue happens in other places as well.

(doing it in the route isone of the few places where it will still work, as laravel will count the numbers of arguments)

Edit: the route example was dumb as pointed out by @tykus. Sorry

tykus's avatar

@Sinnbeck that is not exactly correct...

For instance you tell laravel that the variable is named {ID} yet, in the controller you name it $id.

When you're not type-hinting for Route-Model Binding; it doesn't matter whether the wildcard and parameter match at all; they can even be named differently.

1 like
Sinnbeck's avatar

@tykus Yeah you are correct. It was a bad example but was meant to be more of a rule of thumb :)

tykus's avatar

@Sinnbeck the point about consistency and convention is well made!

1 like
chris J's avatar

@Sinnbeck I am probably going to start over and pay attention to my naming. Aside from that I have checked and every connection is done correctly and my conclusion came from the dd() results. So to be clear, this is an issue coming from my naming or I should update the table with another way?

Sinnbeck's avatar

@tykus Thanks :) Brain fart from my part though! I have edited my answer to better reflect the truth

tykus's avatar

@chris J can you just show us the current implementation of the update method?

chris J's avatar

@tykus

public function update(Request $req, $ID){
        $input = $req->all();
        $testInfo = testInfo::findOrFail($ID);
        $testInfo->NAME = $input['Name'];
        $testInfo->TIME = $input['Time'];
        $testInfo->OBSERVER_ID = $req->observer_id;
		$testInfo->LOCATION_ID = $req->LOCATION_ID;
		$testInfo->save();
}
tykus's avatar

@chris J this is not working; do you have a Model Observer / Model Event registered for the saving event?

Sinnbeck's avatar

@chris J Try testing it as simple as possible

public function update(Request $req, $ID){
        $input = $req->all();
        $testInfo = testInfo::findOrFail($ID);
        $testInfo->NAME = 'This is a test name'; //look for this.
        $testInfo->TIME = $input['Time'];
        $testInfo->OBSERVER_ID = $req->observer_id;
		$testInfo->LOCATION_ID = $req->LOCATION_ID;
		$testInfo->save();
          
        dd(testInfo::findOrFail($ID)->toArray());
}
chris J's avatar

@Sinnbeck This returns an array but it doesn't update the value when changed from the dropdown

chris J's avatar

I think that I will start from the begging and pay attention to my naming because this is very confusing. Thank you for your help

Snapey's avatar

The dd looks ok to me

The only objectionable part is your naming conventions

chris J's avatar

@Snapey I know that the table names and field names are not good but in every model I have defined the table and the fillables. My issue is that despite getting all the data the table is not updated. Where can this error come from?

Snapey's avatar

@chris J focus on cleaning up your code (I think I said this before)

<input type="text" name="Name" value="{{ old('NAME') ?? $testInfo->NAME}}" placeholder="Name" class="form-control" style="margin-bottom: 8px">

note

<input type="text" name="Name" value="{{ old('Name', $testInfo->NAME)}}" placeholder="Name" class="form-control" style="margin-bottom: 8px">
1 like

Please or to participate in this conversation.