Jump to content

Laravel 5.4 "format" model output

Go to solution Solved by leodaniel,

I am not familiar with blade because I always use twig as my templating engine. You may be searching for a filter right?

Anyway, I am not completely sure what you are asking.

 

If I understand it right:

/* Gather your model */

$users = App\User::all();

foreach($users as $user){
   /*Do Your Stuff here*/
}

 

If it's just displaying your results use a filter in blade (I think they exist in blade). If you want to format your result from the DB for usage in you app, you can use a Model Access Mutator. Check the Laravel Documentation for that.

If you just want to format say like the name (column: name) you can use an access Mutator on your Model

/* in App\User */

public function getNameAttribute($name){
    return 'Name: '.$name;
}

/* now when you access the name */
$user = App\User::find(1);

echo user->name;
/* will output: Name: YourUserName */

 

Hello, so I'm quite new to laravel and I have just made my page display stuff from the database. It's displaying all my server pool sizes in bytes, how can I reformat them? (when I used normal php I used a function I still have to take the value and format it)

 

I have tryed to search how to use functions in views but people said thats not the way to do it.

 

How do you do this?

Back-end developer, electronics "hacker"

Link to comment
https://linustechtips.com/topic/785000-laravel-54-format-model-output/
Share on other sites

Link to post
Share on other sites

I am not familiar with blade because I always use twig as my templating engine. You may be searching for a filter right?

Anyway, I am not completely sure what you are asking.

 

If I understand it right:

/* Gather your model */

$users = App\User::all();

foreach($users as $user){
   /*Do Your Stuff here*/
}

 

If it's just displaying your results use a filter in blade (I think they exist in blade). If you want to format your result from the DB for usage in you app, you can use a Model Access Mutator. Check the Laravel Documentation for that.

If you just want to format say like the name (column: name) you can use an access Mutator on your Model

/* in App\User */

public function getNameAttribute($name){
    return 'Name: '.$name;
}

/* now when you access the name */
$user = App\User::find(1);

echo user->name;
/* will output: Name: YourUserName */

 

Business Management Student @ University St. Gallen (Switzerland)

HomeServer: i7 4930k - GTX 1070ti - ASUS Rampage IV Gene - 32Gb Ram

Laptop: MacBook Pro Retina 15" 2018

Operating Systems (Virtualised using VMware): Windows Pro 10, Cent OS 7

Occupation: Software Engineer

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×