0
votes

I have two tables, "teachers" & "teacher_certificates" which keep teachers certificates.

I'm trying to save teachers certificates by eloquent relationship like here https://laravel.com/docs/5.7/eloquent-relationships#the-create-method

Teacher Model:

namespace App\Models\Teachers;

use App\User;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Database\Eloquent\SoftDeletes;

  class Teacher extends Model
  {
  public function Certificates()
     {
        return $this->hasMany(TeacherCertificates::class, 'teacher_id');
    }
  }
}

TeacherCertificate Model:

namespace App\Models\Teachers;

use App\User;
use Illuminate\Database\Eloquent\Model;

class TeacherCertificates extends Model
{
    protected $table='teacher_certificates';
    protected $fillable=['teacher_id','certificate'];
    protected $touches=[Teacher::class];
    public $timestamps=false;

}

And the controller:

namespace App\Http\Controllers\Dashboard;

use App\Http\Controllers\Controller;
use App\Models\Teachers\Experiences;
use App\Models\Teachers\Skills;
use App\Models\Teachers\Teacher;
use App\Models\Teachers\TeacherCertificates;
use App\User;
use Illuminate\Http\Request;
use App\Http\Requests\TeacherCreateRequest;
use Illuminate\Support\Facades\DB;    

class TeacherController extends Controller
    {

        public function store(TeacherCreateRequest $request)
        {
            DB::transaction(function () use ($request) {
                $data = $request->all();
                $user = User::create($data);
                $data[ 'user_id']=$user->id;

                $teacher = Teacher::create($data);



                //certificates
                $certificates=array_map(
                    function ($certificate) use ($teacher) {
                        return ['teacher_id' => $teacher->id,
                            'certificate' => $certificate];
                    }, explode('\n', $request->certifications));


                $teacher->Certificates()->createMany($certificates);
            }
        }
    }

I'm getting this error:

BadMethodCallException
Method Illuminate\Database\Query\Builder::App\Models\Teachers\Teacher does not exist.
1
Add your controller use statements to question. Ex: use App\Example;Manpreet
@Manpreet AddedSoheil Rahmat
You say u have certificates table but you are using: protected $table='teacher_certificates'; Some misinformation in question.Manpreet
What is the namespace of Teacher model ? Copy head of file hereMahdi Younesi
@MahdiYounesi I Added the namespace and usage of Teacher modelSoheil Rahmat

1 Answers

3
votes

The problem resides in definition of $touches property of Teacher class, Which should be name of a method in your class.

For more info read Laravel's Doc