Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 205
Mario Ene Avatar asked Mar 12 '15 10:03

Mario Ene


People also ask

Can we write PHP code in blade template Laravel?

Unlike some PHP templating engines, Blade does not restrict you from using plain PHP code in your templates. In fact, all Blade templates are compiled into plain PHP code and cached until they are modified, meaning Blade adds essentially zero overhead to your application.

What is the advantage of Laravel blade template?

The main advantage of using the blade template is that we can create the master template, which can be extended by other files.


4 Answers

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.

like image 155
sleepless Avatar answered Oct 20 '22 04:10

sleepless


I solve the problem. So simple. Syntax error.

  • App\Product
  • App\Service

enter image description here

But I also want to know how to pass a function with parameters to view....

like image 37
Mario Ene Avatar answered Oct 20 '22 02:10

Mario Ene


want to use model in view as:

{{ Product::find($id) }}

you can use in view:

<?php
$tmp = \App\Product::find($id);
?>
{{ $tmp->name }}

Hope this will help you

like image 12
Hưng Trịnh Avatar answered Oct 20 '22 02:10

Hưng Trịnh


In new version of Laravel you can use "Service Injection".

https://laravel.com/docs/5.8/blade#service-injection

/resources/views/main.blade.php

@inject('project', 'App\Project')

<h1>{{ $project->get_title() }}</h1>
like image 9
Mowshon Avatar answered Oct 20 '22 02:10

Mowshon