【问题标题】:problem after upgrading laravel and php version [closed]升级laravel和php版本后的问题[关闭]
【发布时间】:2021-05-16 22:47:46
【问题描述】:

我正在使用 laravel 5.2.45 和 PHP 7.1 没有任何问题,然后我决定升级到 laravel 7 和 php 7.4 我正在从事的项目正在运行,但我在某些页面上遇到问题,尤其是 laravel 中的属于关系,我收到此错误

 [2021-02-13 15:32:00] local.ERROR: Trying to access array offset on value of type null {"exception":"[object] (ErrorException(code: 0): Trying to access array offset on value of type null at /var/www/html/easy/app/Http/Controllers/SubscriberController.php:431)
[stacktrace]
#0 /var/www/html/easy/app/Http/Controllers/SubscriberController.php(431): Illuminate\\Foundation\\Bootstrap\\HandleExceptions->handleError()
#1 [internal function]: App\\Http\\Controllers\\SubscriberController->userFilterData()
#2 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Controller.php(54): call_user_func_array()
#3 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/ControllerDispatcher.php(45): Illuminate\\Routing\\Controller->callAction()
#4 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Route.php(240): Illuminate\\Routing\\ControllerDispatcher->dispatch()
#5 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Route.php(197): Illuminate\\Routing\\Route->runController()
#6 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(681): Illuminate\\Routing\\Route->run()
#7 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Routing\\Router->Illuminate\\Routing\\{closure}()
#8 /var/www/html/easy/app/Http/Middleware/Permissions.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#9 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): App\\Http\\Middleware\\Permissions->handle()
#10 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/VerifyCsrfToken.php(76): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#11 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\VerifyCsrfToken->handle()
#12 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/View/Middleware/ShareErrorsFromSession.php(49): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#13 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\View\\Middleware\\ShareErrorsFromSession->handle()
#14 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Session/Middleware/StartSession.php(56): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#15 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Session\\Middleware\\StartSession->handle()
#16 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/AddQueuedCookiesToResponse.php(37): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#17 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Cookie\\Middleware\\AddQueuedCookiesToResponse->handle()
#18 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Cookie/Middleware/EncryptCookies.php(66): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#19 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Cookie\\Middleware\\EncryptCookies->handle()
#20 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#21 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(683): Illuminate\\Pipeline\\Pipeline->then()
#22 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(658): Illuminate\\Routing\\Router->runRouteWithinStack()
#23 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(624): Illuminate\\Routing\\Router->runRoute()
#24 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Routing/Router.php(613): Illuminate\\Routing\\Router->dispatchToRoute()
#25 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(165): Illuminate\\Routing\\Router->dispatch()
#26 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(128): Illuminate\\Foundation\\Http\\Kernel->Illuminate\\Foundation\\Http\\{closure}()
#27 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Middleware/CheckForMaintenanceMode.php(63): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#28 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(167): Illuminate\\Foundation\\Http\\Middleware\\CheckForMaintenanceMode->handle()
#29 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Pipeline/Pipeline.php(103): Illuminate\\Pipeline\\Pipeline->Illuminate\\Pipeline\\{closure}()
#30 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(140): Illuminate\\Pipeline\\Pipeline->then()
#31 /var/www/html/easy/vendor/laravel/framework/src/Illuminate/Foundation/Http/Kernel.php(109): Illuminate\\Foundation\\Http\\Kernel->sendRequestThroughRouter()
#32 /var/www/html/easy/public/index.php(55): Illuminate\\Foundation\\Http\\Kernel->handle()
#33 {main}
"} 

这是我的模型

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class Subscriber extends Model
{
    protected $table = 'reign_users';

    public $timestamps = false;

    /*public function profile()
    {
        return $this->belongsTo('App\Model\Profile', 'owner');
    }*/
    public function profiles()
    {
        return $this->hasOne('App\Model\Profile', 'id', 'srvid');
    }

    public function owners()
    {
        return $this->hasOne('App\Model\AclManager', 'id', 'owner');
    }
    
    public function radAcctData() {
        return $this->hasOne('App\Model\RadAcct', 'username', 'username');
    }
    
    public function usermac() {
        return $this->hasOne('App\Model\UserMAC', 'username', 'username');
    }
    
    public function onlineData() {
        return $this->hasOne('App\Model\OnlineUser', 'username', 'username');
    }

    public function userInvoice(){
        return $this->hasOne('App\Model\UserInvoice', 'username', 'username')->latest();
    }

    public function userNetwork(){
        return $this->hasOne('App\Model\Networks', 'id', 'networkid');
    }

    public function thanaName(){
        return $this->hasOne('App\Model\Thana', 'id', 'thana');
    }


}

这是我在控制器代码中的代码

  public function userFilterData(Request $request) {


        $user = Subscriber::with( 'userInvoice', 'usermac', 'userNetwork');

//        $user = Subscriber::leftJoin('radacct as r', function ($join) use($request) {
//                    $join->on('r.username', '=', 'reign_users.username');
//                    $join->on("r.acctstoptime", "IS", DB::raw("NULL"));
//                })
//                        ->with('userInvoice', 'usermac', 'userNetwork');

        /* only manager cannot see the deleted user */
        if (Session::get('type') == "Manager" && Session::get('admin_assistant') == 0) {
            $user->where('reign_users.owner', Session::get('id'));
        }

//date filter conditionn
        if (isset($request->dateFlag)) {
            $today = date("Y-m-d");
            if ($request->dateFlag == 1) {
                $user->where(DB::raw("date_format(reign_users.createdon, '%Y-%m-%d')"), $today);
            } elseif ($request->dateFlag == 2) {
                $weekStart = date('Y-m-d', strtotime('-6 days'));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$weekStart' AND '$today'");
            } elseif ($request->dateFlag == 3) {
                $monthStart = date('Y-m-d', strtotime('first day of this month'));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$monthStart' AND '$today'");
            } elseif ($request->dateFlag == 4) {
                $range = explode('-', $request->dateRange);
                $startDate = date('Y-m-d', strtotime($range[0]));
                $endDate = date('Y-m-d', strtotime($range[1]));
                $user->whereRaw("date_format(reign_users.createdon, '%Y-%m-%d') BETWEEN '$startDate' AND '$endDate'");
            } else {

            }
        }


//filter by user's status like active,online,expired
        if (isset($request->userStatus) && $request->userStatusVal != "") {
            $today = date("Y-m-d H:i:s");
            if ($request->userStatusVal == 1) {
                $user->whereRaw("reign_users.expiration <= '$today'");
            }
            if ($request->userStatusVal == 2) {
                $user->whereRaw("reign_users.expiration >= '$today'");
            }
            if ($request->userStatusVal == 3) {
                $threeDaysAfter = date("Y-m-d", strtotime("+3 days"));
                $dateToday = date("Y-m-d");
                $user->whereRaw("date_format(reign_users.expiration, '%Y-%m-%d') BETWEEN '$dateToday' AND '$threeDaysAfter'");
            }
            if ($request->userStatusVal == 4) {
                $user->whereRaw("reign_users.enableuser = 1");
            }
            if ($request->userStatusVal == 5) {
                $user->whereRaw("reign_users.enableuser = 0");
            }
        }

        if (isset($request->createdBy) && $request->createdByVal != "") {
            $user->whereRaw("reign_users.createdby = $request->createdByVal");
        }

        if (isset($request->profile) && $request->profileVal != "") {
            $user->whereRaw("reign_users.srvid = $request->profileVal");
        }

        if (isset($request->manager) && $request->managerVal != "") {
            $user->whereRaw("reign_users.owner = $request->managerVal");
        }

        if (isset($request->network) && $request->networkVal != "") {
            $user->whereRaw("reign_users.networkid = $request->networkVal");
        }

        if (($request->order[0]['column'] == 0) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.username", $order);
        }

        if (($request->order[0]['column'] == 4) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.expiration", $order);
        }

        if (($request->order[0]['column'] == 5) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.extended_expiration", $order);
        }
        if (($request->order[0]['column'] == 6) && isset($request->order[0]['dir'])) {
            $order = $request->order[0]['dir'];
            $user->orderBy("reign_users.owner", $order);
        }

        /* string search */
        $searchStr = $request->search['value'];
        if ($searchStr != "") {
            $user->whereRaw("(reign_users.username like '%$searchStr%' OR reign_users.firstname like '%$searchStr%' OR reign_users.lastname like '%$searchStr%' OR reign_users.mobile like '%$searchStr%' OR reign_users.mac like '%$searchStr%')");
        }

        $user->where('reign_users.status', '!=', 3);


        $data['recordsTotal'] = $user->count();
        $data['recordsFiltered'] = $user->count();

        $user->limit($request->length)->offset($request->start);
        $userData = $user->get();

//        return $userData[1]->onlineData->status;
//        $expiredDate = $userData[1]->expiration;
//        $currentDate = date('Y-m-d');
//        $expiredInThreeDays = date('Y-m-d', strtotime('-3 days', strtotime($expiredDate)));
////        return $expiredInThreeDays;
//        if ($expiredInThreeDays >= $currentDate) {
//            return $expiredDate;
//        }else{
//            return $currentDate;
//        }

        $data['draw'] = $request->draw;


        $data['data'] = array();
        $sl = 0;
        foreach ($userData as $k => $val) {
            $isNewUser = 0;

            /* only new User don't have any invoice and monthly package user */
            if ($val->userInvoice == null && $val->profiles['timebaseexp'] == 1) {
                $isNewUser = 1;

                if ($val->user_type == 2) {
                    $profileMonthStartDay = $val->custom_month_start_day;
                    $userCurrentExpiration = date($val->expiration);

                    $countMonth = 1;
                    //$newDate = strtotime('+' . $countMonth . ' month', strtotime($userCurrentExpiration));
                    $newDate = strtotime('last day of next month', strtotime($userCurrentExpiration));
                    $nextMonthYear = date('Y-m', $newDate);

                    $settingData = SoftwareSetting::select('value')->where('attribute', 'gnrl_expiration_time')->first();
                    $time = $settingData->value;

                    $activationDate = date('Y-m-d H:i:s', strtotime($nextMonthYear . '-' . $profileMonthStartDay . ' ' . $time));
                } else {
                    /* if user have custom month start day, profile month start is ignored */
                    if ($val->custom_month_start_day != null) {
                        $profileMonthStartDay = $val->custom_month_start_day;
                    } else {
                        $profileMonthStartDay = $val->profiles['month_start_day'];
                    }

                    $profileUnitMonth = $val->profiles['timeunitexp'];
                    $userCurrentExpiration = date($val->expiration);


                    //$newDate = strtotime('+' . $countMonth . ' month', strtotime($userCurrentExpiration));
                    $newDate = strtotime('last day of next month', strtotime($userCurrentExpiration));
                    $nextMonthYear = date('Y-m', $newDate);


                    $settingData = SoftwareSetting::select('value')->where('attribute', 'gnrl_expiration_time')->first();
                    $time = $settingData->value;

                    $activationDate = date('Y-m-d H:i:s', strtotime($nextMonthYear . '-' . $profileMonthStartDay . ' ' . $time));
                }

                $createdDate = $val->createdon;
                $newExpirationDate = date('Y-m-d', strtotime($activationDate));

                $activatedDayCount = date_diff(date_create($createdDate), date_create($newExpirationDate));

                $dayCountNewUser = $activatedDayCount->format("%a");
            }

            $expiredDate = $val->expiration;
            $currentDate = date('Y-m-d');
            $expiredInThreeDays = date('Y-m-d', strtotime('-3 days', strtotime($expiredDate)));
            $userActive = $val->enableuser;
            if ($currentDate > $expiredDate && $userActive == 0) {
                $color = 'gray';
            } elseif ($currentDate > $expiredDate && $userActive == 1) {
                $color = 'red';
            } elseif ($expiredInThreeDays <= $currentDate) {
                $color = 'orange';
            } elseif ($userActive == 0) {
                $color = 'gray';
            } elseif ($userActive == 1) {
                $color = 'blue';
            } else {
                $color = 'black';
            }

            $data['data'][$sl]['user_name'] = "<a class='userShow'  data-toggle='modal'
                                               data-target='#userDetails' href='$val->id'><strong style='color:" . $color . "'>" . $val->username .
                    "</strong></a><br><small class='text-info'>Added: " . date('d,M Y', strtotime($val->createdon)) . "</small>";



            $data['data'][$sl]['full_name'] = $val->firstname . ' ' . $val->lastname .
                    "<br> <small class='text-info'>Phone: " . $val->mobile . "</small>";


            $data['data'][$sl]['profile'] = ($val->user_type == 2) ? $val->ip : $val->profiles['srvname'] . "<br><small class='text-danger'>" .$val->usermac['mac'].
  "</small>";

            if ($val->isNOC == 1) {
                $networkBox = 'NOC';
            } else {
                $networkBox = 0;//$val->userNetwork['name'];
            }
            $data['data'][$sl]['networkBox'] = $networkBox;

            $data['data'][$sl]['billing_date'] = date('d,M Y H:i:s', strtotime($val->expiration));
//            $data['data'][$sl]['billing_date'] = date('d,M Y H:i:s', strtotime($val->expiration)) .
//                    "<br><small class='text-danger'>Last Online: " .
//                    date("d,M Y, H:i", strtotime($val->lastonline)) . "</small>";

            $data['data'][$sl]['expiration'] = "<small>" . date('d,M Y H:i:s', strtotime($val->extended_expiration)) . "</small>";

            $data['data'][$sl]['owner'] = $val->owners['full_name'] == "" ? "Admin" : $val->owners['full_name'];


            $costAmount = 0;
            if ($val->owners['id'] > 0) {
                $profile = AclManagerProfiles::select('cost_amount')->where(array(
                            'manager_id' => $val->owners['id'],
                            'profile_id' => $val->profiles['id'],
                        ))->first();
                $costAmount = isset($profile->cost_amount) ? $profile->cost_amount : 0;
            }

            if ($isNewUser == 1) {
                $unitPrice = round(($dayCountNewUser / 30) * $val->profiles['unitprice']);
                //$data['data'][$sl]['commission'] = $costAmount > 0 ? ($unitPrice - round(($dayCountNewUser / 30) * $costAmount)) : 0;
            } else {
                $unitPrice = $val->profiles['unitprice'];
                //$data['data'][$sl]['commission'] = $costAmount > 0 ? ($unitPrice - $costAmount) : 0;
            }

            $data['data'][$sl]['monthly_bill'] = $unitPrice + $val->additional_cost - $val->discount;


            $data['data'][$sl]['activation'] = "<a class='userActive badge badge-info' data-toggle='modal'
                                               data-target='#expirationExpand' price='$unitPrice' username='$val->username' href='$val->id'>
                                                Pay Bill
                                            </a>";
            if (Session::get('admin_assistant') == 1 && $val->owner > 0) {
                $data['data'][$sl]['activation'] = "";
            }

            $editUrl = URL::to('subscriber' . '/' . $val->id);

            if ($val->status == 0) {
                $data['data'][$sl]['action'] = "<a href='$editUrl' action='GET'>
                                                <i class='icon-pencil text-info'></i>
                                                </a>
                                                 |
                                                <a href='$editUrl' data-method='delete'
                                                data-confirm='Are you sure?  User will be delete.'>
                                                <i class='icon-trash text-danger'></i>
                                                </a>";
            } else {
                $data['data'][$sl]['action'] = "<a href='$editUrl' data-method='delete'
                                                    data-confirm='Are you sure? Do you want to restore this User?'>
                                                <i class='icon-reload text-danger'></i>
                                                </a>";
            }

            $sl++;
        }

        echo json_encode($data);
        die();
    }

这是经理模型

class AclManager extends Model
{

    protected $table = 'reign_acl_managers';
    public $timestamps = false;

    public function parent()
    {
        return $this->hasOne('App\Model\AclManager', 'id', 'parent_id');
    }

    public function manager()
    {
        return $this->hasOne('App\Model\AclGroup', 'id', 'group_id');
    }

}

我有两张表,一张是超级管理员,另一张是经理,我正在尝试获取订阅用户和他们所属的经理,有些用户属于超级管理员,但在manager 表,所以它们在表中的所有者将为 0, 所以当我试图获取所有者详细信息时,我得到了

Trying to access array offset on the value of type null

在这一行

 $data['data'][$sl]['owner'] = $val->owners['full_name'] == "" ? "Admin" : $val->owners['full_name']; 

问题是相同的代码在旧版本的 laravel 上运行良好,但在这个新版本中却不行。我认为问题出在模型中的关系上,但我不知道如何解决。

【问题讨论】:

  • 您是否停下来阅读 PHP 和 Laravel 的升级说明。您跳过了这两个版本的几个版本,因此您希望在进行跳转之前至少必须检查升级说明
  • 您尝试过什么调试问题?如果那是您自己的代码行抛出这样的错误或警告,为什么不修复您的代码?
  • 我想修复代码,但我不知道该怎么做,因为我说这种关系与旧版本很好,所以我不知道问题出在哪里跨度>
  • 这是错误 [2021-02-13 15:40:25] local.ERROR: Trying to access array offset on value of type null {"exception":"[object] (ErrorException(代码:0):尝试在 /var/www/html/easy/app/Http/Controllers/CrmController.php:281 处访问 null 类型值的数组偏移量)[stacktrace]
  • 我应该改变关系吗?经理必须属于父母或者他们必须是他们自己的父母,当我试图获取属于超级管理员的订阅者时,我收到此错误,因为他们的所有者ID将为0,并且在经理表中找不到此ID

标签: php laravel laravel-5 laravel-query-builder


【解决方案1】:

问题是$val-&gt;ownersnull

在旧版本的 PHP 中,每当您尝试对 null 变量使用 [] 运算符时,都会通过返回 null 静默处理此错误/通知。

您可以通过先使用 PHP 7.3 然后使用 PHP 7.4 运行以下代码来测试:

<?php
$a = null;
var_dump($a['a']);

PHP 7.3 将打印NULL,而 PHP 7.4 将抛出您提到的错误。

在升级您的 PHP 版本时,出现这些错误是很正常的,因为过去使用的语言有点过于宽松。

LE:条件$val-&gt;owners['full_name'] == "" 之前已经有效,因为null == "" 的计算结果为true,您可以将其替换为!isset($val-&gt;owners['full_name'])

【讨论】:

  • 感谢您的回复,我认为您是对的,那么如何避免此错误通过
  • 检查后面的编辑
猜你喜欢
  • 1970-01-01
  • 2015-04-10
  • 2020-11-04
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 2019-02-16
  • 2012-09-06
相关资源
最近更新 更多