I have model called Page and view called view.blade.php
//this is a model
public function Test()
{
return 'test';
}
//this is the template
<h1>{{$Test}}</h1>
how can I do this? please help me?
As I understood, you want to call model function inside your view? Do it like this:
{{Page::Test()}}
Edit:
If you need to use $this in your function to pass some data for your function (if that was what you were asking in comments below), you can do something like this. First define your static function:
public static function getPages()
{
return [
//some logic (get all pages)
];
}
Now, let's say this function will return multiple pages. If you want to filter them, and to display only one page on your view, you can pass the id of that view as a parameter to a next function which you will then pass to your view:
public function getSinglePage()
{
return self::getPages()[$this->id];
}
Lastly, in order to display the output of that function, use the same method as above, with new function name:
{{Page::getSinglePage()}}
Related
I need to send the same result to almost every view page, so I need to bind the variables and return with every controller.
My sample code
public function index()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.index', compact('drcategory','locations'));
}
public function contact()
{
$drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
$locations = Location::get();
return view('visitor.contact', compact('drcategory','locations'));
}
But as you see, I need to write same code over and over again. How can I write it once and include it any function whenever I need?
I thought about using a constructor, but I cannot figure out how I can implement this.
You are able to achieve this by using the View::share() function within the AppServicerProvider:
App\Providers\AppServiceProvider.php:
public function __construct()
{
use View::Share('variableName', $variableValue );
}
Then, within your controller, you call your view as normal:
public function myTestAction()
{
return view('view.name.here');
}
Now you can call your variable within the view:
<p>{{ variableName }}</p>
You can read more in the docs.
There are a few ways to implement this.
You can go with a service, a provider or, like you said, within the constructor.
I am guessing you will share this between more parts of your code, not just this controller and for such, I would do a service with static calls if the code is that short and focused.
If you are absolutely sure it is only a special case for this controller then you can do:
class YourController
{
protected $drcategory;
public function __construct()
{
$this->drcategory = DoctorCategory::orderBy('speciality', 'asc')->get();
}
// Your other functions here
}
In the end, I would still put your query under a Service or Provider and pass that to the controller instead of having it directly there. Maybe something extra to explore? :)
For this, you can use View Composer Binding feature of laravel
add this is in boot function of AppServiceProvider
View::composer('*', function ($view) {
$view->with('drcategory', DoctorCategory::orderBy('speciality', 'asc')->get());
$view->with('locations', Location::get());
}); //please import class...
when you visit on every page you can access drcategory and location object every time
and no need to send drcategory and location form every controller to view.
Edit your controller method
public function index()
{
return view('visitor.index');
}
#Sunil mentioned way View Composer Binding is the best way to achieve this.
I have setup my navigation menu from a ViewComposer (see laravel view composers: https://laravel.com/docs/5.6/views#view-composers) like this
View::composer('partials.nav', function ($view) {
$view->with('menu', Nav::all());
});
What I need is that from some controllers to setup which navigation item is active, ie "current section".
Question:
How do I send from some controllers a variable to "partials.nav" like currentNavItem?
Do I send it with the rest of the variables for returned view?
like
return view('page.blade.php",$viewVariables + $optionalVariablesForPartialsViews);
It looks spammy
Side notes:
I use laravel 5.6
Later edit
It looks Laravel 5.1 : Passing Data to View Composer might be an options. I will try and get back .
Because the $variable you want to send differs in different controller's actions yes you need to specify the $variable
return view('page.blade.php",$viewVariables,$variablesForPartialsViews);
of course you might need to set a default value for the $variable in order to avoid undefined variable error
You should handle the parameters.
for exemple:
public function compose(View $view)
{
$view->with('page', $this->getPage());
}
public function getPage()
{
$viewVariables = 2;
$optionalVariablesForPartialsViews = 1;
return $viewVariables + $optionalVariablesForPartialsViews;
}
Under your app folder make a class named yourClassNameFacade. Your class would look like this.
class yourClassNameFacade extends Facade
{
protected static function getFacadeAccessor()
{
return 'keyNameYouDecide';
}
}
Then go to the file app/Providers/AppServiceProvider.php and add to the register function
public function register()
{
$this->app->bind('keyNameYouDecide', function (){
//below your logic, in my case a call to the eloquent database model to retrieve all items.
//but you can return whatever you want and its available in your whole application.
return \App\MyEloquentClassName::all();
});
}
Then in your view or any other place you want it in your application you do this to reference it.
view is the following code:
{{ resolve('keyNameYouDecide') }}
if you want to check what is in it do this:
{{ ddd(resolve('keyNameYouDecide')) }}
anywhere else in your code you can just do:
resolve('keyNameYouDecide'))
In my project I have a controller call load and it has a fuction call search() that has a form, i want to submit this form in a child function of search() like this,,
localhost/ci/index.php/load/search
to
localhost/ci/index.php/load/search/something/
how can i do this after submission a form?
this is my contoller like
class Load extends CI_Controller {
function search() {
$this->load->view('search');
}
function something() {
$this->load->view('something');
}
}
This is not child function something()
You can define routes as per your requirements.
After search function call , you can use redirect() method, that will redirect to your route like 'base_url/controller/search/searchresult/'.
Routes.php
$route['Load/search/searchresult'] = 'Load/something';
Load Controller code :
class Load extends CI_Controller {
function search() {
$this->load->view('search');
// after form submission
redirect('Load/search/searchresult');
}
function something() {
$this->load->view('something');
}
}
This is not a child function of search function so you can call it like
localhost/ci/index.php/load/something/
Add this url to your form action and your form will be submitted to something() function
For clarity: localhost/ci/index.php/load/search/something/ does this...
Enters search() method of Load and provides something as a parameter e.g. search($param = 'something') (this is not correct syntax but just for show).
function search($term = null) {
if (is_null($term)) {
// user hasn't searched
} else {
// user searched for $term e.g. something
}
}
The only way you can achieve what you want is to either use the above somehow to your advantage knowing that /something will have to be the search parameter. Or you can use routing as another answerer suggested.
how can i pass a value from my query to the same view in CI. I am having a situation of like this:
public function index() {
$myinfo = $this->Myprofile_model->mydata();
$data['myinfo'] = $myinfo
$this->load->view('header');
$this->load->view('myprofile',$data);
$this->load->view('footer');
}
public function getResults($id) {
$fetchdata = $this->Myprofile_model->fetchresult($id);
$data['userselect'] = $fetchdata;
$this->load->view('myprofile',$data);
}
i already load my wholepage in index. and now i want to make another function to my button which is the getResults($id) function in my controller, and i want to display my another data from database to the same page. When i do the top code, my view is duplicating, because i loaded the $this->load->view('myprofile',$data); twice.
1: Create helper function and use that function on view page.
OR
If you want records for single id then merge both function in one.
If there is many ids and you want to fetch records on click for each id then you can use ajax.
$( document ).ready(function() {
$('.class_name').click(function(){
// place your code here to fetch records.
// on success you can display the result on same page
})
});
I am Not getting clearly but here is the controller to load multiple data on view:
public function index($id) {
$myinfo = $this->Myprofile_model->mydata();
$fetchdata = $this->Myprofile_model->fetchresult($id);
$this->load->view('header');
$this->load->view('myprofile',['myinfo'=>$myinfo,'fetchdata'=>$fetchdata]);
$this->load->view('footer');
}
You can use
$this->load->view('myprofile',['myinfo'=>$myinfo,'fetchdata'=>$fetchdata,'third_data'=>$third_data.. as many as you like]);
Here in your code you are passing an id to the getResults function so if you would like to load the data form this function you can do the same with this function. or pass the id to the same index function to get the result.
Is there any possibility in laravel to keep the state of the controller object?
In every example I found, the controller looks the following way:
class MyController extends Controller {
public function getView(){ //return the view }
public function postData() { //save the data }
}
What I would do is to call a service which loads specific data from my data base and return it to the view. In the example above this should be done within the getView() function. What if I need the same data in my postData() function.. Then I have to make another database call in the postData function. It is not possible to have a member variable in 'MyController' and to load the data only once for the class because of routing in laravel. When I call via routing the getView function I get another instance of MyController than I get if I call postData. Is there a possibility to call a specific function only once for the whole controller and to get access to this values from all the functions within the controller?
Is there a possibility to call a specific function only once for the
whole controller and to get access to this values from all the
functions within the controller?
As per my understanding it it not possible. Actually any function of controller is being called via routes. When your any route has been called every time the new object of controller is being created. But it has other way of round. You can use Cache. You can implement it as below:
Call to your specific function of controller.
Get the data from the database.
Store it in Cache for other functions.
In other functions check is data available in Cache? then get from Cache else call your database function to get the data.
Simply in coding as below:
Use Cache;
class MyController extends Controller {
public function getView(){
$data = call_to_database_and_returned_data();
Cache::put('data',$data,120);
return the view
}
public function postData() {
$data = null;
if(Cache::has('data')) {
$data = Cache::get('data');
} else {
$data = call_to_database_and_returned_data();
Cache::put('data',$data,120);
}
}
}
Syntax Description:
Cache::put('name_to_save_data',$your_variable_to_save,for_number_minutes);