Search code examples
phplaravellaravel-5.8rules

Update Error - Trying to get property 'id' of non-object in Laravel 5.8


I am using Laravel-5.8 for a Web Application. I am trying to apply Rules and Requests in Laravel Validation. I have these codes:

rules

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)
        ],            
    ];
}

Controller

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');  
    }
}

view blade

 <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>

When I clicked on the save button to update, I got this error:

Trying to get property 'id' of non-object

Then, in the rules this code is highlighted:

Rule::unique('org_companies', 'organization_code')->ignore($this->route('company')->id)

How do I get it resolved?

Thank you.


Solution

  • Change

    public function update(UpdateCompanyRequest $request, $id)

    to

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

    With your current route $id is just an ID and company doesn't exist.

    Your rules are looking for it to be an object.

    If you put OrgCompany $company Laravel will automatically find it for you.

    This also allows you to simplify your entire update method.

    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');  
        }
    }
    

    You can also update the signature of your edit method to automatically inject the OrgCompany in the same way.

    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);
    }