环绕Laravel Collection

时间:2017-11-16 05:27:24

标签: php laravel

public function showJobCategoryContent($id){

     $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

     // Imagine here i got 5 data

     foreach ($jobsInfoById as $jobInfoById) {
          return  $current=$jobInfoById->created_at;
        //$trialExpires []= $current->addDays(30);
     }
}

如果我循环它,它只显示1数据。如何使用array符号然后它会显示1数据。

1 个答案:

答案 0 :(得分:1)

如果您想获得所有created_at日期的数组,则不需要循环。

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    return $jobsInfoById->pluck('created_at');
}

使用循环:

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $dates = [];
    foreach ($jobsInfoById as $jobInfoById) {
        $dates[] = $current = $jobInfoById->created_at;
    }

    return $dates;
}

如果想在每个日期添加30天:

public function showJobCategoryContent($id)
{

    $jobsInfoById = DB::table('jobs')->where('category_id', '=', $id)->where('published', '=', 1)->paginate(3);

    $jobsInfoById = $jobsInfoById->map(function ($job) {
        return $job->created_at->addDays(30);
    });

    return $jobsInfoById->pluck('created_at');
}

了解Laravel系列以及它们如何有用:link