小编Sol*_*ine的帖子

Laravel集合-对象的返回数组

因此,我尝试使用以下代码使用Laravel集合返回对象数组:

/**
 * View a user's chat rooms.
 *
 * return \Illuminate\Http\Response|\Laravel\Lumen\Http\ResponseFactory\
 */
public function viewChatRooms()
{
    $user = Auth::user(); // @var User $user
    $username = $user->username;

    $rooms = Room::with('messages')->get()
                    ->filter(function ($val) use ($username){
                        foreach ($val->users as $user) {
                            if($user === $username){
                                return $val;
                            }
                        }
    });

    return response(['rooms' => $rooms]);
}
Run Code Online (Sandbox Code Playgroud)

响应不返回对象数组,而是返回以下内容:

{
    "rooms": {
        "0": {...},
        "3": {...}
    }
}
Run Code Online (Sandbox Code Playgroud)

这是期望的结果:

{
    "rooms": [
        {...},
        {...}
    ]
}
Run Code Online (Sandbox Code Playgroud)

有点受此困扰,有人可以引导我朝正确的方向发展吗?

arrays collections rest json laravel

3
推荐指数
1
解决办法
99
查看次数

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::withTimestamps()

I am trying to create a relationship in laravel with timestamps. I have this app that allows customers to request a job to a marketplace. When a freelancer on the marketplace finds a job their interested in they propose to complete the job and a new row is queried into the freelancer table.

Here is the code creating the relation:

$marketplace->freelancers()->create([
   'request_id' => $id,
   'user_id' => $user->id
]);
Run Code Online (Sandbox Code Playgroud)

Here is the Marketplace Model relationship code:

    /**
     * A request may …
Run Code Online (Sandbox Code Playgroud)

php laravel eloquent

1
推荐指数
1
解决办法
1万
查看次数

标签 统计

laravel ×2

arrays ×1

collections ×1

eloquent ×1

json ×1

php ×1

rest ×1