I have a doubt. I have been checking laracasts and they show some examples of passing variable(s) from router to a view:
Route::get('about', function() {
$people = ['Eduardo', 'Paola', 'Chancho'];
return view('about')->with('people', $people);
});
Route::get('about', function() {
$people = ['Eduardo', 'Paola', 'Carlos'];
return view('about')->withPeople($people);
});
The second example, I am not sure how Laravel handle it. I know it works I have test it, but which pattern they use? why is it possible to handle a dynamic variable.
Thanks in advance for your help!
The second one is handled by Laravel through php's __call magic method. This method redirects all methods that start with 'with' to the with method through this code in the Illuminate\View\View class:
public function __call($method, $parameters)
{
if (Str::startsWith($method, 'with')) {
return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
}
throw new BadMethodCallException("Method [$method] does not exist on view.");
}
As you can see if the method starts with 'with' (Str::startsWith($method, 'with'), Laravel redirects it to the with method return $this->with by taking the first param as the string that follows 'with' Str::snake(substr($method, 4)) and the second param as the first param that was passed $parameters[0]
Hope this helps!
Try this to pass data in view
Route::get('about', function() {
$data['people'] = ['Eduardo', 'Paola', 'Chancho'];
return view('about')->withdata($data);
});
Try this, it works.
Route::get('about', function() {
$people = ['Eduardo', 'Paola', 'Chancho'];
return view('about',compact('people'));
});
Related
Let's say I have a controller called TeamsController. Controller has following method, that returns all teams user has access to.
public function findAll(Request $request): JsonResponse
{
//...
}
Then I have bunch of other controllers with the same method. I would like to create a single route, that would work for all controllers, so I would not need to add a line for each controller every time I create a new controller.
I am unable to catch the controller name from URI. This is what I have tried.
$router->group(['middleware' => 'jwt.auth'], function () use ($router) {
// This works
//$router->get('teams', 'TeamsController#findAll');
// This just returns TeamsController#findAll string as a response
$router->get('{resource}', function ($resource) {
return ucfirst($resource) . 'Controller#findAll';
});
});
You return a string instead of calling a controller action:
I believe Laravel loads the controllers this way (not tested)
$router->group(['middleware' => 'jwt.auth'], function () use ($router) {
$router->get('{resource}', function ($resource) {
$app = app();
$controller = $app->make('\App\Http\Controllers\'. ucfirst($resource) . 'Controller');
return $controller->callAction('findAll', $parameters = array());
});
});
But again, I don't really think it's a good idea.
I would like to understand how to associate more methods to my route. For example:
Route::get('/dashboard', 'DController#showX')->middleware('auth');
Besides showX() I have another function called showY() that I would like to associate with the route, but if I rewrite it twice it doesn't go, how can I solve the problem?
Controller:
public function showY(){
$name=Auth::user()->name;
return view('dashboard',['name'=>$name]);
}
public function showX(){
$y= Y::all();
}
There is no way to do it from the route like that. How would you handle two return values?
Judging by the controller methods, maybe you want to use the value of showX in showY?
The way I see to handle this would be to have one method in the route:
Route::get('/dashboard', 'DController#show')->middleware('auth');
and have it fire both of your other methods:
public function show() {
// decide what to return
$xValue = $this->showX();
return $this->showY($xValue);
}
protected function showY($y){
$name=Auth::user()->name;
return view('dashboard',['name' => $name, 'y' => $y]);
}
protected function showX(){
$y= Y::all();
}
Within the reentryAction in my CustomerclientController I want to forward into the indexAction in case of successful validity check of the post parameters.
Unfortunately, the forward doesn't work. While debugging, I determined that the reentryAction method will be called again, instead of indexAction.
I registered a Dispatcher in my services.php as follows:
$di->setShared('dispatcher', function() use ($eventsManager) {
$dispatcher = new MvcDispatcher();
// Bind the eventsManager to the view component
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
The CustomerclientController:
class CustomerclientController extends Controller {
public function reentryAction($hash) {
// ... a lot of code
if ($this->request->isPost()) {
// ... a lot of code
if ($valid) {
$this->dispatcher->forward([
"customerclient",
"index"
]);
return;
}
}
}
public function indexAction() {
//Does something wise
}
}
I defined no special routes and do not use a route.php file.
What am I doing wrong or what did I forget?
Thanks in advance for your help!
Are you sure you need use MvcDispatcher?
I checked my project and I am using Dispatcher
$di->set('dispatcher', function() use ($di) {
$dispatcher = new Dispatcher;
$dispatcher->setEventsManager($eventsManager);
return $dispatcher;
});
I hope it works!
First of all, try to return the dispatcher->forward(). Second, maybe write the keys in the array.
if ($valid)
return $this->dispatcher->forward([
"controller" => "customerclient",
"action" => "index"
]);
Hope that helps!
I want to prevent write all route in Laravel route.php,actually i follow MVC routing like this www.example.com/controller/action/p1/p2/p3
if you have any good idea give it to me,
i wrote this
$controller = ucfirst(Request::segment(1));
$controller = $controller . 'Controller';
$result=App::make('indexController')->ChechIfExistController($controller);
if($result){
if(Request::segment(2))
$action=Request::segment(2);
else
$action='index';
if(Request::segment(5))
Route::any('/{controller?}/{action?}/{p1?}/{p2?}/{p3?}',array('uses'=>$controller.'#'.$action));
else if(Request::segment(4))
Route::any('/{controller?}/{action?}/{p1?}/{p2?}',array('uses'=>$controller.'#'.$action));
else if(Request::segment(3))
Route::any('/{controller?}/{action?}/{p1?}',array('uses'=>$controller.'#'.$action));
else
Route::any('/{controller?}/{action?}',array('uses'=>$controller.'#'.$action));
} else{
echo '404';
EXIT;
}
but i don't know how to control and check controller and action in laravel to understand if it exist or not.
i need your help.
thanks a lot.
ifound it,this code fix the problem and check if action exist or not,but i would like to do that with laravel but it seems laravel does not have any thing for checking controller and actions
$controller=='Controller'?$controller='IndexController':$controller;
$controllers=new $controller ();
if(method_exists($controllers,$action)){...}
and in composer define my route,
that's all
routes.php
Route::controllers([
'auth' => 'Auth\AuthController',
]);
in AuthController you can do that:
// will be available as METHODNAME /auth/url/{one?}/{two?}/{three?}/{four?}/{five?}
public [methodName]Url($one, $two, $three, $four, $five)
{
//...
}
// for example POST /auth/register
public function postRegister(Request $request)
{
// ...
}
// GET /auth/login
public function getLogin()
{
//...
}
it's not documented, but you can see that in sources:
https://github.com/laravel/framework/blob/5.0/src%2FIlluminate%2FRouting%2FControllerInspector.php
https://github.com/laravel/framework/blob/5.0/src%2FIlluminate%2FRouting%2FRouter.php#L238
That can be done such way:
First we have to write static routes and after that, dynamic route which uses database.
routes.php
Route::get('/', function () {
return 'welcome';
});
Route::get('/faq', function () {
return 'faq';
});
Route::get('/about', function () {
return 'about';
});
Route::get('/{slug}', function ($slug) {
return Article::where('slug', $slug)->first();
});
How can I pass a variable that is processed in the filter back to route for later usage?
Example:
Filter:
Route::filter('myfilter', function()
{
return "some data";
});
Route:
Route::get('/mypage', array('before'=>'myfilter', function($filter) {
if($filter!= 'admin') {
return Redirect::to('home');
}
}));
The above example doesn't work. How can I make it works?
Thank you.
WARNING: THIS DOESN'T SEEM TO WORK!
Store it in the IoC container: http://laravel-recipes.com/recipes/3
Filter:
Route::filter('myfilter', function()
{
App::instance('app.name', 'John Doe'); // store var
});
Route:
Route::get('/mypage', array('before'=>'myfilter', function() {
$name = app('app.name'); // read var
return $name;
}));
You cannot. If you return anything from filters Laravel will return that filter to your browser and end your request.
Whay you can do is to redirect to a route and pass values to that route:
Route::filter('myfilter', function()
{
return Redirect::to('mynewpage')->with('var', 'some data');
});
This data will come back in the Session:
$data = Session::get('var');
You may pass data by any of below methods:
Session::put() and Session::get() ( slow because of disk writes )
Config::set() and Config::set() Defining PHP constant by
define() ( recommended for your purpose ) Setting and getting a
global variable by $_GLOBALS[] array ( not recommended )
Recently working in an old Laravel 4.2 project & approached this with a controller method as Controller Filter:
namespace App\Controllers;
Class MyController extends BaseController
{
protected $filterValue;
public function __construct()
{
$this->beforeFilter('#myFilter', array(
'only' => 'myPage'
));
}
public function myFilter($route, $request)
{
$this->filterValue = 'some data';
}
public function myPage()
{
if ($this->filterValue != 'admin') {
return Redirect::to('home');
}
}
}