代码之家  ›  专栏  ›  技术社区  ›  Avijit Biswas

在laravel中,如何使用foreach循环?

  •  0
  • Avijit Biswas  · 技术社区  · 6 年前

    当我使用此代码时:

    Route::get('/user/{id}/posts', function ($id){
       $post = User::find($id)->postst;
       return $post;
    });
    

    输出为:

    [
        {
            "id":1,
            "user_id":1,
            "title":"Eloquent Basic Insert",
            "content":"By eloquent we can easily insert a data and it is awesome",
            "created_at":"2018-05-15 14:45:34",
            "updated_at":"2018-05-15 14:45:34",
            "deleted_at":null
        },
        {
            "id":2,
            "user_id":1,
            "title":"Add with create",
            "content":"This might be fail",
            "created_at":"2018-05-15 14:47:59",
            "updated_at":"2018-05-15 14:47:59",
            "deleted_at":null
        }
    ]
    

    但当我使用foreach循环时,它只显示一个数组

     Route::get('/user/{id}/posts', function ($id){
       $post = User::find($id)->postst;
       foreach ($post as $post){
           return $post->title. '<br>';
       }
    });
    

    此代码的输出为:

    雄辩的基本插入

    如何在浏览器上显示阵列的所有标题?我的代码有什么问题?

    3 回复  |  直到 6 年前
        1
  •  5
  •   Fanie Void    6 年前

    您所做的是在第一个循环中返回标题。 你需要把你的 return 从你的 foreach :

    Route::get('/user/{id}/posts', function ($id){
       $post = User::find($id)->postst;
       $titles = "";
       foreach ($post as $post){
           $titles .= $post->title. '<br>';
       }
       return $titles;
    });
    
        2
  •  2
  •   ali    6 年前

    只要用echo替换返回的单词,就可以了

     Route::get('/user/{id}/posts', function ($id){
     $post = User::find($id)->postst;
      foreach ($post as $post){
       echo $post->title. '<br>';
      }
    });
    
        3
  •  1
  •   martincarlin87    6 年前

    只是为了做一些不同的事情,你应该能够做如下事情:

    Route::get('/user/{id}/posts', function ($id){
        $posts = User::with('posts')->find($id)->posts;
        return $posts->pluck('title');
    });