Sometimes we need to change model value before showing it to user in browser . With help of accessors we can achieve this desired result.
Suppose if we need to break fullname into two parts which is being retrieved from users table and want to show that in view where visitor will be able to see firstname and lastname. We can achieve this result using following snippet.
Step 01: In Model
public function getNameAttribute() { $name = explode(" ", $this->name); $lastname = array_pop($name); $firstName = implode(" ", $name); return ['firstName' => $firstName, 'lastName' => $lastName ]; }
Above, full name from database is broken into firstname and lastname and then it is returned to view as an array.
Step 02: In view
<table class=" table table-bordered table-striped table-hover"> <thead> <tr> <th> FirstName </th> <th> LastName </th> </tr> </thead> <tbody> <tr > <td> {{ $user->name['firstName'] }} </td> <td> {{ $user->name['lastName'] }} </td> </tr> </tbody> </table>