How to merge Laravel objects in controller

后端 未结 5 369
栀梦
栀梦 2021-02-01 04:49

I have a controller where I want to combine data from multiple tables with parallel structures. What I want to end up with in the end is one object I can return from the contro

相关标签:
5条回答
  • 2021-02-01 05:27

    Nowadays you can use

    $new_collection = $collection->merge($other_collection).

    This works in Laravel 4 and seems to handle both arrays and collections.

    0 讨论(0)
  • 2021-02-01 05:31

    You could simply use array_merge(firstObject,secondObject) function.

    $obj = array_merge($mc, $sm);
    return $obj;
    
    0 讨论(0)
  • 2021-02-01 05:43

    We can use collection as below

    $admins = User::where('type', '=', 'admin')->get();
    
    $authors = User::where('type', '=', 'author')->get();
    
    $admin_author_collection = $admins->merge($authors);
    

    Also, Please refer the various collection methods to below link

    http://laravel.com/api/4.2/Illuminate/Database/Eloquent/Collection.html

    0 讨论(0)
  • 2021-02-01 05:48

    What you can do here is merge the arrays of the two query result and then use the Response with json output like shown below.

    $array = array_merge($mc->toArray(), $sm->toArray());
    return Response::json($array);
    
    0 讨论(0)
  • 2021-02-01 05:51
    Route::get('test', function(){
        $rank = Rank::get();
        $policy = Policy::get();
        $obj = (object)array_merge_recursive((array)$rank , (array)$policy);
        var_dump($obj);
    });
    

    This is working for me. Instead of array_merge use array_merge_recursive().

    0 讨论(0)
提交回复
热议问题