mertindervish
mertindervish

Reputation: 301

Laravel merging Eloquent result and array

I'm trying to merge eloquent result and array because I need to add all possible filters that user can use for this model. If anyone have any other idea how to make it I really would be very thankful. Here is an example code:

<?php

class School extends Eloquent {
    protected $table = 'schools';

    public function listSchoolsEndUser()
    {
        $schools_data = new School;

        $schools_data = $schools_data->paginate(12);

        $filters = array( 
            'filters' => array(
                'name' => 'Neshtoto'
            )
        );

        $schools_data = (object) array_merge(get_object_vars($schools_data), $filters);

        echo '<pre>';
        print_r( $schools_data );
        exit;

        return $schools_data;
    }

And the result is very interesting:

stdClass Object
(
    [filters] => Array
        (
            [name] => Neshtoto
        )

)

Upvotes: 0

Views: 1832

Answers (1)

lukasgeiter
lukasgeiter

Reputation: 152860

If you just want to send both, filters and the school_data back in a JSON response you can do it this way:

return Response::json(array(
   'filters' => array(
        'name' => 'Neshtoto'
    ),
    'data' => $school_data->toArray()
));

Or if you want to use array_merge:

$school_data = array_merge($filters, array('data' => $school_data->toArray()));
return $school_data;

Edit

If you are just injecting the data into a view I see no reason at all to merge the data, just pass two variables!

return View::make('view', array('schools' => $school_data, 'filters' => $filters));

(Here $filters would obviously only be array('name' => 'Neshtoto') and not the full thing including 'filters' => ...)

Upvotes: 1

Related Questions