Can someone please tell me how to make my "Page not found" or something messages? For example if someone writes a link in the browser which do not exist in my project, not to show the standard error page ( Woops, something went wrong, View [bla.bla] not found ) but page specified by me?
<?php
Route::get('sendemail', 'EmailController#sendEmail');
Route::get('test', 'AuthController#getTest');
Route::get('napravisiadmin', 'ClassbookController#getIndex');
Route::group(['middleware' => ['web']], function () {
Route::group(['middleware' => ['guest']
], function () {
Route::get('login', 'AuthController#getLogin');
Route::post('login', 'AuthController#postLogin');
});
Route::get('logout', 'AuthController#getLogout');
//Admin
Route::group(['middleware' => ['auth', 'auth.admin']
], function () {
Route::group([
'prefix' => 'admin',
'namespace' => 'Admin'
], function () {
Route::controller('student', 'StudentsController');
Route::controller('profile', 'ProfilesController');
Route::controller('class', 'ClassesController');
Route::controller('subjects', 'SubjectsController');
Route::controller('teacher', 'TeachersController');
Route::controller('marktype', 'MarkTypeController');
Route::controller('rules', 'RuleController');
Route::get('{slug?}', 'PageController#getView');
});
});
//Admin
//Student
Route::group([
'middleware' => ['auth', 'auth.student'],
'prefix' => 'stu',
'namespace' => 'Stu'
], function () {
Route::get('{slug?}', 'StuController#getView');
});
//Student
//Teacher
Route::group([
'middleware' => ['auth', 'auth.teacher'],
'prefix' => 'educator',
'namespace' => 'Educator'
], function () {
Route::get('edit/{id}', 'AccountController#getEdit');
Route::post('edit/{id}', 'AccountController#saveEdit');
Route::get('account', 'AccountController#getView');
Route::get('class-subject', 'AccountController#getClassSubject');
Route::get('add-mark', 'AccountController#getAddMark');
Route::post('mark', 'AccountController#postAddMark');
Route::get('added', 'AccountController#marksList');
Route::get('statistics', 'AccountController#marksInTable');
Route::get('personalemails', 'PersonalEmailController#getView');
Route::post('personalemails', 'PersonalEmailController#personalEmail');
});
//Teacher
});
Route::get('{slug?}', 'PageController#getView');
For the "Page not found" 404 error create a view in resources/views/errors/404.blade.php and it will show when you get a 404 error.
From the documentation:
Custom HTTP Error Pages
Laravel makes it easy to return custom error pages for various HTTP
status codes. For example, if you wish to customize the error page for
404 HTTP status codes, create a resources/views/errors/404.blade.php.
This file will be served on all 404 errors generated by your
application.
The views within this directory should be named to match the HTTP
status code they correspond to.
https://laravel.com/docs/5.2/errors#custom-http-error-pages
You can always go a step further by utilising the exception handler and handling exceptions the way you desire by customising the render() method
https://laravel.com/docs/5.2/errors#the-exception-handler
For example, if you wanted to handle file not found error, Exceptions\Handler.php
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException) {
return response()->view('errors/exceptions/file-not-found', [], 500);
}
return parent::render($request, $e);
}
You can create custom error 404 page. If someone will enter wrong URL in a browser, he will see that page.
Also, you can redirect user manually to this page with:
abort(404);
Update
I guess the problem is here:
Route::get('{slug?}', 'PageController#getView');
You're using this three times, try to remove all of them.
The thing is when Laravel doesn't find any routes, it takes {slug} and passes it to the PageController, so when you enter http://example.com/sometext, you will be transferred to the PageController with slug = sometext.
If you do not want to remove it, check for slug inside a controller and if slug means something - good. If not, just abort(404); and user will be transferred to an error page.
Also, if you're on 5.2.27 of higher, remove web middleware from routes.php (it applies automatically, and manual apply can cause errors and strage behavior).
Related
I'm trying to restrict the access of routes to only some types of users in my site that I'm writing with Laravel 5.7, right now I'm trying to do it with middlewares.
For each user's level I have a middleware with this code(with a variation on the type):
public function handle($request, Closure $next)
{
if(Auth::user()->type==3)
return $next($request);
else
return redirect()->route('dashboard');
}
And in the kernel.php file, I have them written like this:
protected $routeMiddleware = [
...
'teacher' => \App\Http\Middleware\RedirectIfTeacher::class,
...
]
In my application each user has a level, which starts from 1 to 5, but each level has individual views and some shared views, but I can't manage to redirect views for more than just one type of user because I can't make them work when I use more than one middlewares on a route (or routes) that are shared with more than two types of users.
When I try it justs ignores the second or more middlewares and redirects to the route dashboard which is the route for redirecting if the type of user can't enter the desired view.
Right now I've tried with this code:
Route::group(['middleware' => ['administrator','teacher','student']], function(){
And with this code:
Route::group(['middleware' => ['administrator' OR 'teacher' OR 'student']], function(){
Also I tried with this style:
Route::group(['middleware' => ['administrator|teacher|student']], function(){
Without getting any luck, is there anything what am I doing wrong? or is there a better way to do what I'm trying to achieve, thanks in advance!.
I'm using below code and it worked:
Route::group(['middleware' => ['administrator','teacher','student']], function() {});
1 In the kernel.php file, have you got all of the keys assigned with your middlewares ? For example:
protected $routeMiddleware = [
...
'administrator' => \App\Http\Middleware\RedirectIfAdmin::class,
'teacher' => \App\Http\Middleware\RedirectIfTeacher::class,
'student' => \App\Http\Middleware\RedirectIfStudent::class,
...
]
2 Try to check the user vars before the if in your handle().
dd(Auth::user()->type);
You need to pass an array to it I guess
Route::group(['middleware' => ['administrator','teacher','student']], function() {});
If that doesn't work you have to split them I guess
Route::group(['middleware' => 'administrator'], function () {
Route::group([ 'middleware' => 'teacher'], function() {
Route::group([ 'middleware' => 'student'], function() {
});
});
});
My application will have doctors, patients and administrators
Now I would like to have the same route for all roles. as following:
app.com/dashboard/
app.com/dashboard/appointments
But I would like to have a different Controller for the one used for patients, and the one for doctors offcourse. I have tried the following without success
Route::group(['prefix' => 'dashboard', 'middleware' => ['auth']], function () {
/* Doctor */
Route::group(['middleware' => ['role:doctor']], function() {
Route::get('/appointments', 'Doctor\AppointmentController#index');
});
/* Patient */
Route::group(['middleware' => ['role:patient']], function() {
Route::get('/appointments', 'Patient\AppointmentController#index');
});
});
I get an 403 (Unauthorized) error caused by my Role middleware. Even without that I think it's just overwriting the other?
Has anyone been able to use the same route (/dashboard) for completely different purposed? aka different controllers/views
Thank you!
You can use a workaround for this by checking the user role and then call the controller function accordingly as:
Route::get('appointment', function()
{
if (auth()->user()->isDoctor())
{
app()->call('Doctor\AppointmentController#index')
}
elseif(auth()->user()->isPatient())
{
app()->call('Patient\AppointmentController#index')
}
});
I'm using Laravel 5.2. I want to check user session in routes file, so that if session is set user can visit dashboard otherwise redirect to login page.
I have used following code for this but it's not working. It's not giving any error and not redirecting him to login page. anyhow if I write same code in controller functioin, it works fine.
Route::group(['middleware' => ['web']], function () {
Route::get('dashboard/index', ['uses' => 'DashboardController#index'], function() {
$value = $request->session()->get('name', 'not_loggin');
if ($value == 'not_loggin') {
return redirect('/user/login');
}
});
});
it also didn't worked if I write it in constructor.
You should use the auth middleware:
Route::get('dashboard/index', [
'middleware' => 'auth',
'uses' => 'DashboardController#index'
]);
I'm using Laravel 5.1 and wanted to know if there is a better way to do routing redirection.
Route::get('user/login', 'UserController#login');
Route::get('login', function() {
return redirect()->to('user/login');
});
So basically, whenever a user goes to http://example.com/login, they will be redirect to http://example.com/user/login.
Is there a better way or other ways to do this or am I doing it correctly already? Thanks!
That's about as simple as it gets
You could also do redirect('user/login') to save a few characters
If you had multiple redirects like this you could handle them all at once
Route::pattern('user_path', '(login|logout)');
Route::get('{user_path}', function($user_path) {
return redirect('user/' . $user_path);
});
Route::get('new/create_view','CreateController#create_view');
Route::post('new/create_view','CreateController#insert_view');
Route::get('new/create_table','CreateController#create_table');
Route::post('new/create_table','CreateController#insert_table');
Route::get('new/create_package','CreateController#create_package');
Route::post('new/create_package','CreateController#insert_package');
This is the way i am using the route. Simple method. when the time of GET, am calling a controller function and inside that particular controller function, i have written the logical codes. In the POST also, doing the same thing.
Another way is there,GROUP Routing
Route::group(['namespace' => 'Admin'], function()
{
// Controllers Within The "App\Http\Controllers\Admin" Namespace
Route::group(['namespace' => 'User'], function()
{
// Controllers Within The "App\Http\Controllers\Admin\User" Namespace
});
});
eg:
Route::group(array('prefix' => 'api/v1', 'before' => 'auth.basic'), function()
{
Route::resource('pages', 'PagesController', array('only' => array('index', 'store', 'show', 'update', 'destroy')));
Route::resource('users', 'UsersController');
});
So the error I am getting is Symfony \ Component \ HttpKernel \ Exception \ NotFoundHttpException.
Here is the route:
Route::get('/', 'AuthController#index');
Route::get('/login', 'AuthController#login');
Route::post('/login', ['before' => 'csrf', 'uses' => 'AuthController#authenticate']);
Route::get('/logout', 'AuthController#logout');
Route::group(['before' => 'auth'], function() {
$noIndex = [ 'except' => ['index'] ];
$noShow = [ 'except' => ['show'] ];
Route::get('/dashboard', 'PagesController#dashboard');
Route::get('/test', 'MessageController#index');
Here is the controller:
/**
* Display a listing of the resource.
* GET /test
*
* #return Response
*/
public function index()
{
return View::make('test.index');
}
Now that we have some more complete information regarding your routes.php setup, it's possible that the problem is due to the auth filter.
(I'm assuming you left off the final }); from your routes.php above.)
Try removing the before filter (or change it temporarily to ['before' => 'none']) and reload desk.dev:8000/test. Make sure you don't simply hit reload on the current error page, since it may be pointing to desk.dev:8000/login.
If your AuthController is not set up, or is missing the login method, you will get a NotFoundHttpException when the auth filter in filter.php tries to redirect to your login page, with:
return Redirect::guest('login');