Remove return json relationship from Laravel’s Datatables package

Asked

Viewed 104 times

0

I have the following code snippet using Standard and the Datatables package

$products = Product::with('enterprise')
                   ->select(['id', 'enterprise_id', 'name'])
                   ->whereIn('enterprise_id', [1, 2]);

return Datatables::of($products)
       ->editColumn('enterprise_id', function($product){
           return $product->enterprise->name;
       })
       ->make();

And I have as return the following json:

[
    "12",
    "Nome empresa",
    "Nome do produto",
    {
        "id": 1,
        "client_id": 1,
        "name": "Nome empresa",
        "created_at": "2016-08-25 16:38:24",
        "updated_at": "2016-08-25 16:38:24"
    }
]

How do I remove that section of json where the relationship appears? What I’d like to take is this part of json:

{
    "id": 1,
    "client_id": 1,
    "name": "Nome empresa",
    "created_at": "2016-08-25 16:38:24",
    "updated_at": "2016-08-25 16:38:24"
}

I’ve tried using the resource removeColumn unsuccessfully. I have also tried to add a new column nome_empresa and removing the column enterprise_id but also without success.

The result you expected to receive in json would be:

[
    "12",
    "Nome empresa",
    "Nome do produto",
]
  • Is the first json the return of the Datatables function? has how you instead of returning the function’s direct, assign its result to a variable $return, convert this variable to array with json_decode remove the element [3] from that vector and return $return? if you find valid I write a reply with more details.

  • I managed to remove. I will answer my own question to anyone who has the same question.

1 answer

0

To solve this problem just give a removeColumn in the name of the relationship.

In my case on the model Product had the following method to make the relationship:

public function enterprise(){
    return $this->belongsTo('App\Models\Enterprise');
}

So I removed the column as follows:

->removeColumn('enterprise')

Okay, that solves the problem and now json came as needed.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.