TJ Weems
TJ Weems

Reputation: 1114

Error Trying To Get Property Of Non-Object In Laravel 5.6

so I am trying to loop through an array of objects to update certain values in my database with the values from the object

When I run this loop in my controller

foreach($statuses as $status){
            $workflow->statuses()->where('id', $status->id)->update([
                'status' =>  $status->status
            ]);
        };

It gives me error trying to get property of non-object

When I do a `return response($request->statuses) this is the data structure I see in the console enter image description here

here is the complete controller

public function workflowStatuses(Request $request, Workflow $workflow)
    {

        // validate form data
        $data = $request->validate([
            'workflow' => 'required|string',
        ]);

            // validate form data
        $oldStatuses = $request->validate([
            'statuses' => 'required|array'
        ]);

        // validate form data
        $newStatuses = $request->validate([
            'newStatuses' => 'required|array',
        ]);


        $workflow->update($data);

        $statuses = $oldStatuses;

        foreach($statuses as $status){
            $workflow->statuses()->where('id', $status['id'])->update([
                'status' =>  $status->status
            ]);
        };

        $workflow->statuses()->saveMany($newStatuses);

        return response($workflow, 200);

    }

Upvotes: 0

Views: 296

Answers (2)

Manpreet
Manpreet

Reputation: 2620

Try:

foreach($statuses as $status){
   $workflow->statuses()->where('id', $status['id'])->update([
   'status' =>  $status['status'] //$status['status'] should also be accessed by key 
   ]);
};

Upvotes: 0

Devon Bessemer
Devon Bessemer

Reputation: 35337

You can think of the return value of $request->validate() as the array of all request input filtered to only include the data that's being validated. If that validated data contains arrays, you'll have a multi-dimensional array.

Here, $oldStatuses is going to be an array that contains a key named statuses that contains the actual array you're looking for.

$oldStatuses = $request->validate([
   'statuses' => 'required|array'
]);


// $statuses should get 'statuses' out of this validated array
$statuses = $oldStatuses['statuses'];

Instead, you may want to clean this up and not call validate three times. It's usually better to run all the validation rules in one validate() call, unless you have good reason to logically separate them.

$validated = $request->validate([
   'workflow' => 'required|string',
   'statuses' => 'required|array',
   'newStatuses' => 'required|array',
]);

$statuses = $validated['statuses'];

Upvotes: 1

Related Questions