Laravel - How to pass a variable to controller through resource route? - laravel

I've defined this resource in web.php of Laravel app,
Route::resource('Student', 'StudentCtrl');
and I have a variable which contains name of meta file,
$metaFile = 'student_meta.json';
I want to pass $metaFile to StudentCtrl, so I can catch the file name there.
I'm using Laravel 5.4.
Thanks.

Just pass the variable to the url, And thats it.
if its a get request will be routed to StudentCtrl#show
if its a put request will be routed to StudentCtrl#update
if its a delete request will be routed to StudentCtrl#destroy
And so on.
All you have to do is to define a method of the form. GET,POST,PUT/PATCH,DELETE.
Have a look here.

Passing a single variable from Router to Controller is possible only for Single HTTP request method.
Refer here : https://stackoverflow.com/a/50405137/9809983
For a complete resource route, its possible to send a fixed value to all views under that resource, if that's what you are trying to do
In Controller
public function __construct(Request $request)
{
$action_array = $request->route()->getAction();
$json_file['json_file'] = "student_meta.json";
$new_action_array = array_merge($action_array, $json_file);
$request->route()->setAction($new_action_array);
}
Now you can access the value in all the views under the resource controller like,
In View
{{ request()->route()->getAction('json_file') }}
Tested and perfectly works in Laravel 5.6

Related

laravel 5.8 edit function with model instance

public function edit(EduLevel $eduLevel)
{
dd($eduLevel->name);
return view('adm.edulevel.edit',compact('eduLevel'));
}
Route::resource('edulevel','EduLevelController'); //web.php
with resource route
how to get eduLevel to view with model instance laravel. in previous i call with parme parameter id and use find() method to get data..
from this sample - https://itsolutionstuff.com/post/laravel-58-crud-create-read-update-delete-tutorial-for-beginnersexample.html
I don't understand the question but I will just guess that you have a route that accepts a parameter that you you expect it to be the model inside your function.
You need to create a route like this one:
Route::get('/edit/{eduLevel}', 'SomeController#edit');
Notice the same name for the variable, this is important otherwise you will get only the id, slug or whatever.
Make sure your path name also have the same name for route segment name.
so your route path should be like this.
Route::get('/edit/{variablename}', 'ControllerName#edit');
your controller function logic should be like this.
public function edit(EduLevel $variablename)
{
return view('adm.edulevel.edit',compact('variablename'));
}
So make sure your variable name in route and in controller function
should be same.
For more information, you can read Route Model Binding in laravel
I am having the same problem (almost).
I wanted to call a controller method in the view. So I should pass the model from controller to view.
How to pass model from controller to view?
I found this [Laravel 5 call a model function in a blade view but using ->withModel($model); to pass the model from controller to view and {{$model->someFunction()}} to call the method in the view is not working.
Any advice please?

How to set a route parameter default value from request url in laravel

I have this routing settings:
Route::prefix('admin/{storeId}')->group(function ($storeId) {
Route::get('/', 'DashboardController#index');
Route::get('/products', 'ProductsController#index');
Route::get('/orders', 'OrdersController#index');
});
so if I am generating a url using the 'action' helper, then I don't have to provide the storeId explictly.
{{ action('DashboardController#index') }}
I want storeId to be set automatically from the request URL if provided.
maybe something like this.
Route::prefix('admin/{storeId}')->group(function ($storeId) {
Route::get('/', 'DashboardController#index');
Route::get('/products', 'ProductsController#index');
Route::get('/orders', 'OrdersController#index');
})->defaults('storeId', $request->storeId);
The docs mention default parameter though in regards to the route helper (should work with all the url generating helpers):
"So, you may use the URL::defaults method to define a default value for this parameter that will always be applied during the current request. You may wish to call this method from a route middleware so that you have access to the current request"
"Once the default value for the ... parameter has been set, you are no longer required to pass its value when generating URLs via the route helper."
Laravel 5.6 Docs - Url Generation - Default Values
In my Laravel 9 project I am doing it like this:
web.php
Route::get('/world', [NewsController::class, 'section'])->defaults('category', "world");
NewsController.php
public function section($category){}
Laravel works exactly in the way you described.
You can access storeId in your controller method
class DashboardController extends Controller {
public function index($storeId) {
dd($storeId);
}
}
http://localhost/admin/20 will print "20"

Laravel - route model binding with request headers

I am wondering is it possible to do something similar to route model binding, but with request headers. I have a query that I check on my api endpoints, that looks like this:
User::where('telephone', $request->header('x-user'))->firstOrFail();
Is it possible to somehow avoid repeating this query in every method in controllers, but to apply it to routes, so that I could just get the user object just like in a route model binding with type hinting in a function, for every route that in an api routes folder:
public function userTransactions(User $user)
{
//
}
Create a middleware and assign it to the desired routes.
Option 1
In your middleware do:
$user = User::where('telephone', $request->header('x-user'))->firstOrFail();
request()->merge(['user_model' => $user]);
You can then request()->get('user_model') anywhere in your controller
Option 2
Start by creating a global scope class that conforms to your query. Here you'd get the header value and use that in the scope.
https://laravel.com/docs/5.5/eloquent#global-scopes
Next in the middleware, add the scope to the model using addGlobalScope
User::addGlobalScope(new HeaderScope())
Now all queries for User will have a where clause with your header value.
You can subsequently remove the scope or ignore global scopes if needed.

Pass data from routes.php to a controller in Laravel

I am attempting to create a route in Laravel for a dynamic URL to load a particular controller action. I am able to get it to route to a controller using the following code:
Route::get('/something.html', array('uses' => 'MyController#getView'));
What I am having trouble figuring out is how I can pass a variable from this route to the controller. In this case I would like to pass along an id value to the controller action.
Is this possible in Laravel? Is there another way to do this?
You are not giving us enough information, so you need to ask yourself two basic questions: where this information coming from? Can you have access to this information inside your controller without passing it via the routes.php file?
If you are about to produce this information somehow in your ´routes.php´ file:
$information = WhateverService::getInformation();
You cannot pass it here to your controller, because your controller is not really being fired in this file, this is just a list of available routes, wich may or may not be hit at some point. When a route is hit, Laravel will fire the route via another internal service.
But you probably will be able to use the very same line of code in your controller:
class MyController extends BaseController {
function getView()
{
$information = WhateverService::getInformation();
return View::make('myview')->with(compact('information'));
}
}
In MVC, Controllers are meant to receive HTTP requests and produce information via Models (or services or repositores) to pass to your Views, which can produce new web pages.
If this information is something you have in your page and you want to sneak it to your something.html route, use a POST method instead of GET:
Route::post('/something.html', array('uses' => 'MyController#getView'));
And inside your controller receive that information via:
class MyController extends BaseController {
function getView()
{
$information = Input::get('information');
return View::make('myview')->with(compact('information'));
}
}

Laravel 4 - Setting up routes

I'm working on a site I have inherited and having a little trouble routing to a controller.
When I visit the URL www.domain.com/banners/statistics, it won't return anything.
I also noted that when I try and link to this page via Banner Statistics this also gives me an error on my home page.
Routes.php
Route::resource('banners', 'BannerController');
Route::get('banners/{banners}/activate', 'BannerController#activate');
Route::get('banners/{banners}/deactivate', 'BannerController#deactivate');
Route::get('banners/{banners}/delete', 'BannerController#delete');
Route::get('banners/{banners}/preview', 'BannerController#preview');
Route::any('banners/{banners}/cropresize', 'BannerController#cropresize');
Route::get('banners/statistics', 'BannerController#statistics');
BannerController.php
public function create()
{
$data['title'] = 'Create Banner';
$data['disciplines'] = Discipline::lists('name', 'id');
return View::make('admin.banners.create', $data);
}
public function statistics()
{
return View::make('admin.banners.statistics');
}
The resource controller provides you multiple routes.
Including :
GET /resource/{resource} redirecting to the show action of your controller.
List of all created routes : http://laravel.com/docs/controllers#resource-controllers
So when you call
banners/statistics
Laravel think you want to call the show action with "statistics" as a parameter.
To avoid this, you can put all your custom routes above your resource controller route.
Route::get('banners/{banners}/activate', 'BannerController#activate');
Route::get('banners/{banners}/deactivate', 'BannerController#deactivate');
Route::get('banners/{banners}/delete', 'BannerController#delete');
Route::get('banners/{banners}/preview', 'BannerController#preview');
Route::any('banners/{banners}/cropresize', 'BannerController#cropresize');
Route::get('banners/statistics', 'BannerController#statistics');
Route::resource('banners', 'BannerController');
This way Laravel will call your custom route before the routes created by your resource controller.
You can also use only and except if you don't need some of the resource controller routes.
Route::resource('banners', 'BannerController',
array('except' => array('show')));

Resources