Hi guys I hope someone can help me, I'm using laravel 4 and I have a REST controller like this
Route::controller('example', 'SomeClass');
class SomeClass extends BaseController {
public function getThisIsATest() {
return 'Hello World';
}
}
but when I try to enter the URI localhost/example/this-is-a-test
I get a 'Controller method not found.'
I'm thinking it's because the two consecutive uppercase letters in the 'getThisIsATest'
Does someone know how to fix this issue??
Two ways (without changing the URL)...
1. Use an additional route
Add an implicit route for the URL before the controller route:
Route::get('example/this-is-a-test', 'SomeClass#getThisIsATest');
Route::controller('example', 'SomeClass');
2. Change your method name to snake_case
You can change the method name in your controller to snake case and everything will work as excepted. (It doesn't look very pretty though)
public function get_this_is_a_test() {
return 'Hello World';
}
Actually it even works to only write the "problematic" part in snake case: getThisIsA_test. However this looks even more weird ;)
Try this:
Route::resource('example/this-is-a-test', 'SomeClassController#getThisIsATest');
OR:
Route::get('example/this-is-a-test', 'SomeClassController#getThisIsATest');
See, if that solves your problem & Do visit Laravel Controller Docs for more information
Add {{ URL::to('example/this-is-a-test'); }} and you're good to go
In your app/routes.php try defining your route as follows:
Route::controller("example", "testController");
And rename your controller class to
class testController extends BaseController {
public function index(){
// Just have it here to be safe.
}
public function getTest() {
return 'Hello World';
}
}
Now try navigating to localhost/example/test. Let me know if that works, I've never used Route::controller() before, so it's new to me as well.
Edit
As the above doesn't work for this example, try navigating to localhost/example/this-is-atest without changing your controller/route.
Related
I have been declaring all the routes for my application inside web.php , but it is now getting quite large. I find that I am losing a lot of time shifting between web.php and each controller and this is hurting productivity.
I feel like it would be better to define routes inside of the controller, perhaps ideally delegating some URL to a controller and then allowing the controller to handle the "sub routes" since this would allow me to use inheritance when I have two similar controllers with similar routes.
It is not possible given how laravel works. Every request is passed onto router to find its designated spot viz. the controller with the method. If it fails to find the route within the router, it just throws the exception. So the request never reaches any controller if the route is not found. It was possible in earlier versions on Symphony where you would configure the route in the comment of a particular controller method.
Sadly with laravel it works how it works.
But for me, I just like to have the routes in a separate file.
Alternate solution, easier way to sort all the routes.
You can move your route registration into controllers if you use static methods for this. The code below is checked in Laravel 7
In web.php
use App\Http\Controllers\MyController;
.....
MyController::registerRoutes('myprefix');
In MyController.php
(I use here additional static methods from the ancestor controller also posted below)
use Illuminate\Support\Facades\Route;
.....
class MyController extends Controller {
......
static public function registerRoutes($prefix)
{
Route::group(['prefix' => $prefix], function () {
Route::any("/foo/{$id}", self::selfRouteName("fooAction"));
Route::resource($prefix, self::selfQualifiedPath());
}
public function fooAction($id)
{
........
}
In Controller.php
class Controller extends BaseController {
....
protected static function selfAction($actionName, $parameters = [], $absolute = false)
{
return action([static::class, $actionName], $parameters, $absolute);
}
protected static function selfQualifiedPath()
{
return "\\".static::class;
}
protected static function selfRouteName($actionName)
{
//classic string syntax return "\\".static::class."#".$actionName;
// using tuple syntax for clarity
return [static::class, $actionName];
}
}
selfAction mentioned here is not related to your question, but mentioned just because it allows making correct urls for actions either by controller itself or any class using it. This approach helps making action-related activity closer to the controller and avoiding manual url-making. I even prefer making specific functions per action, so for example for fooAction
static public function fooActionUrl($id)
{
return self::selfAction('foo', ['id' => $id]);
}
Passing prefix into registerRoutes makes controller even portable in a sense, so allows inserting it into another site with a different prefix in case of conflict
I am trying to pass a parameter to my UserController but i can't seem to find a method to do this. All other topics give examples where the parameter is already defined in the url but that is not what i want.
$my_var = "some data";
Route::get('/login', 'Auth\UserController#login');
I need $my_var in my UserController
class UserController extends Controller
{
public function login()
{
// Retreive $my_var somehow
return view("login");
}
}
Sorry for my bad english, it's not my native language
In some cases using hardcoded parameters might be reasonable way to go, and one such could be case where you need to get different kinds of entities from single controller.
For an example you could have restful "users/" -route, which fetches all users from UserModel. Next you wish to separate "normal" users and admin-users by having "admin-users/" -route. Now one way to go is to represent both routes to web.php, and make them point to same controller:
Route::resource('users', 'UserController');
Route::resource('admin-users', 'UserController');
One way to solve this separation is by not passing an argument, but by detecting which route was called:
$sqlFilters['user_is_admin'] = $request->is('admin-users') || $request->is('admin-users/*');
This checks whether controller was accessed via "admin-users". Asterisk is wildcard for any route under "admin-users" path.
This method has been existing at least since Laravel 6.0, probably even before that: https://laravel.com/docs/8.x/requests#inspecting-the-request-path
You are doing it wrong. That's not how you work with an MVC framework and it's better not to define a variable or constant in web.php which is for your routes and middlewares only. By the way, if you need to do it this way, you have two ways:
1) Use a trait:
web.php:
trait TestTrait {
public static $my_var = 'some data';
}
Route::get(/login', 'Auth\UserController#login');
UserConroller.php:
use TestTrait;
class UserController extends Controller
{
use TestTrait;
public function login()
{
// You can retrieve it as a variable: $my_var
echo TestTrait::$my_var;
}
}
2) Use a constant instead of a variable:
web.php:
define('MY_VAR', 'some data');
Route::get('/login', 'Auth\UserController#login');
UserConroller.php:
public function login()
{
// You can retrieve it as a constant: MY_VAR
echo MY_VAR;
}
If the variable is hardcoded, why not state it as a constant?
If no other logic is needed, the variable can be passed through the routes file.
$my_var = "some data";
Route::get('/login', function(){
Return view('login', compact('my_var')):
});
I am familiar with Laravel 4 routes, but I am experiencing some problem with Laravel 5.
I code route.php as:
Route::get('/','HomeController#index');
and my HomeController.php is the following:
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
class HomeController extends Controller {
public function index()
{
return View::make('index');
}
}
The output page displays as:
Whoops,looks like something went wrong.
The Route annotation file seems to be perfect.
The same case occurs for folder routing too!!
Please help me out.
First of all you should follow the instructions from James Njuguna in a comment to your question. Withoug debugging we can only guess whats going wrong.
In your case, most likely your error is, that the line
return View::make('index');
is causing an exception, because class App\Http\Controllers\View is not found. In this file a namespace is used, so you have to reference the root namespace like:
return \View::make('index');
OR you use a helper function
return view('index');
This function is documentated at http://laravel.com/docs/5.0/helpers#miscellaneous
If that's still failing... maybe you don't have an index.php or index.blade.php in your resources/views folder.
All, what #shock_gone_wild and #JamesNjuguna said is true. The reason of an error occurring is that you do not use namespaces when you call View.
For testing you can simply return text from a controller like this:
public function index()
{
return 'test'
}
and when it returns a result you can see what was the reason for the error and than you can change it with view global function, like #JamesNjuguna said.
Try this
public function index()
{
return view('home');
}
In laravel 5 the view class is not illuminated using a capital letter at the beginning
<?php
class TasksController extends BaseController {
public function index()
{
return 'show all tasks.';
}
}
?>
That's what I did very simple. But when I go to localhost:8888/tasks
it doesn't show the result it shows Whoops! Something went wrong.
What could possibly be the problem, such a simple code? By the way I just set up Laravel recently.
Controllers don't do anything until you point a route at them, via app/routes.php.
http://laravel.com/docs/routing
Adding:
Route::get('tasks', 'TasksController#index');
is likely to do the trick.
I just started working with Laravel after CodeIgniter and there some things that just confuse me.
I have a PagesController which takes care of displaying static pages such as about, contact, privacy etc'.
Now, instead of creating 3-4 methods on my PagesController, I would like to create one method thats called ShowPage($which) { } and knows which page to display.
The thing is > I can't understand the route issue:
Route::get('about','PagesController#ShowPage'); <--- I need to pass 'about' here
Route::get('contact','PagesController#ShowPage');
Route::get('about','PagesController#ShowPage');
Is that possible or should I need to create a method for each one of these cases?
Here is my exact code:
Controller:
class PagesController extends BaseController {
function showPage($which) {
echo $which;
}
}
Routes:
Route::get('about','PagesController#showPage');
Route::get('contact','PagesController#showPage');
Route::get('about','PagesController#showPage');`
You can access the route directly inside your controller by using
switch(Request::path()){}
which resolves to about, contact etc.
Another way to go about it would be to use
Route::get('{page}', 'PagesController#ShowPage');
which will pass the variable in the controller like
public function showPage($page){}
but be aware that this route will match any path,
if there is not another match above it.
They're already being passed down to the method:
public function ShowPage($which){
switch($which){
case 'about':
// do something
break;
case 'contact':
// do something else
break;
default:
break;
}
}
You may try this:
// In your routes.php (This route will match only this route because of "where")
Route::get('{page}','PagesController#showPage')->where('page', 'about|contact');
If you use http://example.com/about (or contact) it'll work but with other values it won't work, in other words, this route won't match without about or contact.
Then in your controller, try this:
class PagesController extends BaseController {
public function showPage($page) {
// use $page, don't use use switch, $page will be either about or contact
}
}