how to use model function from view ? - laravel 5.4
11,262
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)}}
Author by
Masum
Updated on June 13, 2022Comments
-
Masum almost 2 years
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
-
Masum about 7 yearsmy target is building some query into model function & get it from blade file. so what is the right process? how to you do it?
-
Sagar Arora about 7 years@Masum welcome and if solution is working for you so you may vote up to help others.
-
Masum about 7 yearsI want to vote you. but I don't know where is voting option?