Reputation: 407
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 please
Upvotes: 5
Views: 12236
Reputation: 1773
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)}}
Upvotes: 10