如何修复它在 Laravel 5.3 中的字符串上调用成员函数 diffForHumans()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45620330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:29:14  来源:igfitidea点击:

How to fix it Call to a member function diffForHumans() on string in laravel 5.3

phplaravellaravel-5.3mutators

提问by Raka Hikmah

Why when I use query builder instead there is an error on the function diffForHumans (), but if I use ELoquent ROM but no error there is a way to overcome it? (How can i fix it) thank you

为什么当我使用查询构建器时,函数 diffForHumans () 会出现错误,但是如果我使用 ELoquent ROM 但没有错误,那么有办法克服它吗?(我该如何解决)谢谢

diffForHumans()

diffForHumans()

this is ArticlesController.php

这是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);
    }
}

this is model Article.php

这是模型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);
    }



}

and that is my code, how i can fix it? thank you

那是我的代码,我该如何解决?谢谢你

回答by yoeunes

i noticed a couple of things in you're code,

我注意到你的代码中有几件事,

  • no need to cast created_atand updated_atto dates, they are already casted and are instances of Carbon
  • you can use the property $caststo cast simple attributs like live
  • no need to add a mutator for post_ondate because you add it to $dates
  • also you set a mutator on created_atinstead of post_on, you use SetCreatedAttributeinstead of setPostOnAttribute
  • instead of substr($this->content,0,random_int(60,150))."..."you can use str_limithelper function of Laravel, also change random_intto rand=> int rand ( int $min , int $max )
  • 不需要投射created_atupdated_at日期,它们已经被投射并且是Carbon
  • 您可以使用该属性$casts来转换简单的属性,例如live
  • 无需为post_on日期添加修改器,因为您将其添加到$dates
  • 你还设置了一个 mutator oncreated_at而不是post_on,你使用SetCreatedAttribute而不是setPostOnAttribute
  • 而不是substr($this->content,0,random_int(60,150))."..."你可以使用str_limitLaravel 的辅助函数,也random_int改为rand=>int rand ( int $min , int $max )

the query builder return datesas strings, you need to parse before using them or you will get an error like this one PHP error: Call to a member function on string, just do it like this :

查询构建器dates以字符串形式返回,您需要在使用它们之前进行解析,否则您会收到这样的错误PHP error: Call to a member function on string,只需这样做:

\Carbon\Carbon::parse(\DB::table('articles')->first()->post_on)->diffForHumans()

you can make your model simpler like this :

您可以像这样使模型更简单:

<?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));
    }
}

also you can simplify you indexmethod like this :

你也可以index像这样简化你的方法:

public function index()
{
    $articles = DB::table('articles')->get();

    return view('articles.index', compact('articles'));
}

回答by Sazzadur Rahman

By default eloquent returns date/timefields as a Carboninstance, where query builder don't. So if you want to use Carbonon query builder's returned property, you have to wrap the property with Carbon::parse()method.

默认情况下,eloquent 将date/time字段作为Carbon实例返回,而查询构建器则不会。因此,如果要Carbon在查询构建器的返回属性上使用,则必须使用Carbon::parse()方法包装该属性。

For example, I can use one of Carbon's method toCookieString()on a eloquent result such as

例如,我可以对雄辩的结果使用其中的一个Carbon方法toCookieString(),例如

echo App\User::find(1)->created_at->toCookieString();

which will give a response like this Thursday, 10-Aug-2017 17:59:53 UTC. But if I use query builder instead such as

这将给出这样的响应Thursday, 10-Aug-2017 17:59:53 UTC。但是,如果我使用查询构建器,例如

echo DB::table('users')->find(1)->created_at->toCookieString();

then it will give an error

那么它会给出一个错误

Call to a member function toCookieString() on string

在字符串上调用成员函数 toCookieString()

To use Carbonin here I have wrap the property with Carbon's parse()method.

为了Carbon在这里使用,我用Carbon'sparse()方法包装了属性。

echo Carbon\Carbon::parse(DB::table('users')->find(1)->created_at)->toCookieString();

This will give the desired result as eloquent.

这将给出所需的结果作为雄辩。