At first, I had just one view file that contained all codes for showing a page. but now I decided to split code sections.
So, as I learned, I would make a child view, write my section codes to that file and now return the child view in Laravel Controller. So now passed data goes to child view and in parent view, I have no access to them until I call yield function. But in parent view I need some of that data before calling yield. So How can I pass data which would be available both in parent view and sub view?
I've already tried passing data in extends() as a second parameter but this way
data will be available just when I call yield.
Controller :
class walletsController extends Controller
{
function name(){
return view("subview", ["somedata" => $somedata])
}
}
subview blade file :
#extends('parentview',["somedata" => $somedata] )
#section('wallet')
// some codes here
#endsection
parentview blade file :
// some codes
#yield('wallet')
when I try to use data that being passed in extends() before calling yield it gives me a garbage value.
In this case I would recommend using Laravel's View Composers.
View Composers allow you to pass variables to any view the you want (id doesn't matter if it's a parent or child view).
In your case, you will pass a variable that will be used only on parentview, right?
The code in the AppServiceProvider (boot() method) would be like this:
view()->composer(['parentview', 'folder.another-view-that-you-want'], function ($view) {
$someVar = 'some var value';
$view->with(['someVar' => $someVar]);
});
You can also pass a variable to every single view, using *:
view()->composer('*', function ($view) {
$someVar = 'some var value';
$view->with(['someVar' => $someVar]);
});
Of course, you can read further in the docs: https://laravel.com/docs/5.8/views#view-composers
Related
I want to create a global variable and pass this into all view, so I can get this variable into all blade template
basically, my need is to pass my general setting controller value into my common blade view like header.blade.php
Thanks in advance
For that you will need to add some code in the App->Providers->AppServiceProvider.php like this:
public function boot()
{
view()->composer('*',function($view){
$settings = Settings::firstOrNew(['id' => '1']);
$view->with('settings', $settings );
});
}
According to Laravel documentation you can use view composer:
https://laravel.com/docs/5.8/views#view-composers
for using this feature in app > AppServiceProvider and in boot method you can use this approach for passing parameter to specific view If you have data that you want to be bound to a view each time that view is rendered. this approach meet your need perfectly. for example you want to pass a parameter named userName to header.
View()->composer('header', function ($view){
$userName= "username"
$view->with(['userName'=>$userName]);
});
I'm using RESTful controller and passing variables (using forms) works just fine here.
Now for some reason I need to use simple link, created with action() and dedicated route for #create action.
My view creates few similar links with different parameters:
<a href="{!! action('\App\Http\Controllers\Admin\Franch\Category\SubCategoryController#create', array('mainCategoryName' => $mainCategoryName)) !!}">
It works, because I can see this in URL:
/create?mainCategoryName=some_sample_name
But the route doesn't pass variables to the #create action OR controller doesn't recieve it for somereason:
Route::get('admin/franch/sub_categories/create', ['uses' => 'Admin\Franch\Category\SubCategoryController#create');
I wonder how can I pass variables from views to specific controllers, using GET and POST methods?
And this is my #create controller:
public function create($mainCategoryName = false)
{
dd($mainCategoryName);
....
Which is always gives false.
Well You can create a function on the link and in that function user Ajax
$.ajax({
type: "POST",//Or Get
url: url,
data: {"var_name":variable},
success: success,
dataType: dataType
});
Now you can send you variables in the data. and then you can get value of the variable in your controller by:
Input::get('var_name');
It would be much better if you make all your "calculations" in the controller and pass a resulting value to the view like so
class SomeController() extends Controller
{
public function getView():View
{
$mainCategoryName = "fix";
$formUrl = action('\App\Http\Controllers\Admin\Franch\Category\SubCategoryController#create', array('mainCategoryName' => $mainCategoryName));
return view('view.show', compact('formUrl'));
}
...
Your mistake is in keeping meaningful data in the view, when the view should only have processed values:
<a href="{!! $formUrl !!}">
And if you really want to go "nuts", you can create a class that would generate HTML using a blade-view and the controller data and then you can execute this class in the controller to have your "partial" ready to be incorporated in a view as HTML. But not the other way round. Keep the calculations out of your views.
Is it possible to insert a view using javascript?
I wish to perform an ajax call, get the data, then insert a view in to a page and provide the data from the ajax call to that view?
Is this possible?
Yes you can use the render method on a view. Like so;
$view = View::make('your.view')->render();
And then return the html (which is the output) from your controller method by returning the data stored in $view.
If you need to add any data to the view just add the second parameter to the view make.
alternatively you can do this,
set the route for pages you want to call.
e.g.,
Route::get('callajax','PagesController#showAjax');
and then in PagesController#showAjax you return the view.
e.g.,
public function showAjax()
{
return View::make('ajaxpages');
}
and then in ajax call you code this
$.ajax({
url:'callajax',
});
The issue is what I say in the title. The parameter of the index selected in the first dropdown box is not sent to the controller. Therefore the controller cannot pass any value to the model etc. If I harcode saying $pais_id = 1 and send that to the Model it works, so this means, the issue is in the controller not getting it from the jquery.
VIEW
<script type="text/javascript">
//jquery code for source list
$(document).ready(function(){
$('#country').change(function() {
if ($(this).val()!='') {
$("#source").load("/CI-3/controllers/control_form.php",{pais_id: $(this).val()});
}
});
}); // end of country and city function
</script>
The problem must be there because I don't visualize the process:
Jquery detects the changing in the select dropdown list and fetches the selected id. Alright, but what happens next ? it sends it to the controller, yes, and? the controller forwards it to the model, the model does a sql search and returns an array back to the controller and the controller forwards it to the view, but, how does #source in the line above get affected after all that?, so it will not modify itself
$source['source'] = $this->model_form->get_source($pais_id);
should be
$data['source'] = $this->model_form->get_source($pais_id);
in controller. third parameter in view is if it's returned or echo'd. all values are passed in the 2nd parameter as an array.
I load the multiple views from the controller, in order to display a page.
$this->load->view('header');
$this->load->view('content', $data);
$this->load->view('sidebar1', $data1);
$this->load->view('sidebar2', $data2);
$this->load->view('footer');
However I think its not a clean approach. Can it be improved by creating a single main view, for example "views/page" which includes all above views in it. Then instead of calling all the above views, i can call only main view, for example:
$this->load->view('main');
In this case how can I pass the variables for the content, sidebar1 and sidebar2?
Thanks
Pass the data for each view as an array to your main view, then pass those arrays on as your main view loads the subviews.
$data['sidebar1_data'] = array($one => 'one');
$data['sidebar2_data'] = array($two => 'two');
Then in your main view:
$this->load->view('sidebar1', $sidebar1_data);
$this->load->view('sidebar2', $sidebar2_data);
Within my projects, I have a tendency to do:
$this->load->vars($data);
$this->load->view('template_name');
Where my template loads in other views within itself.
The CodeIgniter documentation states the following for the method $this->load->vars():
"This function takes an associative array as input and generates variables using the PHP extract function. This function produces the same result as using the second parameter of the $this->load->view() function above. The reason you might want to use this function independently is if you would like to set some global variables in the constructor of your controller and have them become available in any view file loaded from any function. You can have multiple calls to this function. The data get cached and merged into one array for conversion to variables. "
Using $this->load->vars($data) helps in not having to load data for each view within my template.
use like this
$newData = array_merge($data, $data1, $data2);
$this->load->view('main', $newData);
If there are no key with same name in $data, $data1, $data2 then, it will work without modifying any of view for variable name change.