lundi 13 novembre 2017

Laravel Many To Many Polymorphic Relationship not working for me

I am really stuck on Laravel many to many Polymorphic Relationship and it is 2nd day. Please help me and advise what I am doing wrong.

I have users who can follow status updates on different type applications. Different type of applications in system are company registration, name registration, tax registration etc.

My table looks like

    Schema::create('follows', function (Blueprint $table) {
        $table->unsignedInteger('user_id');
        $table->unsignedInteger('followable_id');
        $table->string('followable_type');
    });

My Company class looks like

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    /**
     * Get all of the followers.
     */
    public function followers()
    {
        return $this->morphToMany('App\User', 'followable', 'follows');
    }
}

My User class looks like

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Get all of the followers for the company application.
     */
    public function followingsOfCompany()
    {
        return $this->morphedByMany('App\Company', 'followable', 'follows');
    }

    /**
     * Get all of the followers for the tax application.
     */
    public function followingsOfTax()
    {
        return $this->morphedByMany('App\Tax', 'followable', 'follows');
    }
}

Now if I save a relationship it saves fine. I save using this command:

    $company->followers()->save($request->user());
    return Response::make(['success'=> ['follow' => 1]], 200);

I can see a record inserted in the follows table with row like

2   20  App\Company

I am getting stuck when I want to fetch logged in users' following companies. It always get into recursion or memory exhausted error (indication of recursion).

I have tried

    $company = $this->companyRepository->findById($id);
    $follower = $company->followers()->where('user_id', '=', $request->user()->id);

I have also tried this

    $follower = \DB::table('follows')
                ->where('followable_id',   $id)
                ->where('followable_type', App\Company::class)
                ->where('user_id',         $request->user()->id);

Please help. Thanks



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2hoOUnt
via IFTTT

Aucun commentaire:

Enregistrer un commentaire