How to use a View Composer variable in the controller - laravel

I am trying to use the View Composer $view_name variable in same controller but it is giving me error.
It is only available to all views, but not for controllers
I want to use that variable in the same controller.
My controller:
public function boot()
{
view()->composer('*', function($view){
$view_name = str_replace('.', '-', $view->getName());
view()->share('view_name', $view_name);
});
$page_name=substr(strrchr(url()->current(),"/"),1);
if($page_name==request()->server('HTTP_HOST')) {
$keywords=keyword::where('page_name','index')->where('active','1')->first();
} else {
$keywords=keyword::where('page_name',$page_name)->where('active','1')->first();
}
}

You can create a Middleware to populate a Configuration variable, configuration is always available from all the framework.
public function handle()
{
config(['myCustomConfig.email' => 'me#example.com']);
}
On your controller
$data = config('myCustomConfig.email');
On your view file
<div>{{ config('myCustomConfig.email') }} </div>

Related

Laravel collection display and short issue

Hello guys!
I have a a little problem with collections. I have never worked with these. I would like to display a collection at my welcome blade but there is a problem. My collection is not in the contrroller, the collection's place is in the App/Repositories/xyz.php and in a function. How can i pass this function to the controller and after show it at the welcome blade??
App/repositories/xyz.php
public function getcars(): Collection
{
return collect([
new Car(...)
)];
controller
public function __invoke(): View
{
return view('welcome', ['cars' => collect([
new Car() ------> I would like to put datas from xyz.php repo here
new Car()
new Car()
....
And welcome.blade file where i would like to display
<div class="car-list">
<h2>{{ $title }}</h2>
#foreach($cars as $car)
<x-car :car="$car" />
#endforeach
</div>
You could do that in many ways:
Creating new instance
use App\repositories\Xyz;
public function __invoke(): View
{
$repo = new Xyz();
return view('welcome')->with('cars', $repo->getcars());
}
Pulling your class from the container
use App\repositories\Xyz;
public function __invoke(): View
{
$repo = app(Xyz::class);
return view('welcome')->with('cars', $repo->getcars());
}
Using dependency injection to resolve it from container
use App\repositories\Xyz;
protected Xyz $repo;
public function construct(Xyz $xyz): View
{
$this->repo = $xyz;
}
public function __invoke(): View
{
return view('welcome')->with('cars', $this->repo->getcars());
}
I believe from your Controller file, you can create an object property of your Repository via __construct() method like this:
protected MyRepository $myRepository;
public function __construct(MyRepository $myRepository)
{
$this->myRepository = $myRepository;
}
Then, you can call $this->myRepository's method from there, for example like getting records, etc. Then you can pass the result to your view.

How to transfer data to parent template without code duplication,

I have main layout which contains a header, nav, footer and ofc many blade templates with
inherited from him. My problem: i have categories which i need to connect in my navbar, also in many children templates, maybe it can be done somehow globally without duplication code.
It's my 'HomeContoller' return index template, but if i return my categories with $categories my main layout can't see this variable
public function index()
{
$posts = Post::paginate(10);
$popularPosts = Post::orderByViews()->take(6)->get();
return view('front.index', ['posts' => $posts, 'popularPosts' => $popularPosts]);
}
Now i return to layout.blade my $categories by this method.
#php
$categories = App\Category::all();
#endphp
For this particular case I would suggest the View Composer - especially, if you scroll a bit down on that page you'll see Attaching A Composer To Multiple Views - you could use:
View::composer('*', function ($view) {
$view->with('categories', App\Category::all());
});
You can register it under any of the existing providers for instance AppServiceProvider under the boot method:
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
public function boot(): void
{
View::composer('*', function ($view) {
$view->with('categories', App\Category::all());
});
}
}

Pass variables to multiple view in laravel

I want to pass a variable to multiple view bu when i use share method in View. Its says the share method isn't find on View.
How you say i use it and i try the composer either but no matter how i try it can't work could you give me simple example of this action
My controller categorycontroller.php
public function site(){
$data = array();
$data['subcategories'] = SubCategory::all();
$data['categories'] = Category::all();
return view('template.sitemap',compact("data"));
}
My route web.php
Route::get('/404.html', function () {
return view('template/404');
})->name('404.html');
Route::get('404.html','CategoryController#site')->name('404');
Route::get('/sitemap.html', function () {
return view('template/sitemap');
})->name('sitemap.html');
Route::get('sitemap.html','CategoryController#site')->name('sitemap');
what do you suggest?
You can make a variable accessible in multiple views using one of these methods for example:
AppServiceProvider ( reference: https://laravel.com/docs/5.6/providers ) with ViewComposer ( reference: https://laravel.com/docs/master/views#view-composers )
You'll need to add to your ServiceProvider boot() method something similar to this:
public function boot()
{
View::share('variable_name', 'some_value_here');
}
Or inside a controller:
public function __construct() {
$something = 'just a test';
View::share('something', $something);
}

Laravel 5 - How to passing request data from route to controller

I am new in laravel,
How to passed request data into controller ? Just like happen on view ?
Route::get('/kelihatan', function (Request $request) {
return view( 'pages' , [ 'page' => 'index' , '_request' => $request->all() ] );
});
How to passing request data to controller before passed into view or model ? Just like this ??
Route::get( '/{page}', 'UserController#show' );
Mention the path in route first depending upon the type of request i.e. Get or Post
Route::get('/invite/{code}', 'MyController#get_my_action');
Route::post('/invite/{code}', 'MyController#post_my_action');
Then in controller named as MyController create a function like
public function get_my_action($code){
//your code goes here
}
or
public function post_my_action(Request $request, $code)
{
//your code goes here
}
With that route:
Route::get('/{page}', 'UserController#show');
In the controller you can do that:
public function show()
{
$page = request()->route('page');
or that:
public function show($page)
or that:
public function show(Request $request, $page)
Try this:
Routes.php
Route::get( '/{page}', 'UserController#show' );
UserController.php
public function show($page) {
dd($page);
}
Inside your controller define your show function as below:
function show(Request $request)
{
echo $request['page'];//or whatever data you want to pass
}
///add follwoing line before you define controller
use Illuminate\Http\Request;

Laravel: master view or controller always called

How can I set a "default" view and/or controller so it will be always called no matter the route?
I have tried with:
(routes.php)
Route::get('/*', function(){
return View::make('master');
});
and:
Route::get('*', function(){
return View::make('master');
});
But gives me NotFoundHttpException;
Related question: Is there a better way to do this than setting it in the routes.php?
Thanks!
Laravel have something called Controller Layouts, then in your controller you can create a variable named $layout and set it to a master or default view:
class Controller extends BaseController
{
protected $layout = 'layout.master';
public function getIndex() {
$data[];
$this->layout->content = View::make('myview', $data);
}
Now in the layout.master view you can access the $content variable.

Resources