Get Laravel 5 controller name in view - laravel-5

Our old website CSS was set up so that the body tag had an id of the controller name and a class of the action name, using Zend Framework 1. Now we're switching to Laravel 5. I found a way to get the action name through the Route class, but can't find a method for the controller name. I don't see anything in the Laravel docs like this. Any ideas?
This is how you do with action. You inject the Route class, and then call:
$route->getActionName().
I'm looking for something similar for controllers. I've checked the entire route class and found nothing.

If your layout is a Blade template, you could create a view composer that injects those variables into your layout. In app/Providers/AppServiceProvider.php add something like this:
public function boot()
{
app('view')->composer('layouts.master', function ($view) {
$action = app('request')->route()->getAction();
$controller = class_basename($action['controller']);
list($controller, $action) = explode('#', $controller);
$view->with(compact('controller', 'action'));
});
}
You will then have two variables available in your layout template: $controller and $action.

I use a simple solution. You can test and use it in everywhere, also in your views:
{{ dd(request()->route()->getAction()) }}

I will simply use as bellow
$request->route()->getActionMethod()

To get something like PostController try following ...
preg_match('/([a-z]*)#/i', $request->route()->getActionName(), $matches);
$controllerName = $matches[1];
$matches[1] includes the first group while $matches[0] includes everything matched. So also the # which isn't desired.

use this
strtok(substr(strrchr($request->route()->getActionName(), '\\'), 1), '#')

To add to Martin Bean answer, using Route::view in your routes will cause the list function to throw an Undefined offset error when this code runs;
list($controller, $action) = explode('#', $controller);
Instead use this, which assigns null to $action if not present
list($controller, $action) = array_pad(explode('#', $controller), 2, null);

You can use this to just simply display in the title like "Customer - My Site" (laravel 9)
{{ str_replace('Controller', '', strtok(substr(strrchr(request()->route()->getActionName(), '\\'), 1), '#'))}} - {{ config('app.name') }}

You can add this (tested with Laravel v7+)
<?php
use Illuminate\Support\Facades\Route;
echo Route::getCurrentRoute()->getActionMethod();
?>
or
You can use helper function
<?php echo request()->route()->getActionMethod(); ?>
for example :-
Route::get('test', [\App\Http\Controllers\ExampleController::class, 'exampleTest'])->name('testExample');
Now If I request {app_url}/test then it will return exampleTest

Related

What it is the solution for this problem Laravel Action

Action App\Http\Controllers\AdminController#dbTanger not defined.
And this is My AdminController
public function dbTanger() {
$data = Db::table('ressos')
->where('secteur','Services')
->get();
return view('backend.layouts.admin.typeFilterTanger',compact('data','pagi'));
}
And this is the view
<div class="Filter">
<p>Filter Using Ville</p>
Tanger-Asilah
</div>
so if anyone can help me please
and thank you all
Since Laravel 9, the default Controller namespace has not been included in the RouteServiceProvider so you need to be explicit about where to locate controllers (or add the default namespace to your RouteServiceProvider).
What you can do is the following:
{{ action('\App\Http\Controllers\AdminController#dbTanger') }}
However, I would recommend using the route helper in conjunction with named routes as this is easier to manage should files change or move location in the future.
Route::get('/admin/dbTanger', [AdminController::class, 'dbTanger'])->name('admin.dbTanger');
Then use it as follows:
{{ route('admin.dbTanger') }}
The outcome is the same, just easier to manage and maintain long-term.
That error would mean you didn't define a route to this action so there is nothing in the route collection to be found for that action.
Define a route for this action and you would be able to use that action helper to create a URL to a route that uses this action.

Laravel: how to create a rendered view from a string instead of a blade file?

I've some html with {{ soimething }} placeholders in a table.
I would like to get the rendered view from this custom html.
I would like to avoid to manually do string replace.
Is it possible?
Note : I seen suggested questions but I ended finding a more concise way to reach my goal. So I post an answer to this question. Please keep this open.
You can use Blade Facade.
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Blade;
public function __invoke()
{
$name='Peter Pan';
return Blade::render("
<h1> Hello {$name} </h1>
",['name'=>$name]);
}
Found
We can use \Illuminate\View\Compilers\BladeCompiler::render($string, $data)
Where
$string is the text to parse, for example
Hi {{$username}}
$data is the same associate array we could normally pass down to view() helper, for example [ 'username' => $this->email ]
I was missing this from the official doc: https://laravel.com/docs/9.x/blade#rendering-inline-blade-templates
So we can also use
use Illuminate\Support\Facades\Blade;
Blade::render($string, $data)

How to call helper function in laravel 5.5

I am using laravel 5.5. I have created a helper.php in app\Http. I am calling this helper in my blade file by using
{!! Helper::functionName() !!}
this is working fine. but i want to hold this helper result in a variable like
{!! $Result=Helper::functionName() !!}
But currently this is printing this result. How to solve this. please help.
So that i can make any if condition on this $Result.
In my helpers.php
namespace App\Http\Helpers;
class Helper
{
public static function functionName()
{
return "mydata";
}
}
There is no point to use helper like this. You should run the helper in controller and pass calculated data into view. In most cases you shouldn't set any variables in views or make any calculations - those should be passed from controller to view and view should only use them.
In this case, you can use "<?php ?>".
So result:
<?php $Result=Helper::functionName(); ?>
may be this is not possible because in laravel "{{}}" this means echo "" so by default it will print the value. return the value from helper function and use in your blade

Laravel Pagination links not including other GET parameters

I am using Eloquent together with Laravel 4's Pagination class.
Problem: When there are some GET parameters in the URL, eg: http://site.example/users?gender=female&body=hot, the pagination links produced only contain the page parameter and nothing else.
Blade Template
{{ $users->link() }}
There's a ->append() function for this, but when we don't know how many of the GET parameters are there, how can we use append() to include the other GET parameters in the paginated links without a whole chunk of if code messing up our blade template?
I think you should use this code in Laravel version 5+.
Also this will work not only with parameter page but also with any other parameter(s):
$users->appends(request()->input())->links();
Personally, I try to avoid using Facades as much as I can. Using global helper functions is less code and much elegant.
UPDATE:
Do not use Input Facade as it is deprecated in Laravel v6+
EDIT: Connor's comment with Mehdi's answer are required to make this work. Thanks to both for their clarifications.
->appends() can accept an array as a parameter, you could pass Input::except('page'), that should do the trick.
Example:
return view('manage/users', [
'users' => $users->appends(Input::except('page'))
]);
You could use
->appends(request()->query())
Example in the Controller:
$users = User::search()->order()->with('type:id,name')
->paginate(30)
->appends(request()->query());
return view('users.index', compact('users'));
Example in the View:
{{ $users->appends(request()->query())->links() }}
Be aware of the Input::all() , it will Include the previous ?page= values again and again in each page you open !
for example if you are in ?page=1 and you open the next page, it will open ?page=1&page=2 So the last value page takes will be the page you see ! not the page you want to see
Solution : use Input::except(array('page'))
Laravel 7.x and above has added new method to paginator:
->withQueryString()
So you can use it like:
{{ $users->withQueryString()->links() }}
For laravel below 7.x use:
{{ $users->appends(request()->query())->links() }}
Not append() but appends()
So, right answer is:
{!! $records->appends(Input::except('page'))->links() !!}
LARAVEL 5
The view must contain something like:
{!! $myItems->appends(Input::except('page'))->render() !!}
Use this construction, to keep all input params but page
{!! $myItems->appends(Request::capture()->except('page'))->render() !!}
Why?
1) you strip down everything that added to request like that
$request->request->add(['variable' => 123]);
2) you don't need $request as input parameter for the function
3) you are excluding "page"
PS) and it works for Laravel 5.1
In Your controller after pagination add withQueryString() like below
$post = Post::paginate(10)->withQueryString();
Include This In Your View
Page
$users->appends(Input::except('page'))
for who one in laravel 5 or greater
in blade:
{{ $table->appends(['id' => $something ])->links() }}
you can get the passed item with
$passed_item=$request->id;
test it with
dd($passed_item);
you must get $something value
In Laravel 7.x you can use it like this:
{{ $results->withQueryString()->links() }}
Pass the page number for pagination as well. Some thing like this
$currentPg = Input::get('page') ? Input::get('page') : '1';
$boards = Cache::remember('boards' . $currentPg, 60, function() {
return WhatEverModel::paginate(15);
});
Many solution here mention using Input...
Input has been removed in Laravel 6, 7, 8
Use Request instead.
Here's the blade statement that worked in my Laravel 8 project:
{{$data->appends(Request::except('page'))->links()}}
Where $data is the PHP object containing the paginated data.
Thanks to Alexandre Danault who pointed this out in this comment.

Zend Framework: View variable in layout script is always null

I set a view variable in someAction function like this:
$this->view->type = "some type";
When I access this variable inside layout script like this:
<?php echo $this->type ?>
it prints nothing. What's wrong?
My application.ini settings related to layout
resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts/"
resources.layout.layout = "layout" ; changed 'default' to 'layout'
Edit
This thread suggests the alternate solution, but looking for solution to above problem. And this was working in Zend 1.6.2. I just upgraded to 1.10 and it stopped working.
Edit
If I set this view var inside any _init Bootstrap function, it works.
If you want to assign something to your layout you have to go an other way:
// get the layout instance
$layout = Zend_Layout::getMvcInstance();
// assign fooBar as Name to the layout
$layout->name = 'fooBar';
I believe the layout view object and the action view object are separate instances of the Zend_View class.
I think this is the correct way to pass variables from the controller to the layout:
/**
* Controller action
*/
public function indexAction()
{
$this->_helper->layout()->assign('myName', 'John Doe');
}
and then in your layout script you can access the variables by referencing the layout object like this:
<html>
<body>
<?php echo $this->layout()->myName; ?>
</body>
</html>
Do you have the following entry in your application.ini file?
resources.view[] =
So, you can initialize the view with no options and use it through:
<?php echo $this->type ?>

Resources