Search code examples
laravellaravel-4models

Calling model functions in a view in Laravel 4?


I am using a function to write a query, and I am trying to return the variable the function returns and use it in a view. In my model:

Fan.php

public function sample_query() {
        $count = User::where('fbid', '=', 421930)->count();

        return $count;

    }

In the view I am simply trying to call it with:

@sample_query();

This is not working. I am new to this type of thing, and I suppose I don't know how to access the data pulled by queries in the model in the view. Please let me know if there is a better way, or why this isn't working. Thank you!


Solution

  • For your question it seems View Composer will solve your problem

    View composers are callbacks or class methods that are called when a view is created. If you have data that you want bound to a given view each time that view is created throughout your application, a view composer can organize that code into a single location. Therefore, view composers may function like "view models" or "presenters".

    View::composer('profile', function($view)
    {
        $view->with('count', User::count());
    });
    

    for more info read this