Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

carcleo's avatar

How to remove the Pivot of query result?

i have this query

$classroom = Classroom::with('students:id,name')->find($classroom);

its give-me the result

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => Adriel dos Santos Azevedo
            [pivot] => Array
                (
                    [classroom_id] => 1
                    [student_id] => 1
                )

        )

but i need of this resut without the Pivot

[pivot] => Array
                (
                    [classroom_id] => 1
                    [student_id] => 1
                )

For this i make in model Student

protected $hidden = ['pivot'];

But i should like solved it at query and no in Model.

Anythink like

$classroom = Classroom::with('students:id,name')->without('students.Pivot')->find($classroom);

How to do it?

I so get it doing

$classroom = Classroom::with('students:id,name'))->find($classroom);
    $students = [];
    foreach($classroom->students->makeHidden("pivot") as $student) {
        $students[] = $student->toArray();
    };
    echo '<pre>';
    print_r($students);

But note that is the PHP tthat be working,not the Eloquent Query

0 likes
3 replies
tykus's avatar

If you are ultimately intending to return the result as a JSON response, then I would suggest checking out Eloquent API Resources rather than returning the array representation of the Model. This will give you more control of the structure and data in the Response

2 likes
Devio's avatar

You could use ->map()

return Classroom::query()
		->with('students')
		->where('id', $id)
		->get()
		->map( fn($classroom) => [
				'class name' => $class->name
				'students' => $class->students->map( fn($student) => [
						'id'=>$student->id,
						'name'=>$student->name
				])
		]);

Although I don't think this is what you should be doing. Best you rethink your approach.

Please or to participate in this conversation.