Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use model function from view ? - laravel 5.4

i made a function into model class which is

public function scopetest($query)
    {
 return $query->pluck('name');
    }
  }

and my controller code is

 public function index()
     {
     $books = Book::all();

     return view('welcome',compact('books'));

       }

to get the test() function result I wrote my view file

@foreach($books as $book)

 {{$book->test()}}

@endforeach

but problem is when i visit this page it will show 'name' field value 3 times. why it show 3 times? how to call model function from view? & what is the right process? kindly help pleaseview result

like image 614
Masum Avatar asked Feb 21 '17 03:02

Masum


People also ask

What does {{ }} mean in Laravel?

By default, Blade {{ }} statements are automatically sent through PHP's htmlentities function to prevent XSS attacks. If you do not want your data to be escaped, you may use the following syntax: Hello, {!! $name !!}. Follow this answer to receive notifications.

How can we call controller method from view in Laravel?

$varbl = App::make("ControllerName")->FunctionName($params); to call a controller function from a my balde template(view page).

Which function returns a view in Laravel?

Views may also be returned using the View facade: use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.


1 Answers

There are many ways to call a model function in the view.

Method 1:

Pass Some Modal to view in your controller like :

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

In modal create a some function:

  public function someFunction() {
   // do something
  }

In view you can call this function directly as:

{{$model->someFunction()}}

Method 2 or other way:

You can make a static function in the model like:

public static function someStaticFunction($par1, $par2) {
   // do what you need
}

And in your view you can model function directly as:

{{App\Model::someStaticFunction($par1,$par2)}}
like image 80
Sagar Arora Avatar answered Sep 28 '22 11:09

Sagar Arora