Ad

How To Get Specific Columns In Laravel Eloquent With Pagination?

I use this table schema:

Schema::create('forms', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name', 255)->default('');
    $table->text('html')->nullable();
    $table->text('json')->nullable();

    $table->timestamps();
    $table->softDeletes();
});

This is the model:

class Form extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name',
        'html',
        'json'
    ];

    protected $hidden = ['created_at', 'updated_at', 'deleted_at'];
}

And in the controller I want to show a list of all items of model but only the id and name fileds. Now I use this, but it show all not hidden fields:

public function index() {
    return Form::->paginate(100);
}

This function is only for the list of forms names. But here is the second one for show a form datas for modify:

public function show(string $id) {
    $item = Form::findOrFail($id);

    return response()->json($item);
}

Of course this last one function needs to be show all fields (id, name, html and json too).

Is there any best practice to show only fields what I needed in the index() function using with paginate()?

Ad

Answer

If i am not wrong then hopefully you can do it something like this for getting specific columns along with pagination:

return Form::paginate(100,['id','name',.....]);
Ad
source: stackoverflow.com
Ad