Laravel Property [title] does not exist on the Eloquent builder instance

后端 未结 4 1115
悲哀的现实
悲哀的现实 2021-01-12 10:27

I am getting an error while trying to display data from the database.This problem occurred by other people who have created posts on this website. but they have a foreach lo

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-12 10:58

    Eager Loading Relationships(THIS WILL WORK JUST UNDERSTAND THIS)

    DataTables support searching and sorting of eager loaded relationships when using Eloquent. this example will show you how to setup a eager loading search using Eloquent Engine.

    To enable search, we need to eager load the relationship we intend to use using Laravel's User::with('posts') api.

    use DataTables;
    
    Route::get('user-data', function() {
    $model = App\User::with('posts');
    
    return DataTables::eloquent($model)
                ->addColumn('posts', function (User $user) {
                    return $user->posts->map(function($post) {
                        return str_limit($post->title, 30, '...');
                    })->implode('
    '); }) ->toJson(); });

    To trigger search on posts relationship, we need to specify the relation.column_name as the name attribute in our javascript appropriately.

    
    

    Looking at {data: 'posts', name: 'posts.title'},:

    data: posts represents the data key (data.posts) that we are going to display on our table. name: posts.title represents the User model relationship (posts) and the column we are going to perform our search (title).

提交回复
热议问题