Laravel Subscribers with Query Builder

Trying to get Accessors in the Query Builder but failing " " Undefined property: stdClass::$shorcontent

//controller
        public function index(){
        $articles = DB::table('articles')->paginate(10);
        return view('articles.index', ['articles' => $articles], compact('articles'));
    }

      

Here is the Model file with Accessors

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'user_id', 'content', 'live', 'post_on'
    ];

    protected $guarded = ['id'];

    public function getShortContentAttribute()
    {

        return substr($this->content,0, random_int(60, 150));
    }
}

      

Here is the view

//article/index.blade.php View
<td class="col-md-6">{{ $article->shortcontent }} </td>

      

The same code works when I use redoquent instead of the query builder like

public function index()
{
    $articles = Article::paginate(10);
    return view('articles.index', ['articles' => $articles], compact('articles'));
}

      

+3


source to share


2 answers


This answer is delayed and you may have found your solution but hope it helps someone else.

The short answer is, the DB facade doesn't have access to the accessories and mutators defined in the model. Only objects created by model instances can have access to accessories and mutators.

I believe the problem here is that using the database phase element only creates the Query Builder without referencing the accessors or mutators you have set in the article model. The DB phase only processes the database using the query builder and returns an article model independent object.

However, the model facade will build the query builder, but the instance of the created object will have access to the accessories and mutators, since it is an instance of an object of the Model class.

Check out this answer: Difference between DB and Model Facade



Accessors are available only after trying to get an attribute value from a model instance, for example:

$article = Article::find(1);
$shortContent = $article->short_content;

      

This is explained further here

Thus, if you want to access the accessories, you will have to use the model facade, i.e. Article::paginate(10)

...

+1


source


You are missing the short_content attribute. Just add this



namespace App;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{

protected $fillable = [
    'user_id', 'content', 'live', 'post_on'
];
protected $appends = ['short_content'];
protected $guarded = ['id'];

public function getShortContentAttribute()
{

return substr($this->content,0, random_int(60, 150));

}

}

      

+1


source







All Articles