Skip to content
Advertisement

Error Call to a member function attach() on null

I want to create tag system but I have an error “Error Call to a member function attach() on null “. Look at my code

Relationship:

Job.php

public function services(){
        $this->belongsToMany('AppJobervices');
    }

Jobservices.php

public function jobs(){
    $this->belongsToMany('AppJob');
}

And I created pivot table

Schema::create('job_jobservices', function (Blueprint $table) {
    $table->id();
    $table->integer('job_id');
    $table->integer('jobservices_id');
    $table->timestamps();
});

Controller and view

Into controller I tryed attached my services. Look at this.

$job = Job::create([
           'title'          => $request->title,
           'description'     => $request->description,
           //...
        ]);
$job->services()->attach($request->services);

I think, $request->services is good becouse If i try dd($request->services), it display me this but just in case I’ll show you my view

<select class="js-example-responsive col-12" multiple="multiple" name="services[]">
    @foreach($services as $service)
        <option value={{ $service->id }}>{{ $service->name }}</option>
    @endforeach
</select>
    @error('services')
        <div class="alert alert-danger" role="alert">
        {{ $message}}
        </div>
    @enderror

I don’t know why but it display me an error

Error Call to a member function attach() on null

Do you know what is wrong?

Advertisement

Answer

You should return with the relationship.

public function services()
{
    return $this->belongsToMany('AppJobervices');
}
public function jobs()
{
    return $this->belongsToMany('AppJob');
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement