Laravel How to get Route Profile based on Route Name - laravel

I have this route:
Route::get('/test',['as'=>'test','custom_key'=>'custom_value','uses'=>'TestController#index'])
I've been tried to use $routeProfile=route('test');
But the result is returned url string http://domain.app/test
I need ['as'=>'test','custom_key'=>'custom_value'] so that I can get the $routeProfile['custom_key']
How can I get 'custom_value' based on route name ?

For fastest way, now I use this for my question:
function routeProfile($routeName)
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
$action = $route->getAction();
if (!empty($action['as']) && $routeName == $action['as']) {
$action['methods'] = $route->methods();
$action['parameters'] = $route->parameters();
$action['parametersNames'] = $route->parametersNames();
return $action;
}
}
}
If there's any better answer, I will be appreciate it.
Thanks...

Try this:
use Illuminate\Support\Facades\Route;
$customKey = Route::current()->getAction()['custom_key'];

I believe you are looking for a way to pass variable to your route
Route::get('/test/{custom_key}',[
'uses'=>'TestController#index',
'as'=>'test'
]);
You could generate a valid URL like so using
route('test',['custom_key'=>'custom_key_vale'])
In your view:
<a href="{route('test',['custom_key'=>'custom_key_vale'])}"
In your controller method:
....
public function test(Request $request)
{
$custom_key = $request->custom_key;
}
....

You can try one of the below code:
1. Add use Illuminate\Http\Request; after namespace line code
public function welcome(Request $request)
{
$request->route()->getAction()['custom_key'];
}
2. OR with a facade
Add use Route; after namespace line code
and use below into your method
public function welcome()
{
Route::getCurrentRoute()->getAction()['custom_key'];
}
Both are tested and working fine!

Related

how can i get language value randomly in laravel controller?

class DynamicDependent extends Controller
{
function fetch(Request $request)
{
$value = "home";
$value2 = Lang::get('home.'.$value.'');
}
}
output :'home.home'.
But i need value from language file.
please guide me to get this.
It seems like you are trying to get a translation. For that you can use the trans helper method like this:
//In your resources/lang/{some_lang_code}/home.php
return [
'home' => 'My translation',
];
//In your controller
$value = "home";
$value2 = trans('home.'.$value); //My translation

recover the slug of a category linked to another category Laravel

I would like to recover the slug of 2 categories from my routes but can’t write the Controller.
My Route
Route::get('technicians/o/{occupation}/c/{city}', 'User\TechnicianController#viewoccupationcity');
My Controller
public function viewoccupationcity($slug)
{
$technicians = TechnicianResource::collection(occupation::where('slug',$slug)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
Route::get('technicians/o/{occupation}/c/{city}', 'User\TechnicianController#viewoccupationcity');
Your controller will accept the parameters from your route as variables by order
public function viewoccupationcity($ocupation, $city)
{
...
}
Example:
URL: technicians/o/foo/c/bar
public function viewoccupationcity($ocupation, $city)
{
// $ocupation will be 'foo'
// $city will be 'bar
}
Ok, you would need to retrieve 2 variables as that is what you are passing
public function viewoccupationcity($occupation, $city)
If you want the whole slug to do another search then you would use the $request object. So like so
public function viewoccupationcity(Request $request, $occupation, $city){ // You also need to include the Request decleration
$slug = $request->path();
$technicians = TechnicianResource::collection(occupation::where('slug',$slug)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
EDIT: We are having to do a lot of guesswork as your question isn't very clear. I think what you are trying to achieve is probably this
public function viewoccupationcity($occupation, $city){
$technicians = TechnicianResource::collection(occupation::where('city',$city)->where('occupation',$occupation)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
If you need something more then you need to give more details

It can not find my variable in my view in laravel 5.6

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$datanews['newss'] = News::orderBy('created_at','desc')->get();
$dataevent['events'] = Event::orderBy('created_at','desc')->get();
$user['users'] = User::all();
return view('user/aktuelles.index',$datanews, $dataevent,$user);
}
this is a part of my controller, i can show news and events in my view but everytime it says it can not find the variable user?
i dont know why because i dont know why it shows me the other variables but not the user variable???
in my view i can see the other variables like this:
#foreach ($newss as $news)
{{$news->newstitel}}
#endforeach
but i want to show user like this:
{{$user[1]->avatar}}
i tried everything so i tried so look my controller like this:
$user = DB::table('users')->get();
or get the variable via compact
and i tried exactly the same so like this
$user['users'] = User::orderBy('created_at','desc')->get();
and a foreach in my view but it can not found the variable user??
i dont know why
this is the error
Undefined variable: users
return view('user.aktuelles.index', compact('datanews', 'dataevent', 'user');
I am not sure how the helper view() handles the 4th parameter you are passing. According to the docs you can pass data like this:
return view('user/aktuelles.index',[
'datanews' => $datanews,
'dataevent' => $dataevent,
'user' => $user,
]);
or
return view('user/aktuelles.index')->with([
'datanews' => $datanews,
'dataevent' => $dataevent,
'user' => $user,
]);
Maybe give this way a try.
Edit:
The view() helper accepts 3 Parameters: $view = null, $data = [], $mergeData = [] so the 4th parameter you are trying to pass is not even working. You have to pass your data as second parameter or with the chained function with(array $data).
You have to return value in view like below method:
Change this line
$user['users'] = User::orderBy('created_at','desc')->get();
To
$user = User::orderBy('created_at','desc')->get();
return view('user/aktuelles.index', ['datanews' => $datanews,'dataevent'=> $dataevent,'users'=>$user]);
Now, You will get result inside your view using 'users'.
You are not passing variables to view correctly use with or compact to pass variables to view.
i prefer compact as it is simple and easier.
Passing data to view using compact:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$datanews = News::orderBy('created_at','desc')->get();
$dataevent = Event::orderBy('created_at','desc')->get();
$user = User::all();
return view('user.aktuelles.index',compact('datanews', 'dataevent','user'));
}
Passing variables to view using with:
public function index()
{
$datanews = News::orderBy('created_at','desc')->get();
$dataevent = Event::orderBy('created_at','desc')->get();
$user = User::all();
return view('user.aktuelles.index)->with(['datanews' => $datanews,'dataevent'=> $dataevent,'users'=>$user]);
}
You should try this:
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$data['news'] = News::orderBy('created_at','desc')->get();
$data['events'] = Event::orderBy('created_at','desc')->get();
$data['users'] = User::all();
return view('user/aktuelles.index', $data);
}

laravel route by passing parameter got page not found

I just regular do the route with passing parameter
Route::get('cabinet', 'CabinetController#index');
Route::get('cabinet/{$id}', 'CabinetController#show');
and the controller just simple like this
class CabinetController extends Controller
{
function index()
{
$cabinets = Cabinet::all();
return view('detail', compact('cabinets'));
}
function show($id)
{
$single = Cabinet::find($id);
$cabinets = Cabinet::all();
return view('detail', compact('cabinets', 'single'));
}
}
public/cabinet/1
How come i got
Sorry, the page you are looking for could not be found.
Thank you for solve this for me
Remove the $ from route declaration:
Route::get('cabinet/{id}', 'CabinetController#show');

Routing to controller with optional parameters

I'd like to create a route that takes a required ID, and optional start and end dates ('Ymd'). If dates are omitted, they fall back to a default. (Say last 30 days) and call a controller....lets say 'path#index'
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(!$start)
{
//set start
}
if(!$end)
{
//set end
}
// What is the syntax that goes here to call 'path#index' with $id, $start, and $end?
});
There is no way to call a controller from a Route:::get closure.
Use:
Route::get('/path/{id}/{start?}/{end?}', 'Controller#index');
and handle the parameters in the controller function:
public function index($id, $start = null, $end = null)
{
if (!$start) {
// set start
}
if (!$end) {
// set end
}
// do other stuff
}
This helped me simplify the optional routes parameters (From Laravel Docs):
Occasionally you may need to specify a route parameter, but make the presence of that route parameter optional. You may do so by placing a ? mark after the parameter name. Make sure to give the route's corresponding variable a default value:
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
Or if you have a controller call action in your routes then you could do this:
web.php
Route::get('user/{name?}', 'UsersController#index')->name('user.index');
userscontroller.php
public function index($name = 'John') {
// Do something here
}
I hope this helps someone simplify the optional parameters as it did me!
Laravel 5.6 Routing Parameters - Optional parameters
I would handle it with three paths:
Route::get('/path/{id}/{start}/{end}, ...);
Route::get('/path/{id}/{start}, ...);
Route::get('/path/{id}, ...);
Note the order - you want the full path checked first.
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Find more details here (Laravel 7) : https://laravel.com/docs/7.x/routing#parameters-optional-parameters
You can call a controller action from a route closure like this:
Route::get('{slug}', function ($slug, Request $request) {
$app = app();
$locale = $app->getLocale();
// search for an offer with the given slug
$offer = \App\Offer::whereTranslation('slug', $slug, $locale)->first();
if($offer) {
$controller = $app->make(\App\Http\Controllers\OfferController::class);
return $controller->callAction('show', [$offer, $campaign = NULL]);
} else {
// if no offer is found, search for a campaign with the given slug
$campaign = \App\Campaign::whereTranslation('slug', $slug, $locale)->first();
if($campaign) {
$controller = $app->make(\App\Http\Controllers\CampaignController::class);
return $controller->callAction('show', [$campaign]);
}
}
throw new \Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
});
What I did was set the optional parameters as query parameters like so:
Example URL:
/getStuff/2019-08-27?type=0&color=red
Route:
Route::get('/getStuff/{date}','Stuff\StuffController#getStuff');
Controller:
public function getStuff($date)
{
// Optional parameters
$type = Input::get("type");
$color = Input::get("color");
}
Solution to your problem without much changes
Route::get('/path/{id}/{start?}/{end?}', function($id, $start=null, $end=null)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
return App\Http\Controllers\HomeController::Path($id,$start,$end);
});
and then
class HomeController extends Controller
{
public static function Path($id, $start, $end)
{
return view('view');
}
}
now the optimal approach is
use App\Http\Controllers\HomeController;
Route::get('/path/{id}/{start?}/{end?}', [HomeController::class, 'Path']);
then
class HomeController extends Controller
{
public function Path(Request $request)
{
if(empty($start))
{
$start = Carbon::now()->subDays(30)->format('Y-m-d');
}
if(empty($end))
{
$end = Carbon::now()->subDays(30)->format('Y-m-d');
}
//your code
return view('view');
}
}

Resources