我的laravel控制器中有以下编辑方法:
public function editArtilce(Request $request) {
/* Get the last part of the URI */
$explodedUrl = explode('/', $request->url());
$urlSlug = array_pop($explodedUrl);
$article = DB::table('admin')->where('slug', 'LIKE', '%' . $urlSlug . '%')->get();
return $article;
}
现在我正在做:
return $article;
我在浏览器中收到以下输出:
[{"id":10,"title":"This is a title","description":"This is a description","keywords":"Keyword1 , Keyword2 , Keyword3 , Keyword4 , Keyword5 , Keyword6","blog_content":"<p>I am a lovely burger<\/p>","tag":"gulp","filePath":"2017-02-23-21-54-30-blog-post-image.jpg","slug":"this-is-a-title","created_at":"2017-02-23 21:54:30","updated_at":"2017-02-23 21:54:30"},{"id":11,"title":"This is a title","description":"This is a description","keywords":"Keyword1 , Keyword2 , Keyword3 , Keyword4 , Keyword5 , Keyword6","blog_content":"<p>I am a lovely burger<\/p>","tag":"gulp","filePath":"2017-02-23-21-56-29-blog-post-image.jpg","slug":"this-is-a-title","created_at":"2017-02-23 21:56:29","updated_at":"2017-02-23 21:56:29"}]
但是当我尝试像这样访问这个数组的属性时:
return $article->title
我收到以下错误:
为什么我无法在laravel中访问数组的属性?我究竟做错了什么 ?
答案 0 :(得分:4)
而不是$article->title
尝试:
$article[0]->title;
因为$ article是Std类对象,其结构如下:
array(
{ } // 0th index
{ } // 1st index
)
要动态使用foreach()
,请执行以下操作:
foreach($article as $data)
{
$data->id;
$data->title;
}
答案 1 :(得分:1)
您可以使用first()
代替get()
直接获取对象。
$article = DB::table('admin')
->where('slug', 'LIKE', '%' . $urlSlug . '%')
->first();
并且在尝试访问它的属性之前必须检查它是否为null。 $article->title
或任何你想要的东西。