I have some problems with my controller in laravel 5.4
My routes.php:
Route::group(array('domain' => '{subdomain}.site.com','as'=>'www::','middleware'=>array('web','varnish')), function() {
Route::any('/material/{page?}/', [
'as' => 'www_material', 'uses' => 'www\MaterialController#index'
]);
});
My controller:
<?php namespace App\Http\Controllers\www;
use App\Http\Controllers\Controller;
use View;
use DB;
use Illuminate\Http\Request;
class MaterialController extends Controller {
public function index($subdomain, $page = 1, Request $request)
{
echo $subdomain;
echo $page;
//...some code
}
}
There is no problems with url www.site.com/material/2/:
submodain = www,
page = 2
But www.site.com/material/:
Type error: Too few arguments to function App\Http\Controllers\www\MaterialController::index(), 2 passed and exactly 3 expected
I cant understand why this happend, because default value of page is 1.
Can someone help me? I cant solve this problem alone.
Thank you.
Your problem is the order the arguments are in the index method.
As the Request object will always be present put that first followed by $subdomain and then $page
As stated on the php website above example #5:
Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.
public function index(Request $request, $subdomain, $page = 1)
{
echo $subdomain;
echo $page;
//...some code
}
Try to remove trailing slash next to {page?} mentioned below and rerun the code.
Route::any('/material/{page?}', [
'as' => 'www_material', 'uses' => 'www\MaterialController#index'
]);
Related
Hi I have the following Lumen Route
$router->get('/end', function (\Illuminate\Http\Request $request) use ($router) {
$controller = $router->app->make('App\Http\Controllers\Legacy\EndLegacyController');
return $controller->index($request);
});
I am trying to give it a route name so that I can use redirect to redirect to this route like redirect()->route('name_of_route')
so far I have tried
})->namedRoute['end'] = '/end'; // No Effect
})->name('end') //Undefined function
but it didn't work
here's a list of present routes
Edit
Because of my certain requirement, I can't use ['as' => 'end', 'uses'=> 'ControllerName#Action']
you can use the following syntax: $router->get('/end', ['as'=>'name_here', function()]);
I am getting 404 while am trying to access my api url here is my route :
MY Api route list:
<?php
use Illuminate\Http\Request;
Route::middleware('auth:api')->get('/', function (Request $request) {
return $request->user();
});
Route::get('testapi','ApiDoctorController#testapi');
and the controller function that is provide data response is :
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi(){
$data = [
'name' => 'HEllo',
'age' => '24',
'height' => '5.4'
]
return response()->json($data);
}
}
When i try to access it in post-man at http://mydomain/project/api/testapi
its showing 404 error i am new to laravel help me out please
[![POSTMAN RESPONSE][1]][1][1]: https://i.stack.imgur.com/1uV6Z.png
First of all your missing the semicolon on the end of your data array.
Is Route::get('testapi','ApiDoctorController#testapi'); in your routes/api.php?
If not you'll need to define it so.
In postman you're doing domain/project/api/testapi when it should be domain/api/testapi as that is what you have specified in your routes file unless your entire laravel install is in domain/project.
I have added the semi-colon for you and formatted the code. If you're testing via postman please ensure that CSRF is disabled in your App/Http/Kernel.php (Just comment it out for your testing) then place it back in when you've setup authentication.
Let me know if this helps!
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiDoctorController extends Controller
{
public function testapi()
{
$data = [
'name' => 'Hello',
'age' => '24',
'height' => '5.4'
];
return response()->json($data);
}
}
Thanks everyone i got it i just add public after my project directory and it work thanks to all of you for your valuable time
How to get value of one route into another
Route::get('/first_url', function () {
return "Hello this is test";
});
I Tried something like this but not worked.
Route::get('/second_url', function () {
$other_view = Redirect::to('first_url');
});
I want to get returned value from first_url to variable $other_view in second_url to process and manipulate returned value.
Using Redirect is changing url. Which I dont want to use.
Any Idea ??? Or Am I trying wrong thing to do.
If you just want to return first_url, do this:
Route::get('/first_url', ['as' => 'firstRoute', function () {
return "Hello this is test";
}]);
Route::get('/second_url', function () {
return redirect()->route('firstRoute');
});
Learn more about redirects to routes here.
Update:
If you want to pass variable, you can use form or just create a link with parameters. You can try something like this {{ route('second_url', ['param' => 1]) }}
Then your second route will look like this:
Route::get('/second_url/{param}', ['uses' => 'MyController#myMethod', 'param' => 'param']);
And myMethod method in MyController:
public function myMethod($param){
echo $param;
...
I don't know why you would like to do this, but you can get the rendered contents of the route by executing a simple HTTP request to your route and reading the contents:
Route::get('/second_url', function () {
$other_view = file_get_contents(URL::to('first_url'));
return $other_view; // Outputs whatever 'first_url' renders
});
You need to send HTTP request and then process the response. You can use file_get_contents as #tommy has suggested or you can use HTTP library like Guzzle:
$client = new GuzzleHttp\Client();
$res = $client->get(route('firstRoute'));
in this case u should use a named route.
https://laravel.com/docs/5.1/routing#named-routes
somthing like this:
Route::get('/first_url', ['as' => 'nameOfRoute', function () {
return "Hello this is test";
}]);
Route::get('/second_url', function () {
redirect()->route('nameOfRoute');
});
You can not pass the variable value to another route directly. http is stateless protocol. if you want to preserve the value of variable to another route you can do that by 3 methods query string, sessions and cookies only. Your can pass parameter to to specific route like this
Route::get('/second_url/{param}', ['uses' => 'MyController#myMethod',
'param' => 'param']);
The idea behind achieving what you want is naming the function of your first route and calling it within both the first route and your second route. Your function will simply return the view to the first route, and retrieve the rendered html for your second.
function MyFirstRouteFunction() {
// Do whatever your do in your first route
// I assume your function return here an instance of Laravel's View
}
Route::get('/first_url', MyFirstRouteFunction);
Route::get('/second_url', function () {
$contentsOfFirstRoute = MyFirstRouteFunction()->render();
// Make use of rendered HTML
});
There is no need to make one extra HTTP request.
You should use Guzzle or curl to achive this:
Route::get('/second_url', function () {
//:::::Guzzle example:::::
$client = new GuzzleHttp\Client();
$res = $client->request('GET', 'http://...second_url...', []);
//:::::curl example:::::
$ch = curl_init();
//define options
$optArray = array(
CURLOPT_URL => 'http://...second_url...',
CURLOPT_RETURNTRANSFER => true
);
//apply those options
curl_setopt_array($ch, $optArray);
//execute request and get response
$res = curl_exec($ch);
});
Note that using Guzzle may need you to install required libraries.
If you put your first_route closure into a controller action you could try to instantiate that controller and call the method directly.
This is considered as bad practice.
routes.php
Route::get('/first_url', 'TestController#getFirstUrl');
App/Http/Controllers/TestController.php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
public function getFirstUrl()
{
return view('my-view');
}
}
routes.php
Route::get('/second_url', function () {
$controller = new \App\Http\Controllers\TestController();
$contentsOfFirstRoute = $controller->getFirstRoute();
// Make use of rendered HTML
});
I think what I want is quite basic, I just can't find the proper syntax as I am still learning Laravel.
So, I am using google verification for sign ins on my website. This entails a post request to my backend that has to be handled, I have put this logic in a controller. My routes.php:
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken'
]);
My controller (verify.php):
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class verify extends Controller
{
public function verifyIdToken($token)
{
$token = $_POST['id'];
$email = $_POST['email'];
return $this->getAuth()->verifyIdToken($token);
echo $this->getAuth()->verifyIdToken($token);
return view('aviewII')->with(['verify' => json_encode(verifyIdToken($token)),'email'=> json_encode($email)]);
}
}
Of course, because of how the function in the controller is written, I get the following error Missing argument 1 for App\Http\Controllers\verify::verifyIdToken() My question is, how do I tell the function in the controller to take $_POST['id'] as the argument for $token?
Something like this:
Route::post('google' , [
'as' => 'verify.index',
'uses' => 'verify#verifyIdToken ~with $_POST['id'] as $token'
]);
For additional reference, my actual post request looks like this:
$.post( "http://example.com/google", {email:profile.getEmail(),id:id_token} );
Controller method:
public function verifyIdToken(Request $request)
{
// Not necessary but a better practice for ajax 'POST' responses.
if($request->ajax() && $request->isMethod('post'))
{
return $request::get('token');
}
}
Route:
Route::post('google', ['as' => 'some.alias', 'uses' => 'SomeController#verifyIdToken']);
You are looking for Laravel's request class. You should type-hint the class on your method, which then allows loads of options to actually obtain the data. Something like:
use Illuminate\Http\Request;
public function verifyIdToken(Request $request)
{
$token = $request->input('id');
$email = $request->input('email');
return $this->getAuth()->verifyIdToken($token);
echo $this->getAuth()->verifyIdToken($token);
return view('aviewII')->with(['verify' => json_encode(verifyIdToken($token)),'email'=> json_encode($email)]);
}
The documentation on it has tons more useful information.
I am currently trying to create a link on the index page that'll allow users to create an item. My routes.php looks like
Route::controller('items', 'ItemController');
and my ItemController looks like
class ItemController extends BaseController
{
// create variable
protected $item;
// create constructor
public function __construct(Item $item)
{
$this->item = $item;
}
public function getIndex()
{
// return all the items
$items = $this->item->all();
return View::make('items.index', compact('items'));
}
public function getCreate()
{
return View::make('items.create');
}
public function postStore()
{
$input = Input::all();
// checks the input with the validator rules from the Item model
$v = Validator::make($input, Item::$rules);
if ($v->passes())
{
$this->items->create($input);
return Redirect::route('items.index');
}
return Redirect::route('items.create');
}
}
I have tried changing the getIndex() to just index() but then I get a controller method not found. So, that is why I am using getIndex().
I think I have set up my create controllers correctly but when I go to the items/create url I get a
Unable to generate a URL for the named route "items.store" as such route does not exist.
error. I have tried using just store() and getStore() instead of postStore() but I keep getting the same error.
Anybody know what the problem might be? I don't understand why the URL isn't being generated.
You are using Route::controller() which does generate route names as far as I know.
i.e. you are referring to "items.store" - that is a route name.
You should either;
Define all routes specifically (probably best - see this blog here)
Use Route::resource('items', 'ItemController'); see docs here
If you use Route::resource - then you'll need to change your controller names
The error tells you, that the route name is not defined:
Unable to generate a URL for the named route "items.store" as such route does not exist.
Have a look in the Laravel 4 Docs in the Named Routes section. There are several examples that'll make you clear how to use these kind of routes.
Also have a look at the RESTful Controllers section.
Here's an example for your question:
Route::get('items', array(
'as' => 'items.store',
'uses' => 'ItemController#getIndex',
));
As The Shift Exchange said, Route::controller() doesn't generate names, but you can do it using a third parameter:
Route::controller( 'items',
'ItemController',
[
'getIndex' => 'items.index',
'getCreate' => 'items.create',
'postStore' => 'items.store',
...
]
);