Convert laravel object to array

前端 未结 14 900
名媛妹妹
名媛妹妹 2020-12-13 19:33

Laravel output:

Array
(
    [0] = stdClass Object
    (
        [ID] = 5

    )

    [1] = stdClass Object
    (
        [ID] = 4

    )

)

14条回答
  •  情书的邮戳
    2020-12-13 20:18

    UPDATE since version 5.4 of Laravel it is no longer possible.

    You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:

    DB::setFetchMode(PDO::FETCH_ASSOC);
    
    // then
    DB::table(..)->get(); // array of arrays instead of objects
    
    // of course to revert the fetch mode you need to set it again
    DB::setFetchMode(PDO::FETCH_CLASS);
    

    For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section

    Event::listen(StatementPrepared::class, function ($event) {
        $event->statement->setFetchMode(...);
    });
    

提交回复
热议问题