Ошибка обновления - Попытка получить свойство 'id' необъекта в Laravel 5.8 - PullRequest
1 голос
/ 06 февраля 2020

Я использую Laravel -5,8 для веб-приложения. Я пытаюсь применить правила и запросы при проверке Laravel. У меня есть эти коды:

правила

public function rules()
{
    return [
        'organization_code' => [
            'required',
            'string',
            'min:2',
            'max:20',               
            Rule::unique('org_companies', 'organization_code')->ignore($this->route('company')->id)
        ],   
        'organization_name' => [
            'required',
            'string',
            'min:3',
            'max:100',               
            Rule::unique('org_companies', 'organization_name')->ignore($this->route('company')->id)
        ], 
        'website' => [
            'nullable',
            'url',
            'max:100',               
            Rule::unique('org_companies', 'website')->ignore($this->route('company')->id)
        ],             
        'org_image'             => 'nullable|image|mimes:jpeg,bmp,png,gif|max:2048',
        'total_employees'       => 'nullable|numeric|digits_between:0,10',
        'registration_number' => [
            'nullable',
            'string',
            'max:50',               
            Rule::unique('org_companies', 'registration_number')->ignore($this->route('company')->id)
        ], 
        'phone_number' => [
            'nullable',
            'numeric',
            'phone:NG',               
            Rule::unique('org_companies', 'phone_number')->ignore($this->route('company')->id)
        ],            
        'secondary_phone' => [
            'nullable',
            'numeric',
            'phone:NG',               
            Rule::unique('org_companies', 'secondary_phone')->ignore($this->route('company')->id)
        ],    
        'email' => [
            'nullable',
            'email',
            'max:80',               
            Rule::unique('org_companies', 'email')->ignore($this->route('company')->id)
        ],   
        'secondary_email' => [
            'nullable',
            'email',
            'max:80',               
            Rule::unique('org_companies', 'secondary_email')->ignore($this->route('company')->id)
        ],            
    ];
}

контроллер

public function edit($id)
{       
    $company = OrgCompany::where('id', $id)->first();   
    $countries = ConfigCountries::all();
    return view('organization.companies.edit')->with('company', $company)->with('countries', $countries);
}

public function update(UpdateCompanyRequest $request, $id)
{
    try {    
            $orgStartDate = Carbon::parse($request->org_start_date);
            $company = OrgCompany::find($id);
            $company->organization_code     = $request->organization_code;
            $company->organization_name     = $request->organization_name;
            $company->website               = $request->website;
            $company->org_description       = $request->org_description;
            $company->total_employees       = $request->total_employees;
            $company->registration_number   = $request->registration_number;
            $company->org_start_date        = $orgStartDate;
            $company->phone_number          = $request->phone_number;
            $company->secondary_phone       = $request->secondary_phone;
            $company->email                 = $request->email;
            $company->secondary_email       = $request->secondary_email;
            $company->country_id            = $request->country_id;  

             if ($request->org_image != "") {
                 $org_image = $request->file('org_image');
                 $new_name = rand() . '.' . $org_image->getClientOriginalExtension();
                 $org_image->move(public_path('storage/companies/image'), $new_name);
                 $company->org_image = $new_name;
            }

        $company->save();
            Session::flash('success', 'Company is updated successfully');
            return redirect()->route('organization.companies.index');                

    } catch (Exception $exception) {
            Session::flash('danger', 'Action failed!');
            return redirect()->route('organization.companies.index');  
    }
}

просмотр лезвия

 <div class="card-body">
       <form  action="{{route('organization.companies.update', ['id'=>$company->id])}}" method="post" class="form-horizontal" enctype="multipart/form-data">
        {{ csrf_field() }}
        <input name="_method" type="hidden" value="PUT"> 

                    <span style="color:blue;"><h4 class="box-title"><b>Company Information</b></h4></span>
                    <hr class="m-t-0 m-b-40">  
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group row">
                                        <label class="control-label text-right col-md-3"> Company Code<span style="color:red;">*</span></label>
                                        <div class="col-md-9 controls">
                                            <input  type="text" name="organization_code" placeholder="Enter company code here" class="form-control" value="{{old('organization_code',$company->organization_code)}}">
                                        </div>
                                    </div>
                                </div>
                                <!--/span-->
                                <div class="col-md-6">
                                    <div class="form-group row">
                                        <label class="control-label text-right col-md-3"> Company Name<span style="color:red;">*</span></label>
                                        <div class="col-md-9 controls">
                                            <input  type="text" name="organization_name" placeholder="Enter company name here" class="form-control" value="{{old('organization_name',$company->organization_name)}}">
                                        </div>
                                    </div>
                                </div>
                                <!--/span-->
                            </div>

                        <div class="form-actions">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="row">
                                        <div class="col-md-offset-3 col-md-9">
                &nbsp;&nbsp;&nbsp;<button type="submit" class="btn btn-primary">{{ trans('global.save') }}</button>
                <button type="button" onclick="window.location.href='{{route('organization.companies.index')}}'" class="btn btn-default">Cancel</button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
        </form>
</div>

Когда я нажал кнопку сохранения, чтобы обновить, я получил эту ошибку:

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

Затем в правилах выделяется этот код:

Rule :: unique ('org_companies', 'organization_code') -> игнорировать ($ this-> route ('company') -> id)

Как мне решить эту проблему?

Спасибо.

1 Ответ

0 голосов
/ 06 февраля 2020

Изменить

public function update(UpdateCompanyRequest $request, $id)

на

public function update(UpdateCompanyRequest $request, OrgCompany $company)

При вашем текущем маршруте $id это просто идентификатор, а company не существует

Ваши правила ищут, чтобы это был объект.

Если вы введете OrgCompany $company Laravel, он автоматически найдет его для вас.

Это также позволяет упростить весь метод обновления.

public function update(UpdateCompanyRequest $request, OrgCompany $company)
{
    try {    
        $orgStartDate = Carbon::parse($request->org_start_date);

// this will already be assigned and is unnecessary -> 
        // $company = OrgCompany::find($id);

        // your request object already contains a validated, clean array.
        $validated = $request->validated();
        $company->fill($validated);
        $company->org_start_date        = $orgStartDate;

        if ($request->org_image != "") {
            $org_image = $request->file('org_image');
            $new_name = rand() . '.' . $org_image->getClientOriginalExtension();
            $org_image->move(public_path('storage/companies/image'), $new_name);
            $company->org_image = $new_name;
        }

        $company->save();
        Session::flash('success', 'Company is updated successfully');
        return redirect()->route('organization.companies.index');                

    } catch (Exception $exception) {
        Session::flash('danger', 'Action failed!');
        return redirect()->route('organization.companies.index');  
    }
}

Вы можете также обновите подпись вашего edit метода, чтобы автоматически внедрить OrgCompany таким же образом.

public function edit(OrgCompany $company)
{       
// already exists now -> $company = OrgCompany::where('id', $id)->first();   
    $countries = ConfigCountries::all();
    return view('organization.companies.edit')->with('company', $company)->with('countries', $countries);
}
...