如何修复它调用成员函数diffForHumans()在laravel 5.3中的字符串
问题描述:
为什么当我使用查询生成器而不是函数diffForHumans()时出现错误,但是如果我使用偶尔ROM但没有错误,如何克服它? (如何解决它)谢谢如何修复它调用成员函数diffForHumans()在laravel 5.3中的字符串
这是ArticlesController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Article;
use Carbon\Carbon;
use Auth;
use DB;
class ArticlesController extends Controller
{
public function index()
{
$articles =DB::table('articles')->get();
$articles = ['articles'=>$articles];
return view('articles.index',$articles);
}
}
这是模型Article.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
//
use SoftDeletes ;
protected $fillable = [
'user_id','content','live','post_on',
];
protected $dates =[
'post_on','deleted_at','created_at','updated_at',
];
public function setLiveAttribute($value)
{
$this->attributes['live'] = (boolean)($value);
}
public function getShortContentAttribute()
{
return substr($this->content,0,random_int(60,150))."...";
}
public function setPostOnAttribute($value)
{
$this->attributes['post_on'] = Carbon::parse($value);
}
public function setCreatedAtAttribute($value)
{
$this->attributes['post_on'] = Carbon::parse($value);
}
}
,这是我的代码,我该如何修复它? 谢谢
答
我注意到有两件事情在你的代码,
- 没有必要投
created_at
和updated_at
到日期,他们已经铸造而成,是Carbon
- 情况下,你可以使用物业
$casts
投简单attributs像live
- 无需添加增变了
post_on
日期,因为你把它添加到$dates
- 还你
created_at
设置赋值函数,而不是post_on
,您使用SetCreatedAttribute
代替setPostOnAttribute
- 而不是
substr($this->content,0,random_int(60,150))."..."
可以使用Laravel的str_limit
助手功能,也改变random_int
到rand
=>int rand (int $min , int $max)
查询建设者返回dates
作为字符串,你需要解析之前使用它们,否则你会得到像这样的错误PHP error: Call to a member function on string
,只是这样做︰
\Carbon\Carbon::parse(\DB::table('articles')->first()->post_on)->diffForHumans()
你可以让你的模型简单,像这样:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Article extends Model
{
use SoftDeletes ;
protected $fillable = [
'user_id','content','live','post_on',
];
protected $dates = [
'post_on','deleted_at'
];
protected $casts = [
'live' => 'boolean'
];
public function getShortContentAttribute()
{
return str_limit($this->content, rand(60,150));
}
}
也可以简化你index
方法是这样的:
public function index()
{
$articles = DB::table('articles')->get();
return view('articles.index', compact('articles'));
}
答
默认情况下雄辩回报date/time
领域为Carbon
例如,在查询生成器别。因此,如果您想在查询构建器的返回属性上使用Carbon
,则必须使用Carbon::parse()
方法包装该属性。
例如,我可以在口才结果使用Carbon
的方法toCookieString()
之一如
echo App\User::find(1)->created_at->toCookieString();
这将给这样Thursday, 10-Aug-2017 17:59:53 UTC
的响应。但是,如果使用查询构建器,而不是如
echo DB::table('users')->find(1)->created_at->toCookieString();
那么它会在字符串给出错误
调用一个成员函数toCookieString()
要在这里使用Carbon
我用Carbon
的parse()
方法包装财产。
echo Carbon\Carbon::parse(DB::table('users')->find(1)->created_at)->toCookieString();
这会给人想要的结果作为雄辩。
ouh谢谢你,这是很好的建议,当我尝试你的建议,它的作品 –