Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kgp43's avatar
Level 2

How to access functions within a model, in a view

Hi,

How can I access a function within a model? (in a view) I got this small function in my model, and I would like to access it in my view.

namespace App;

use Illuminate\Database\Eloquent\Model;

class Convert extends Model
{
    protected $fillable = [
        'unit_type',
        'unit_num',
    ];
    
    public function pressure() {
        
        # Set base values
        # Base: 1 bar
        $base['bar'] = 1;
        $base['pa'] = 100000;
        $base['mpa'] = 0.1;
        $base['nmm2'] = 0.1;
        $base['psi'] = 14.5038;
        $base['ksi'] = 0.0145037738007;
        
        return $base;
        
    }
}

Added this to my view, but it does not work:

{{ App\Convert::pressure() }}
0 likes
5 replies
Tray2's avatar
{{ $model->pressure() }}

Should work if you send the model collection to the view.

kgp43's avatar
Level 2

Hmm... seems like the function I got does not belong to the model in the first place, since its not used to interact with my database. Models are only used for DB stuff, right?

Maybe I should make a helper.php file and add it to that instead.

Tray2's avatar

Depends on what you are trying to do. If you are trying to convert data returned from the database then you can have it in your model.

Snapey's avatar
Snapey
Best Answer
Level 122

If you want to use it like this

{{ App\Convert::pressure() }}

Then you need to declare it a static function

    static function pressure() {
        
        # Set base values
        # Base: 1 bar
        $base['bar'] = 1;
        $base['pa'] = 100000;
        $base['mpa'] = 0.1;
        $base['nmm2'] = 0.1;
        $base['psi'] = 14.5038;
        $base['ksi'] = 0.0145037738007;
        
        return $base;

    }

Otherwise you need a Convert model instance passed to the view

Please or to participate in this conversation.