Laravel - controllers without routing - php

I am newbie to laravel.
I created new controller - book.
This is my code -
class BookController extends BaseController {
public function index()
{
return View::make('book.index');
}
public function insert()
{
return View::make('book.insert');
}
}
My routes.php -
Route::get('book/', 'BookController#index');
//Route::any('book/insert', array('uses' => 'BookController#insert'));
When i uncomment 2nd line, i can access insert page.
Is it possible to access pages without add them to routes.
Now it produce this error

You may read about resource controller.
Execute this on terminal:
php artisan make:controller BookController
This command will generate BookController.php in your app/controllers folder. Read the code for more information.
Define in your routes/web.php file:
Route::resource('book', 'BookController');
Actions Handled By Resource Controller:

Route filters provide a convenient way of limiting access to a given route, which is useful for creating areas of your site which require authentication. So it is better to use route.php as Laravel framework indicates.
you can add filters to there as well, refer documentation

Related

Although I created the route correctly But when I try to show the page It gives me an error page not found

This is my function in MemberController
public function text(){
return "hello";
}
This is my route
Route::get('/text',[MemberController::class,'text']);
So,basically its unable to read new route that i created.
Thanks in advance
Hope you're using laravel 8 and above
follwoing should be your controller code (MemberController.php)
<?php
namespace App\Http\Controllers;
class MemberController extends Controller{
public function text(){
return "hello";
}
}
and this should be your route code (web.php)
<?php
use App\Http\Controllers\MemberController;
Route::get('/text',[MemberController::class,'text']);
Code you have provided is not enough, though you can check following things.
See if your routes aren't cached. Run php artisan route:clear in order to clear the cached routes.
Where have you defined the route? If it's in the web.php file then, your actual url should be: http://localhost:8000/text.
If it's in the api.php file then, your url should be: http://localhost:8000/api/text.

Routes inside controllers with laravel?

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

Laravel controller route

In Laravel 5.1 I was able to create following route:
Route::controller('posts', 'PostsController');
It was very handy, since I could use methods depending on request type:
public function getCreate()
{
// method for getting
}
public function postCreate()
{
// method for creating
}
In Laravel 5.5 it appears that this functionality (HTTP Controllers) has been removed(?) and replaced by HTTP Requests.
Requests are nice, but not that handy.. and it offers way more methods than I need.
Is there a possibility to keep using request-related method names for controllers in Laravel 5.5?
I think you can use Resource Route
Resource Controllers
Laravel resource routing assigns the typical "CRUD" routes to a controller with a single line of code. For example, you may wish to create a controller that handles all HTTP requests for "photos" stored by your application. Using the make:controller Artisan command, we can quickly create such a controller:
php artisan make:controller PhotoController --resource
This command will generate a controller at app/Http/Controllers/PhotoController.php. The controller will contain a method for each of the available resource operations.
Next, you may register a resourceful route to the controller:
Route::resource('photos', 'PhotoController');
This single route declaration creates multiple routes to handle a variety of actions on the resource. The generated controller will already have methods stubbed for each of these actions, including notes informing you of the HTTP verbs and URIs they handle.
Actions Handled By Resource Controller
Ref:
https://laravel.com/docs/5.5/controllers#resource-controllers
Route::controller() was eliminated after Laravel 5.3
Route::resource() is very specific to exactly, only create for you and let you access the seven methods to CRUD an object
If you want to create your own views, I believe you have to define all them with Route::get(), Route::post(), etc. in the routes/web file

url in routes.php not rendering in laravel 4

I am new to laravel. I am just trying to do some basic stuff using routes and controllers.
I have this controller named testcontroller which looks as below
<?php
class testcontroller extends BaseController{
public function show(){
return 'test';
}
}
I have also defined a route in routes.php as below
Route::get('test', 'testcontroller#show');
when i try to access it using localhost/laravel/public/test it would give the 404 NOT FOUND error, however i have tried rewriting the route in main directory as
Route::get('/', 'testcontroller#show');
and it works all fine, i have even tried and successfully rendered views using this. Can anyone suggest where am i going wrong with the url. Any help will be appreciated.
Thanks :)
Test controller
# app/controllers/TestController.php
class TestController extends BaseController {
public function show()
{
return 'test';
}
}
Routes File
# app/routes.php
Route::get('test', array(
'uses' => 'TestController#show'
));
Route::get('/', array(
'uses' => 'TestController#show'
));
Edit: since that is not working, it is probably to do with your server configuration. Instead of learning how to do that, I'd recommend the use of a VM over WAMP. Also Laravel provides an easy way to use one with Laravel Homestead.
Check out this instructional video on how to do that.

Laravel Controller doesn't exist, even though it clearly exists

The error I'm getting is that the controller doesn't exist even though I know it does, here's the code.
Route.php
Route::get('mdpay/template', array("uses" => "templateController#index"));
templateController.blade.php
class templateController extends BaseController {
public function index()
{
echo "made it";
}
}
Why might I be getting this error: Class TemplateController does not exist
================= UPDATE: ==================
Ok, so I've created the correct route, renamed my file, and corrected the class name and I'm still coming up with that error.
File Names:
templateController.php
// File Name: TemplateController.php
class TemplateController extends BaseController {
public function index()
{
// app/views/myView.blade.php
echo "hello";
}
}
My route is:
Route::get('mdpay/template', array("uses" => "TemplateController#index"));
Still receiving Controller Doesn't Exist error. All my other controllers (3 others) are working except this one.
If you are using the standard composer classmap autoloader you need to composer dumpautoload everytime you create a new file.
So to create a new controller with the standard composer setup given by Laravel:
Create a new file in app/controllers named TemplateController.php
Open up terminal and run composer dumpautoload
As previous users have said, only view files should end with .blade.php.
If you're using Laravel 8, add this line to your RouteServiceProvider.php (you can search it by using CTRL + P):
protected $namespace = 'App\Http\Controllers';
This solved the issue for me.
It should be:
// File Name: TemplateController.php
class TemplateController extends BaseController {
public function index()
{
// return "made it"; // or
// app/views/myView.blade.php
return View::make('myView');
}
}
Route for that:
Route::get('mdpay/template', array("uses" => "TemplateController#index"));
Use blade in a Blade view, i.e: myView.blade.php basically stored in app/views/ folder. Read more about blate template on Laravel website.
Controllers live in the app/controllers directory and should remain there unless you have your own namespaced structure.
The reason you're getting a Class TemplateController does not exist is because it doesn't, firstly, your class is called templateController and secondly, it exists as templateController.blade.php which wouldn't be loaded in this way.
Blade files are for views, and only views within app/views or a custom views directory should end with .blade.php.
Create the file app/controllers/TemplateController.php and add the following code to it.
class TemplateController extends BaseController {
public function index()
{
echo "made it";
}
}
Now on the command line, run the command composer dumpautoload and change you route declaration to:
Route::get('mdpay/template', array('uses' => 'TemplateController#index"));
Now it should all work.
In case you're using Laravel 9 and the error is like Illuminate\Contracts\Container\BindingResolutionException and Target class <controller name> does not exist. when trying php artisan route:list on terminal.
This is the setup that I do:
Add protected $namespace = 'App\\Http\\Controllers'; to RouteServiceProvider.php
Add 'namespace App\Http\Controllers;' to the controller file.
Do php artisan optimize on terminal
(Just to make sure the route already there) Do php artisan route:list again on terminal, and the controller route should be displayed.

Categories