Search code examples
phplaravelselectorm

Laravel, how to get selected, db fields


Have a model, from controller, I need access this Model db fields.

Code in controller:

$crud -> get() -> getAttributes();
//$crud->attributesToArray()
print_r($crud);

I was able to get entire table fields, but I need only fields, which are selected. Need dynamically show table with selected fields only, which can change during run time.


Solution

  • Assume you have a query:

    $query = Crud::select('id as Id', 'name as Name', 'something')
                 ->selectRaw('CONCAT(id, "-", name) as Serial')
                 ->get();
    

    Without knowing what the query is, to get a table that looks like this

    Id Name something Serial
    1 A lorem 1-A
    .. .... ......... ......

    You need to use the Builder instance (before calling ->get()

    $query = Crud::select('id as Id', 'name as Name', 'something')
                 ->selectRaw('CONCAT(id, "-", name) as Serial');
    
    $results = $query->get();
    
    dump($query->getQuery()->columns);
    /*
    [
        'id as Id',
        'name as Name',
        'something',
        Illuminate\Database\Query\Expression
    ]
    */
    
    dump(array_map(function ($column) {
        return $column instanceof Illuminate\Database\Query\Expression
            ? Str::afterLast($column->getValue(), 'as ')
            : Str::afterLast($column, 'as ');
    }, $query->getQuery()->columns));
    /*
    [
        'Id',
        'Name',
        'something',
        'Serial'
    ]
    */
    

    So you could that to a view.

    $query = Crud::select('id as Id', 'name as Name', 'something')
                 ->selectRaw('CONCAT(id, "-", name) as Serial')
                 ->get();
    
    $columns = array_map(function ($column) {
        return $column instanceof Illuminate\Database\Query\Expression
            ? Str::afterLast($column->getValue(), 'as ')
            : Str::afterLast($column, 'as ');
    }, $query->getQuery()->columns);
    
    $results = $query->get();
    
    return view('view', compact('columns', 'results'));
    

    And then in your view

    <table>
      <thead>
        <tr>
          @foreach ($columns as $column)
            <th>{{ $column }}</th>
          @endforeach
        </tr>
      </thead>
      <tbody>
        @foreach ($results as $result)
          <tr>
            @foreach ($columns as $column)
              <td>{{ $result->{$column} }}</td>
            @endforeach
          </tr>
        @endforeach
      </tbody>
    </table>