Related
I'm trying to set up a basic Laravel 9 CRUD application, and I cannot get the edit route working for the User Controller.
routes/web.php
Route::get('/dashboard', function () { return view('dashboard'); })
->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{$id}/edit','edit')->middleware('auth');
Route::post('user/{$id}/edit','update')->middleware('auth');
Route::get('user/{$id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
UserController.php
class UserController extends Controller
{
function edit(int $id)
{
echo 123;
}
I'm getting a 404 NOT FOUND page
Also, why don't I see the stack trace for this error?
Also, in some examples, I've seen people using the model class name as the parameter type in the controller method declaration, such as:
function edit(User $id)
{
echo 123;
}
However, I've also seen other examples using int instead. So which is the correct one?
First, inside your .env filte you should put
APP_ENV=local
APP_DEBUG=true
and change your web.php to:
<?php
use Illuminate\Support\Facades\Route;
Route::get('/dashboard', function () { return view('dashboard'); })->middleware(['auth'])->name('dashboard');
use App\Http\Controllers\UserController;
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
require __DIR__.'/auth.php';
Then, try to run
php artisan route:list
and check if your routes are correct.
And try to remove middlewares inside user files, maybe you do not have login page and it redirects you there.
Be sure you are in the correct url like localhost/user/1/edit
Parameters in routes don't take a starting $. Change all occurrences of {$id} in your routes to just {id}:
Route::controller(UserController::class)->group(function(){
Route::get('user','index')->middleware('auth')->name('cases');
Route::get('user/create','create')->middleware('auth');
Route::post('user/create','store')->middleware('auth');
Route::get('user/{id}/edit','edit')->middleware('auth');
Route::post('user/{id}/edit','update')->middleware('auth');
Route::get('user/{id}/delete','destroy')->middleware('auth');
Route::get('user/{id}','show')->middleware('auth');
});
More on Route Parameters
Edit: you might also want to take a look at Resource Controllers. Something like Route::resource('users', UserController::class); will manage all of the required routes
I have a file called: test.php located in public/inc/test.php. Through jQuery, I can make a get request through jQuery ($.get), by typing:URL: "public/inc/test.php?" + param1` etc.
I want to do the same, but through Laravel. I want to have a route called: /sendparams/{param1}/{param2}, and do a get request to the test.php file from inside a route in web.php and pass the params variables.
How should the route be written?
edit:
by implementing the classes in laravel as external classes, this is no more needed.
you have in your laravel project a file named web.php inside the routes folder.
Define within the web.php file the below code:
Route::get('/sendparams/{param1}/{param2}', 'ControllerName#index');
Perform the below command to create the controller
php artisan make:controller ControllerName
Open ControllerName (app/Http/Controllers/ControllerName)
Your new controller has an structure like this:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class MailController extends Controller
{
public function __construct()
{
}
/* This is the method executed in your route defined in web.php*/
public function index(Request $request) {
$param1 = $request->param1;
$param2 = $request->param2;
$allParams = $request->all(); // returns an associative array with all params
}
}
you can check your routes performed the below command
php artisan route:list
Regards
I began to study Laravel, I have this problem.
File: project/app/Http/routes.php
<?php
Route::get('about', 'PagesController#about');
In the directory project I do by terminal
php artisan make:controller PagesController
File: project/app/Http/Controllers/PagesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class PagesController extends Controller
{
public function about()
{
return("About");
}
}
You need to enter in apache configuration file and specify AllowOverride Yes on the directory where laravel still working
You are accessing your / route in your provided image. Which is not defined in your routes.php file that's why you are getting this error.
Add
Route::get('/', function() {
return "hello world";
});
and then try this route: 192.168.1.101/laravel-p/public/
Note you've explained the about route in your above code. So hit this route
`192.168.1.101/laravel-p/public/about`
You are accessing your / route in your provided image. Which is not
defined in your routes.php file that's why you are getting this error.
Add
Route::get('/', function() {
return "hello world"; });
and then try this route: 192.168.1.101/laravel-p/public/
Note you've explained the about route in your above code. So hit this
route
192.168.1.101/laravel-p/public/about
Nothing..
enter image description here
<?php
Route::get('/', function() {
return "hello world";
});
Route::get('about', 'PagesController#about');
I added new controller in /app/controllers/admin/ folder and added the route in /app/routes.php file as well. Then i run the following command to autoload them
php artisan dump-autoload
I got the following error
Mcrypt PHP extension required.
I followed instruction given at https://askubuntu.com/questions/460837/mcrypt-extension-is-missing-in-14-04-server-for-mysql and able to resolve the mcrypt issue.
After that i run the php artisan dump-autoload command but still getting following error
{"error":{"type":"ReflectionException","message":"Class CoursesController does not exist","file":"\/var\/www\/html\/vendor\/laravel\/framework\/src\/Illuminate\/Container\/Container.php","line":504}}
Here is code of my routes.php file
Route::group(array('before' => 'adminauth', 'except' => array('/admin/login', '/admin/logout')), function() {
Route::resource('/admin/courses', 'CoursesController');
Route::resource('/admin/teachers', 'TeachersController');
Route::resource('/admin/subjects', 'SubjectsController');
});
Here is code of CoursesController.php file
<?php
class CoursesController extends BaseController
{
public function index()
{
$courses = Course::where('is_deleted', 0)->get();
return View::make('admin.courses.index', compact('courses'));
}
public function create()
{
return View::make('admin.courses.create');
}
public function store()
{
$validator = Validator::make($data = Input::all(), Course::$rules);
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
Course::create($data);
return Response::json(array('message'=>'Course created successfully','status'=>'success'));
}
}
public function edit($id)
{
$course = Course::find($id);
return View::make('admin.courses.edit', compact('course'));
}
public function update($id)
{
$course = Course::findOrFail($id);
$validator = Validator::make($data = Input::all(), Course::editRules($id));
if ($validator->fails()) {
$messages = $validator->messages();
$response = '';
foreach ($messages->all(':message') as $message) {
$response = $message;
}
return Response::json(array('message'=>$response, 'status'=>'failure'));
} else {
$course->update($data);
return Response::json(array('message'=>'Course updated successfully','status'=>'success'));
}
}
public function destroy($id)
{
Course::findOrFail($id)->update(array('is_deleted' => '1'));
return Response::json(array('message'=>'Course deleted successfully','status'=>'success'));
}
}
Did you add autoload classmap to composer.json file?
Open your composer.json file and add
"autoload": {
"classmap": [
"app/controllers/admin",
]
}
if you add folders inside controllers, you need to add it to composer.json file. Then run
composer dumpautoload
OR ALTERNATIVE
go to app/start/global.php and add
ClassLoader::addDirectories(array(
app_path().'/controllers/admin',
));
2021 answer (Laravel 8.5)
In your controller;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Providers\RouteServiceProvider;
use Illuminate\Http\Request;
class AuthController extends Controller
{
public function login(Request $request){
return "login";
}
}
In your routes;
use App\Http\Controllers\AuthController;
Route::post('/login', [AuthController::class, 'login']);
Doc = https://laravel.com/docs/8.x/routing#the-default-route-files
In my case, in the top of my controller code i add this line :
namespace App\Http\Controllers\CustomFolder\ControllerClassName;
and my problem is solved
We can create controller via command line.
php artisan make:controller nameController --plain.
Before Laravel 5, make namespace is not available. Instead, this works
php artisan controller:make nameController
Execute your command inside your project directory and then create your function.
Don't forget to do:
php artisan route:clear
In my case this was the solution when I got this error after making a route code change.
In my case, I had to change the route file from this:
Route::get('/','SessionController#accessSessionData');
to this:
Route::get('/','App\Http\Controllers\SessionController#accessSessionData');
then clearing the cache with this:
php artisan route:clear
made things work.
A bit late but in my experience adding this to the RouteServiceProvider.php solves the problem
protected $namespace = 'App\Http\Controllers';
I think your problem has already been fixed. But this is what did.
Structure
Http
.Auth
.CustomControllerFolder
-> CustomController.php
to get this working
in your route file make sure you use the correct name space
for eg:
Route::group(['namespace'=>'CustomControllerFolder','prefix'=>'prefix'],
function() {
//define your route here
}
Also dont forget to use namespace App\Http\Controllers\CustomControllerFolder in your controller.
That should fix the issue.
Thanks
I just had this issue because I renamed a file from EmployeeRequestContoller to EmployeeRequestsContoller, but when I renamed it I missed the .php extension!
When I reran php artisan make:controller EmployeeRequestsContoller just to be sure I wasn't going crazy and the file showed up I could clearly see the mistake:
/EmployeeRequestsContoller
/EmployeeRequestsContoller.php
Make sure you have the extension if you've renamed!
I use Laravel 9 this is the way we should use controllers
use App\Http\Controllers\UserController;
Route::get('/user', [UserController::class, 'index']);
Sometimes we are missing namespace App\Http\Controllers; on top of our controller code.
In my case, I have several backup files of admin and home controllers renamed with different dates and we ran a composer update on top of it and it gave us an error
after I removed the other older controller files and re-ran the composer update fixed my issue.
- Clue - composer update command gave us a warning.
Generating optimized autoload files
Warning: Ambiguous class resolution, "App\Http\Controllers\HomeController" was found in both "app/core/app/Http/Controllers/HomeController(25-OCT).php" and "app/core/app/Http/Controllers/HomeController.php", the first will be used.
Warning: Ambiguous class resolution, "App\Http\Controllers\AdminController" was found in both "app/core/app/Http/Controllers/AdminController(25-OCT).php" and "app/core/app/Http/Controllers/AdminController.php", the first will be used.
Use full namespace inside web.php
Route::resource('myusers','App\Http\Controllers\MyUserController');
I'm new to Laravel. To try and keep my app organized I would like to put my controllers into subfolders of the controller folder.
controllers\
---- folder1
---- folder2
I tried to route to a controller, but laravel doesn't find it.
Route::get('/product/dashboard', 'folder1.MakeDashboardController#showDashboard');
What am I doing wrong?
For Laravel 5.3 above:
php artisan make:controller test/TestController
This will create the test folder if it does not exist, then creates TestController inside.
TestController will look like this:
<?php
namespace App\Http\Controllers\test;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class TestController extends Controller
{
public function getTest()
{
return "Yes";
}
}
You can then register your route this way:
Route::get('/test','test\TestController#getTest');
Add your controllers in your folders:
controllers\
---- folder1
---- folder2
Create your route not specifying the folder:
Route::get('/product/dashboard', 'MakeDashboardController#showDashboard');
Run
composer dump-autoload
And try again
For those using Laravel 5 you need to set the namespace for the controller within the sub-directory (Laravel 5 is still in development and changes are happening daily)
To get a folder structure like:
Http
----Controllers
----Admin
PostsController.php
PostsController.php
namespace Admin\PostsController.php file like so:
<?php namespace App\Http\Controller\Admin;
use App\Http\Controllers\Controller;
class PostsController extends Controller {
//business logic here
}
Then your route for this is:
$router->get('/', 'Admin\PostsController#index');
And lastly, don't for get to do either composer or artisan dump
composer dump-autoload
or
php artisan dump
For ** Laravel 5 or Laravel 5.1 LTS both **, if you have multiple Controllers in Admin folder, Route::group will be really helpful for you. For example:
Update: Works with Laravel 5.4
My folder Structure:
Http
----Controllers
----Api
----V1
PostsApiController.php
CommentsApiController.php
PostsController.php
PostAPIController:
<?php namespace App\Http\Controllers\Api\V1;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostApiController extends Controller {
...
In My Route.php, I set namespace group to Api\V1 and overall it looks like:
Route::group(
[
'namespace' => 'Api\V1',
'prefix' => 'v1',
], function(){
Route::get('posts', ['uses'=>'PostsApiController#index']);
Route::get('posts/{id}', ['uses'=>'PostssAPIController#show']);
});
For move details to create sub-folder visit this link.
1.create your subfolder just like followings:
app
----controllers
--------admin
--------home
2.configure your code in app/routes.php
<?php
// index
Route::get('/', 'Home\HomeController#index');
// admin/test
Route::group(
array('prefix' => 'admin'),
function() {
Route::get('test', 'Admin\IndexController#index');
}
);
?>
3.write sth in app/controllers/admin/IndexController.php, eg:
<?php
namespace Admin;
class IndexController extends \BaseController {
public function index()
{
return "admin.home";
}
}
?>
4.access your site,egļ¼localhost/admin/test
you'll see "admin.home" on the page
ps: Please ignore my poor English
In Laravel 5.6, assuming the name of your subfolder' is Api:
In your controller, you need these two lines:
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
And in your route file api.php, you need:
Route::resource('/myapi', 'Api\MyController');
Just found a way how to do it:
Just add the paths to the /app/start/global.php
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/controllers/product',
app_path().'/models',
app_path().'/database/seeds',
));
php artisan make:controller admin/CategoryController
Here
admin is sub directory under app/Http/Controllers and
CategoryController is controller you want to create inside directory
I am using Laravel 4.2. Here how I do it:
I have a directory structure like this one:
app
--controllers
----admin
------AdminController.php
After I have created the controller I've put in the composer.json the path to the new admin directory:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin",
"app/models",
"app/database/migrations",
"app/database/seeds",
"app/tests/TestCase.php"
]
},
Next I have run
composer dump-autoload
and then
php artisan dump-autoload
Then in the routes.php I have the controller included like this:
Route::controller('admin', 'AdminController');
And everything works fine.
If you're using Laravel 5.3 or above, there's no need to get into so much of complexity like other answers have said.
Just use default artisan command to generate a new controller.
For eg, if I want to create a User controller in User folder.
I would type
php artisan make:controller User/User
In routes,
Route::get('/dashboard', 'User\User#dashboard');
doing just this would be fine and now on localhost/dashboard is where the page resides.
Hope this helps.
1) That is how you can make your app organized:
Every route file (web.php, api.php ...) is declared in a map() method, in a file
\app\Providers\RouteServiceProvider.php
When you mapping a route file you can set a ->namespace($this->namespace) for it, you will see it there among examples.
It means that you can create more files to make your project more structured!
And set different namespaces for each of them.
But I prefer set empty string for the namespace ""
2) You can set your controllers to rout in a native php way, see the example:
Route::resource('/users', UserController::class);
Route::get('/agents', [AgentController::class, 'list'])->name('agents.list');
Now you can double click your controller names in your IDE to get there quickly and conveniently.
I think to keep controllers for Admin and Front in separate folders, the namespace will work well.
Please look on the below Laravel directory structure, that works fine for me.
app
--Http
----Controllers
------Admin
--------DashboardController.php
------Front
--------HomeController.php
The routes in "routes/web.php" file would be as below
/* All the Front-end controllers routes will work under Front namespace */
Route::group(['namespace' => 'Front'], function () {
Route::get('/home', 'HomeController#index');
});
And for Admin section, it will look like
/* All the admin routes will go under Admin namespace */
/* All the admin routes will required authentication,
so an middleware auth also applied in admin namespace */
Route::group(['namespace' => 'Admin'], function () {
Route::group(['middleware' => ['auth']], function() {
Route::get('/', ['as' => 'home', 'uses' => 'DashboardController#index']);
});
});
Hope this helps!!
This is for laravel 9.
Organize your controllers in subfolder as you wish:
controller
---folder-1
------controllerA
------controllerB
---folder-2
------controllerC
------controllerD
use the controllers in the route file
use App\Http\controllers\folder-1\controllerA;
.....etc
Write your routes as normal
Route::get('/xyz', [controllerA::class, 'methodName']);
I had this problem recently with laravel 5.8 but i underestand I should define controller in a right way like this below:
php artisan make:controller SubFolder\MyController // true
Not like this:
php artisan make:controller SubFolder/MyController // false
Then you can access the controller in routes/web.php like this:
Route::get('/my', 'SubFolder\MyController#index');
In my case I had a prefix that had to be added for each route in the group, otherwise response would be that the UserController class was not found.
Route::prefix('/user')->group(function() {
Route::post('/login', [UserController::class, 'login'])->prefix('/user');
Route::post('/register', [UserController::class, 'register'])->prefix('/user');
});
Create controller go to cmd and the type
php artisan make:controller auth\LoginController