Search code examples
laravel-bladelaravel-5

Laravel 5 call a model function in a blade view


I want to build a blade view from 3 tables:

  • "inputs_details" - fields: article_type (values: 'p' for product,'s' for service), article_id, ....
  • "products" - fields: id, name
  • "services" - fields: id, name

enter image description here

But, in browser, I have the error: "Class 'Product' not found".

Is there a solution to pass to the view this function (to find the name of the product or the service based on article_type and article_id)?

I was trying also with join query, but I couldn't put so many conditions in a single join query .. where article_type is "p", then join with "products" table ... or .... where article_type is "s", then join with "services" table.


Solution

  • Related to the question in your answer:

    You have multiple options to achieve this that are way better:

    Let's assume you have a model which you pass to the view:

    $model = Model::find(1);
    View::make('view')->withModel($model);
    

    Now in your Model you could have a function:

    public function someFunction() {
        // do something
    }
    

    In your view you could call that function directly:

    {{$model->someFunction()}}
    

    This is nice if you want to do something with the model (the dataset).

    If not you can still make a static function in the model:

    public static function someStaticFunction($var1, $var2) {
        // do something
    }
    

    And then:

    {{App\Model::someStaticFunction($yourVar1,$yourVar2)}}
    

    Hope it helps.