Laravel admin backend column usage

Created At: 2021-10-15 18:38:13 Updated At: 2022-04-09 13:44:38

Column attribute

The column object's setAttributes() method is used to add HTML attributes to each row of the current column. A useful scene is to add style to the current column.

$grid->column('name')->setAttributes(['style' => 'color:blue;']);

After setting the attributes you can see the change

So with setAttributes you can set any style. Do remember setAttributes takes array of styles inside square brackets.

The style() method is based on the setAttributes() method, adding styles directly, such as limiting the width of the column:

$grid->column('description', __('Description'))->style('max-width:100px;word-break:break-all;');

This before adding the style method. After adding the style method you get like below

The line breaks down. So with style() method you can control the widh, height of a row and column. Style() method takes a lot of css properties.

Display callback

The display() method is used to process the value of the current column via the passed callback function:

$grid->column('email')->display(function ($value) {

    return "<span style='color:blue'>$value</span>";

});

You can return html from this function. 

The above display function takes the email value from the database and change the color of the email address to blue. And it returns html. See the changes in the picture

With this display() function you can do anything inside the callback(or clousre). Because it's a function inside, so you can do any data operation inside it. 

For example if you want to combine two column together and create a new column(which did not exist in the database).

$grid->column('name');

$grid->column('last_name');

// `full_name` field that does not exist
$grid->column('full_name')->display(function () {
    return $this->name . ' ' . $this->last_name;
});

If my database, full_name column does not exist. But inside display function we can combine name and last_name field and create a new column for our record on the backend.

You see it combined the columns(name and last_name from the database) and displayed 

Style column

If you want to style the column for example it's width and height then you can display() callback function on a column with style() attribute.

$grid->column('content', __('Content'))->style('min-width: 300px;max-width:500px;word-break:break-all;white-space: normal;')->display(function ($val){
     return substr($val,0,100);
});

Without the style() function, this column would take space as much it's content's width. But now with this we limit it to take only the first 100 character.

It just returns PHP function substr().

You can apply this width to any of your column.

Comment

Add Reviews