Ошибка: попытка получить свойство не-объекта при создании или сохранении данных

введите здесь описание изображения

«Попытка получить свойство не-объекта»

Модель

При создании новых данных и желании их сохранить возникает ошибка, как указано выше.

public static function findOrCreate($plan_id, $data)
{
    $fromDate = Carbon::now()->subDay()->startOfWeek();
    $nowDate = Carbon::now()->today();

    $spent_time = static::where('plan_id', $plan_id)->first();

    if (is_null($spent_time)) {
        return static::create($data);
    }else{
        $new_spent_time = SpentTime::find($plan_id);
        $task_category = $new_spent_time->task_category;

        $new_spent_time->task_category = (['{task_category}' => $task_category, 
                                        '{daily_spent_time}' => $new_spent_time->daily_spent_time,
                                        '{daily_percentage}' => $new_spent_time->daily_percentage,
                                        '{spent_time}' => $new_spent_time->spent_time,
                                        '{percentage}' => $new_spent_time->percentage, $new_spent_time->task_category]);

        $new_spent_time->spent_time = $new_spent_time::where('task_category',$task_category)
                                    ->sum('daily_spent_time', $new_spent_time->daily_spent_time , $fromDate);
        $request['spent_time'] = (int)$new_spent_time->spent_time + $spent_time->daily_spent_time;

        $new_spent_time->percentage = $new_spent_time::where('task_category',$task_category)
                                    ->sum('daily_percentage', $new_spent_time->daily_percentage, $fromDate);
        $request['percentage'] = (int)$new_spent_time->percentage  + $spent_time->daily_percentage;
        $new_spent_time->save();

        return $spent_time->update($data);
    }

person Lia nur fadilah    schedule 19.10.2018    source источник


Ответы (2)


"Trying to get property of non-object" означает, что свойство не существует

поменяй find на findOrFail

$new_spent_time = SpentTime::findOrFail($plan_id);

таким образом, laravel вернет ошибку, если не найдет запись в базе данных.

другой способ проверить, успешно ли выполнен ваш запрос:

$new_spent_time = SpentTime::find($plan_id);
if($new_spent_time){

    $task_category = $new_spent_time->task_category;

    $new_spent_time->task_category = (['{task_category}' => $task_category, 
                                    '{daily_spent_time}' => $new_spent_time->daily_spent_time,
                                    '{daily_percentage}' => $new_spent_time->daily_percentage,
                                    '{spent_time}' => $new_spent_time->spent_time,
                                    '{percentage}' => $new_spent_time->percentage, $new_spent_time->task_category]);

    $new_spent_time->spent_time = $new_spent_time::where('task_category',$task_category)
                                ->sum('daily_spent_time', $new_spent_time->daily_spent_time , $fromDate);
    $request['spent_time'] = (int)$new_spent_time->spent_time + $spent_time->daily_spent_time;

    $new_spent_time->percentage = $new_spent_time::where('task_category',$task_category)
                                ->sum('daily_percentage', $new_spent_time->daily_percentage, $fromDate);
    $request['percentage'] = (int)$new_spent_time->percentage  + $spent_time->daily_percentage;
    $new_spent_time->save();

    return $spent_time->update($data);
}else{
    return 'no result found';
}
person Kapitan Teemo    schedule 19.10.2018
comment
но страница не найдена. есть другое решение? - person Lia nur fadilah; 19.10.2018
comment
при сохранении создавать новые данные с той же категорией. - person Lia nur fadilah; 19.10.2018
comment
это означает, что laravel не нашел ни одной записи в вашей базе данных. попробуйте вернуть $plan_id и посмотрите, какие данные он возвращает, а затем сравните их в своей базе данных, если эти id действительно существуют. - person Kapitan Teemo; 19.10.2018
comment
Если вы используете $new_spent_time = SpentTime::findorfail($plan_id);, страница не будет найдена. но если использовать $new_spent_time = SpentTime::get(); ошибка, подобная этой Свойство [task_category] не существует в этом экземпляре коллекции. - person Lia nur fadilah; 19.10.2018
comment
Route::resource('/real', 'Контроллер трекера'); - person Lia nur fadilah; 19.10.2018
comment
ваш маршрут с использованием public static function findOrCreate - person Kapitan Teemo; 19.10.2018
comment
что он говорит? - person Lia nur fadilah; 19.10.2018
comment
Я имею в виду, можете ли вы показать свой маршрут, используя public static function findOrCreate? Route::resource('/real', 'TrackerController'); не использует эту конкретную функцию - person Kapitan Teemo; 19.10.2018
comment
Извините, я еще не понимаю вашу точку зрения, не могли бы вы мне помочь, пожалуйста - person Lia nur fadilah; 19.10.2018
comment
в вашем routes.php покажите мне route, который использует функцию findOrCreate. нравится Route::post('/sample','SampleController@findOrCreate'); - person Kapitan Teemo; 19.10.2018
comment
вы можете проверить ссылку stackoverflow.com/questions/52865862/, вы можете мне помочь? - person Lia nur fadilah; 19.10.2018
comment
потому что в контроллере я сделал вызов модели - person Lia nur fadilah; 19.10.2018

это должно быть при сохранении данных, которые созданы, перейдут в форму и подсчитают количество данных

введите здесь описание изображения

person Lia nur fadilah    schedule 19.10.2018