Laravel Put Route Giving 404 Error - php

So I have been trying to use the "put" method in my routing, I have followed this example directly from the "routes.php" file:
Route::put('hello/(:any)', function($name)
{
return "Welcome, $name.";
});
This returns a 404 error, I really want my code to look like below. I want to be able to take to parameters from the url and use them for verification, later on I plan to use an encoding method but for now I just wanted to get the routes working properly before I tried encoding them. Any help would be greatly appreciated!!!
Route::put('admin/activate/(:any?)/(:any?)', function($r, $e) {
return "Random value: $r <br/> Email: $e";
});
You can find the page here: http://diverseevolution.com/admin/activate/randomstring/test#gmail.com
Here is my overall "routes.php" file:
Route::get('/', function() {
return View::make('homepage.index');
});
///////////////////////////////////////////////////////////////////////////////////////////
/////////////// Administration Account Creation & Login /////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
// Create account
Route::get('admin/createform', function() {
return View::make('admin.createform');
});
// action for actual admin creation
Route::post('admin/create', array('before' => 'csrf', function() {
$rules = array(
'fname' => 'required|min:3',
'lname' => 'required|min:3',
'email' => 'required|email|unique:users',
'pword' => 'required'
);
$validated = Validator::make(Input::all(), $rules);
if($validated -> fails()) {
return Redirect::to('admin/createform')->with_input();
} else {
$r = Hash::make(time() .'ReAl19dk4-^4$'. $_POST['pword']);
$user = new User;
$user -> fname = $_POST['fname'];
$user -> lname = $_POST['lname'];
$user -> email = $_POST['email'];
$user -> pword = Hash::make($_POST['pword']);
$user -> status = 'unactivated';
$user -> random = $r;
if($user -> save()) {
//////////////////////// Email /////////////////////////////////
// We still need to make this functionality
$msg = '
<h1>Your admin account has been created!</h1>
<p>Congratulations on creating your new account, there is one last step before your account can be activated. Below is a link, simply follow the link to activate your account, once you have your account will be active and you will be able to login!</p>
<p>http://diverseevolution.com/admin/activate/'. $r .'/'. $_POST['email'] .'</p>
<p>Thanks, Diverse Evolution</p>
';
// Mail headers
$headers = "Reply-To: Diverse Evolution <info#diverseevolution.com>\r\n";
$headers .= "Return-Path: Diverse Evolution <info#diverseevolution.com>\r\n";
$headers .= "From: Diverse Evolution <info#diverseevolution.com>\r\n";
$headers .= "Organization: Diverse Evolution\r\n";
$headers .= 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "X-Priority: 3\r\n";
$headers .= "X-Mailer: PHP". phpversion() ."\r\n";
define('_headers', $headers);
if(mail($_POST['email'], 'Diverse Evolution Account Created', $msg, _headers)) {
return Redirect::to('admin/thanks');
} else {
}
} else {
return Redirect::to('admin/createform')->with_input();
}
}
}));
// creates the thank you page for the admin account creation
Route::get('admin/thanks', function() {
return View::make('admin/thanks');
});
// account activation email, this is still not working 011613
Route::put('admin/activate/(:any?)/(:any?)', function($r, $e) {
return "Random value: $r <br/> Email: $e";
});
// Login form
Route::get('admin/loginform', function() {
return View::make('admin/loginform');
});
// Login action
Route::post('admin/login', array('before' => 'csrf', function() {
$rules = array(
'email' => 'required|email',
'pword' => 'required'
);
$validated = Validator::make(Input::all(), $rules);
if($validated -> fails()) {
return Redirect::to('admin/loginform')->with_input();
} else {
$credentials = array('username' => $_POST['email'], 'password' => $_POST['pword']);
if (Auth::attempt($credentials)) {
return Redirect::to('admin/dash');
} else {
return Redirect::to('admin/loginform')->with_input();
}
}
}));
Route::get('admin/logout', function() {
Auth::logout();
return Redirect::to('admin/loginform');
});
///////////////////////////////////////////////////////////////////////////////////////////
/////////////////////// Administration Pages ////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////
Route::group(array('before' => 'auth'), function() {
Route::get('admin/dash', function() {
return 'Dashboard';
});
});
/*
|--------------------------------------------------------------------------
| Application 404 & 500 Error Handlers
|--------------------------------------------------------------------------
|
| To centralize and simplify 404 handling, Laravel uses an awesome event
| system to retrieve the response. Feel free to modify this function to
| your tastes and the needs of your application.
|
| Similarly, we use an event to handle the display of 500 level errors
| within the application. These errors are fired when there is an
| uncaught exception thrown in the application.
|
*/
Event::listen('404', function()
{
return Response::error('404');
});
Event::listen('500', function()
{
return Response::error('500');
});
/*
|--------------------------------------------------------------------------
| Route Filters
|--------------------------------------------------------------------------
|
| Filters provide a convenient method for attaching functionality to your
| routes. The built-in before and after filters are called before and
| after every request to your application, and you may even create
| other filters that can be attached to individual routes.
|
| Let's walk through an example...
|
| First, define a filter:
|
| Route::filter('filter', function()
| {
| return 'Filtered!';
| });
|
| Next, attach the filter to a route:
|
| Route::get('/', array('before' => 'filter', function()
| {
| return 'Hello World!';
| }));
|
*/
Route::filter('before', function()
{
// Do stuff before every request to your application...
});
Route::filter('after', function($response)
{
// Do stuff after every request to your application...
});
Route::filter('csrf', function()
{
if (Request::forged()) return Response::error('500');
});
Route::filter('auth', function()
{
if (Auth::guest()) return Redirect::to('admin/loginform');
});

You didnt include your form - but I'm guessing you didnt include a "PUT" in the form.
echo Form::open('user/profile', 'PUT');
You can see more about forms and PUT here. But in general, you need to specifically include PUT in your form, otherwise it will just be POST (browser default).

Using GET works?
or
Route::put('hello/(:all)', function($name)
{
return "Welcome, $name.";
});
all becouse #

Related

Laravel 7: Verify email using API endpoint + single page application

I have a NuxtJS/Vue SPA and I want to verify the user email with the Laravel API that's my server side.
I create a custom notification called VerifyEmail.php:
<?php
namespace App\Notifications;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Lang;
use Illuminate\Notifications\Notification;
class VerifyEmail extends Notification {
public function via($notifiable) {
return ['mail'];
}
public function toMail($notifiable) {
$params = [
'id' => $notifiable->getKey(),
'hash' => sha1($notifiable->getEmailForVerification()),
'expiry' => Carbon::now()->addMinutes(60)->timestamp
];
$url = config('app.web_client_url') . '/verify-email?';
foreach ($params as $key => $param) {
$url .= "{$key}={$param}&";
}
$key = config('app.key');
$signature = hash_hmac('sha256', $url, $key);
$url .= "signature=$signature";
return (new MailMessage)
->subject(Lang::get('Verify Email Address'))
->line(Lang::get('Please click the button below to verify your email address.'))
->action(Lang::get('Verify Email Address'), $url)
->line(Lang::get('If you did not create an account, no further action is required.'));
}
}
In my registration controller when a user registers I use:
...
$user->save();
$user->notify(new VerifyEmail());
return response()->json([
'message' => $user
], 201);
and the email gets sent. The URL in the email is something like: https://localhost:7000/verify-email?id=37&hash=4c1691e6db623b85d90cee62f80d6f9085648c92&expiry=1595596017&signature=d6c6374b203b1da66d11818728921a4160e30ebf43c5a8be544220c8eca97bb3 (localhost:7000 is the address of my NuxtJS application).
Upon going to that page, I make the following request in the mounted lifecycle method:
this.signature = this.$route.query.signature
this.expiry = this.$route.query.expiry
this.hash = this.$route.query.hash
this.id = this.$route.query.id
this.$axios.$get(`api/email/verify/${this.id}?hash=${this.hash}&expiry=${this.expiry}&signature=${this.signature}`)
.then(response => {
this.successMessage = response
}).catch(error => {
this.errorMessage = error
})
This request hits the endpoint on my server and the following method runs:
public function verify($user_id, Request $request) {
if (!$request->hasValidSignature()) { // Check always fails and we get a 401
return response()->json(["msg" => "Invalid URL provided."], 401);
}
$user = User::findOrFail($user_id);
if (!$user->hasVerifiedEmail()) {
$user->markEmailAsVerified();
}
return response()->json(["msg" => "Email verified."], 200);
}
The route for laravel endpoint:
Route::get('email/verify/{id}', 'Api\EmailVerificationController#verify')->name('verification.verify');
I can see that the parameters are received in the verify method request object parameter (e.g. setting a breakpoint and checking):
The check for a valid signature always fails and results in a 401 being sent back to the client. What's wrong with the URL/signature that I'm generating?
Here what I did to solve the problem. Go to AuthServiceProvider
/**
* Register any authentication / authorization services.
*
* #return void
*/
public function boot()
{
$this->registerPolicies();
//
VerifyEmail::createUrlUsing(function ($notifiable) {
$params = [
"expires" => Carbon::now()
->addMinutes(60)
->getTimestamp(),
"id" => $notifiable->getKey(),
"hash" => sha1($notifiable->getEmailForVerification()),
];
ksort($params);
// then create API url for verification. my API have `/api` prefix,
// so i don't want to show that url to users
$url = \URL::route("verification.verify", $params, true);
// get APP_KEY from config and create signature
$key = config("app.key");
$signature = hash_hmac("sha256", $url, $key);
// generate url for yous SPA page to send it to user
return env("APP_FRONT") .
"/auth/verify-email/" .
$params["id"] .
"/" .
$params["hash"] .
"?expires=" .
$params["expires"] .
"&signature=" .
$signature;
});
}
}
add this to api.php
Route::get("/verify-email/{id}/{hash}", [
VerifyEmailController::class,
"__invoke",
])
->middleware(["auth:sanctum","signed", "throttle:6,1"])
->name("verification.verify");
add this to VerifyEmailController.php
/**
* Mark the authenticated user's email address as verified.
*
* #param \Illuminate\Foundation\Auth\EmailVerificationRequest $request
* #return \Illuminate\Http\RedirectResponse
*/
public function __invoke(EmailVerificationRequest $request)
{
if ($request->user()->hasVerifiedEmail()) {
return response()->json(
[
"message" => "Your'r email already verified.",
],
Response::HTTP_BAD_REQUEST
);
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return response()->json(
[
"message" => "Verification complete thank you.",
],
Response::HTTP_OK
);
}
}
Front end
async verfyEmail() {
try {
const params = new URLSearchParams(this.$route.query)
let res = await this.$axios.get(
'verify-email/' +
this.$route.params.id +
'/' +
this.$route.params.hash,
{ params }
)
this.$router.push({ name: 'platform-dashboard' })
} catch (error) {
console.log(error.response)
this.$router.push({ name: 'platform-dashboard' })
}
}

Laravel Multi Auth before not working

I'm using ollieread multiauth. I got the problem when at route i try to use
Route::group(['before' => 'auth'], function()
{
Route::get('/onlinetest', array('as'=>'onlinetest', 'uses'=>'HomeController#onlinetest'));
Route::get('/quiz', array( 'as'=>'quiz', 'uses'=>'HomeController#quiz'));
Route::get('/number', array( 'as'=>'number', 'uses'=>'HomeController#number'));
Route::get('/word', array( 'as'=>'word', 'uses'=>'HomeController#word'));
});
Here is my usercontroller:
public function handlelogin()
{
$today = date("Y-m-d H:i:s");
$userdata = array(
'email' => Input::get('username'),
'password' => Input::get('password')
);
if (Auth::check())
{
return Redirect::to('/');
}
if(Auth::user()->attempt($userdata, true))
{
$user = User::find(Auth::user()->get()->id);
// check if user has use his account for test
if ($user->status == '0')
{
Auth::logout();
Session::flush();
return Redirect::to('/login')->with('message', FlashMessage::DisplayAlert('Your Account has been used for test', 'warning'));
}
$datebirth = Date($user->BirthDate);
$dob = Date("Y") - $datebirth;
Session::put('current_user', Input::get('username'));
Session::put('full_name', $user->FullName);
Session::put('gender', $user->Sex);
Session::put('dob', $dob);
Session::put('user_id', $user->id);
// set the user last login
$user->last_login = $today;
$user->save();
return Redirect::to('/onlinetest')->with('message', 'Login Successfully.');
}
else
{
return Redirect::to('/login')->with('message', FlashMessage::DisplayAlert('Incorrect Username / Password', 'danger'));
}
}
My Filter:
<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
//
});
App::after(function($request, $response)
{
//
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
if (Session::token() !== Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
apparently if I not using olliread this route is not working. I always can go to onlinetest even i'm not logging in.
Is there any solution for the route? or maybe I got it wrong at my controller?
Thanks.
You don't have a "user" filter which you specify in your Route group. Try swapping out "user" in your route group to "auth":
<?php
Route::group(['before' => 'auth'], function()
{
// ...
});

Laravel controller method calling other 'helper' methods

I had a functioning user log in route in my controller however the method itself was very long and handled multiple issues such as the possibility of the user being banned, ip logging etc. I wanted to break the method down so that it was more managable and I was wondering if this is possible?
Here are the 3 methods where 'postLogin()' is the route:
public function postLogin()
{
$validator = Validator::make(Input::all(), array(
'login-username' => 'required',
'login-password' => 'required'
));
if($validator->fails())
return Redirect::back()->withErrors($validator)->withInput();
else
{
$user_attempt = Input::get('login-username');
$pass_attempt = Input::get('login-password');
$auth = Auth::attempt(array(
'username' => $user_attempt,
'password' => $pass_attempt
), true);
if($auth)
$this->handleAuth();
else
return Redirect::route('home')->with('fail', 'Incorrect username or password, username: ' . $user_attempt . ' pass: ' . $pass_attempt);
}
}
private function handleAuth()
{
$username = Auth::user()->username;
$banned_info = UserBans::getBanned($username);
$stored_ip = Auth::user()->ip_address;
$current_ip = User::getIp();
if($stored_ip != $current_ip)
User::updateIp(Auth::user(), $current_ip);
if(is_null($banned_info))
return Redirect::intended('/');
else
$this->handleBan($banned_info, $current_ip);
}
private function handleBan($banned_info, $current_ip)
{
if(UserBans::isBanned($banned_info['ban_end']))
{
$message = "This account is currently banned until: " . $banned_info['ban_end'] . " Reason: " . $banned_info['reason'];
if($banned_info['ip_address'] != $current_ip)
{
$banned_model = UserBans::getBannedModel($banned_info['id']);
User::updateIP($banned_model, $current_ip);
}
Auth::logout();
return Redirect::route('home')->with('fail', $message);
}
else
{
UserBans::destroy($banned_info['id']);
return Redirect::intended('/');
}
}
The issue I'm finding is that the the main controller method will call the helper methods with no problem however the helper methods attempt to redirect to routes for example in handleAuth():
if(is_null($banned_info))
return Redirect::intended('/');
This occurs if the user is not banned and has the correct credentials, normally it would redirect to the home page and you would be logged in, however when this method calls the intended I am left with a blank page at the 'postLogin' routes url. If you refresh the page you are at the home and are logged in. Here are the relevant routes:
Route::group(array('before' => 'guest'), function()
{
Route::group(array('before' => 'csrf'), function()
{
Route::post('/user/login', array('uses' => 'UserController#postLogin', 'as' => 'postLogin'));
});
});
Is this possible to do with laravel routing/controllers? if not can you give any recommendations on how to handle this situation?
at handleAuth(), return Redirect::intended('/'); is returning something to postLogin(). You need to return that value from the postLogin().
So, add return at postLogin().
if($auth)
return $this->handleAuth();
Other Fixes
at handleAuth(), also add return
else
return $this->handleBan($banned_info, $current_ip);
Looks you are forgot to return handleBan() results
public function postLogin()
{
//...
if($auth)
return $this->handleAuth();
//...
}
private function handleAuth()
{
//...
if(is_null($banned_info))
return Redirect::intended('/');
else
return $this->handleBan($banned_info, $current_ip);
}

Laravel white screen when using Redirect Class

I am currently getting a white screen of death when I am trying to redirect my users using the Laravel Redirect class after handling data. If I use the native php-function header("location ...") the application responds correctly and sends the user on its merry way, but using Laravel's Redirect class the site crashes with a white screen of death. I have tried both the Redirect::action and Redirect::to functions, but they are both resulting in the same irritating white screen of death. The laravel.log shows nothing...
Does anyone have any ideas?
Here is the code for the data handler controller class:
<?php
class ManagerLayoutDataController extends BaseController
{
public function route($action, $moduleID) {
if(method_exists('ManagerLayoutDataController',$action)) {
$this->$action($moduleID);
}
// Invalid action (method not found)
else {
die('Action routing error');
//return Redirect::to('/');
}
}
public function updateHeaderBg($moduleID) {
$image = Input::file('img');
$user = Auth::user();
$siteID = $user->getSiteID();
$layoutDataMessage = null;
// Validate file upload (NOT FILE CHARACTERISTICS)
if(Input::hasFile('img') && $image->isValid() && isset($siteID) && $siteID !== "") {
$res = ManagerFileUpload::uploadImage($siteID, $image);
if($res->success) {
$fileName = $res->fileName;
$dbViewModule = ViewModuleRepository::getModule($moduleID);
if($dbViewModule->type === DBViewModule::MODULE_TYPE_HEADER) {
$headerModule = new HeaderModule($dbViewModule);
$headerModule->updateBgImage($fileName);
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_SUCCESS,"");
}
}
else {
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_FAIL,$res->message);
}
}
else {
$layoutDataMessage = new LayoutDataMessage(LayoutDataMessage::STATUS_FAIL, "Bilden kunde inte laddas upp.");
}
if($layoutDataMessage != null) {
return Redirect::action('ManagerLayoutController#main')->with('message',$layoutDataMessage);
//return Redirect::to('manager/layout/');
//header('location: */manager/layout');
}
else {
return Redirect::action('ManagerLayoutController#main')->with('message',LayoutDataMessage(LayoutDataMessage::STATUS_FAIL, "Bilden kunde inte laddas upp."));
//return Redirect::to('manager/layout/');
//header('location: */manager/layout');
}
}
}
The Main Controller
<?php
class ManagerLayoutController extends BaseController
{
public function main() {
$user = Auth::user();
$siteID = $user->getSiteID();
$moduleComposition = ViewModuleCompositionRepository::getCurrentInWorkModuleComposition($siteID);
$dbViewModules = ViewModuleRepository::getModulesFromComposition($moduleComposition->id);
$viewModules = array();
foreach($dbViewModules as $dbViewModule) {
switch($dbViewModule->getType()) {
case DBViewModule::MODULE_TYPE_HEADER:
$viewModules[] = new HeaderModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_TEXT_SECTION:
$viewModules[] = new TextSectionModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_KEY_METRICS:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_SLIDESHOW:
$viewModules[] = new SlideShowModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_VACANCIES:
$viewModules[] = new VacanciesModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_EMAIL_SUBSCRIPTION:
$viewModules[] = new EmailSubscriptionsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_CO_WORKERS:
$viewModules[] = new CoworkersModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_NEWS_SECTION:
$viewModules[] = new NewsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_INSTAGRAM_FEED:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
case DBViewModule::MODULE_TYPE_SOCIAL_MEDIA:
$viewModules[] = new KeyMetricsModule($dbViewModule);
break;
}
}
$data = array(
'siteID' => $siteID,
'viewModules' => $viewModules
);
return View::make('dashboard.pages.manager.layout_main',$data);
}
}
filters.php
<?php
/*
|--------------------------------------------------------------------------
| Application & Route Filters
|--------------------------------------------------------------------------
|
| Below you will find the "before" and "after" events for the application
| which may be used to do any work before or after a request into your
| application. Here you may also register your custom route filters.
|
*/
App::before(function($request)
{
//
});
App::after(function($request, $response)
{
//
});
/*
|--------------------------------------------------------------------------
| Authentication Filters
|--------------------------------------------------------------------------
|
| The following filters are used to verify that the user of the current
| session is logged into this application. The "basic" filter easily
| integrates HTTP Basic authentication for quick, simple checking.
|
*/
Route::filter('auth', function()
{
if (Auth::guest())
{
if (Request::ajax())
{
return Response::make('Unauthorized', 401);
}
else
{
return Redirect::guest('login');
}
}
});
Route::filter('auth.basic', function()
{
return Auth::basic();
});
/*
|--------------------------------------------------------------------------
| Guest Filter
|--------------------------------------------------------------------------
|
| The "guest" filter is the counterpart of the authentication filters as
| it simply checks that the current user is not logged in. A redirect
| response will be issued if they are, which you may freely change.
|
*/
Route::filter('guest', function()
{
if (Auth::check()) return Redirect::to('/');
});
/*
|--------------------------------------------------------------------------
| CSRF Protection Filter
|--------------------------------------------------------------------------
|
| The CSRF filter is responsible for protecting your application against
| cross-site request forgery attacks. If this special token in a user
| session does not match the one given in this request, we'll bail.
|
*/
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
/** Admin pages */
Entrust::routeNeedsRole( 'admin*', 'Admin', Redirect::to('/login'));
/** Manage pages */
Entrust::routeNeedsRole( 'manager*', array('Super Manager','Manager'), Redirect::to('/login'), false );
/**
* Check view module ownership before editing data
*/
Route::filter('viewmodule.ownership', function($route) {
$user = Auth::user();
$siteID = $user->getSiteID();
$moduleID = $route->getParameter('moduleID');
// Check that the module with $moduleID belongs to $siteID
if(ViewModuleRepository::moduleBelongToSite($moduleID, $siteID)) {
}
// Unauthorized access
else {
die('Filter error');
//Redirect::to('/');
}
});
routes.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the Closure to execute when that URI is requested.
|
*/
Route::get('/', 'FrontController#main');
Route::get('/manager', 'ManagerHomeController#home');
Route::get('/manager/statistics', 'ManagerStatisticsController#main');
Route::get('/manager/resume-manager', 'ManagerResumeController#main');
Route::get('/manager/resume-manager/pending', 'ManagerResumeController#resumesPending');
Route::get('/manager/resume-manager/approved', 'ManagerResumeController#resumesApproved');
Route::get('/manager/resume-manager/rejected', 'ManagerResumeController#resumesRejected');
Route::get('/manager/layout', 'ManagerLayoutController#main');
Route::get('/manager/layout-old', 'OLDManagerLayoutController#main');
Route::post('/manager/layout/data/{action}/{moduleID}/', array('before'=>'viewmodule.ownership', 'uses' => 'ManagerLayoutDataController#route'));
Route::get('/manager/setup', 'ManagerSetupController#setup');
Route::get('/admin', 'AdminHomeController#home');
Route::get('/login', 'UsersController#login');
Route::get('/test', 'TestController#testMail');
// Confide routes
Route::get('users/create', 'UsersController#create');
Route::post('users', 'UsersController#store');
Route::get('users/login', 'UsersController#login');
Route::post('users/login', 'UsersController#doLogin');
Route::get('users/confirm/{code}', 'UsersController#confirm');
Route::get('users/forgot_password', 'UsersController#forgotPassword');
Route::post('users/forgot_password', 'UsersController#doForgotPassword');
Route::get('users/reset_password/{token}', 'UsersController#resetPassword');
Route::post('users/reset_password', 'UsersController#doResetPassword');
Route::get('users/logout', 'UsersController#logout');
Try to add
ini_set('display_errors', 1);
It should at least tell you what is the actual error.
This is only for development mode, remove it when you go into production
Look if there is a "return" before the Redirect. For example:
// Unauthorized access
else {
die('Filter error');
//Redirect::to('/');
}
Here should be return Redirect::to('/');

Laravel redirect or make view?

I have made a contact form and I want to send the user to a thank you page or back to the contact form with an error message saying what fields were missing that need to be filled.
Initially I tried:
public function submit() {
if (Input::has('name')) {
$name = Input::get('name');
} else {
return Redirect::to('apply')->with('message', 'Login Failed');
}
$this->thanks($name);
}
public function thanks() {
return View::make('apply.thanks', array('metaTitle' => 'Application Sent | Thank you'));
}
But this gives me an error.
So I replaced the line $this->thanks($name); with return Redirect::to('apply/thanks')->with('message', 'Login Failed');
And it works.
My two questions are:
Is this the right way to send the user to the thank you page?
If there is an error, I would like to send back which errors occurred (what required fields weren't filled out). How is this achieved?
I have tried to implement route names:
routes file
Route::post('apply/submit', array('as' => 'applicationSubmit', 'uses' => 'ApplyController#submit'));
Route::post('apply/thanks', array('as' => 'applicationThanks', 'uses' => 'ApplyController#thanks'));
apply file
public function submit() {
$validationErrors = array();
if (Input::has('name')) {
$name = Input::get('name');
} else {
$validationErrors[] = 'You must enter your name';
}
if($validationErrors) {
if(Request::ajax()){
} else {
return Redirect::to('apply')->with('validationErrors', $validationErrors);
}
} else {
if(Request::ajax()){
} else {
return Redirect::route('applicationThanks')->with('name', $name);
}
}
}
But I'm getting the error Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException (I found out how to turn the detailed error messages on :) )
I think you want something like this:
public function submit() {
if (Input::has('name')) {
$name = Input::get('name');
} else {
return Redirect::to('apply')->with('message', 'Login Failed');
}
return Redirect::to('thanks')->with('name', $name);
}
public function thanks() {
return View::make('apply.thanks', array('metaTitle' => 'Application Sent | Thank you'));
}
Of course you need to have defined route to thanks.
But you could also make it simpler without using thanks method at all:
public function submit() {
if (Input::has('name')) {
$name = Input::get('name');
return View::make('apply.thanks', array('metaTitle' => 'Application Sent | Thank you'));
}
return Redirect::to('apply')->with('message', 'Login Failed');
}
I would rather go for second method (there's no need to make extra redirection just to display view).
You could also consider using named routes in case you will change your urls in future
EDIT
Route for thanks need to use get method and not post because you make redirection to it (no form data are sent by user to this route), so instead of:
Route::post('apply/thanks', array('as' => 'applicationThanks', 'uses' => 'ApplyController#thanks'));
it should be rather:
Route::get('apply/thanks', array('as' => 'applicationThanks', 'uses' => 'ApplyController#thanks'));
I advise you to look at Basic routing - you should really understand verbs and routing and in case you don't care you can always use Route::any to match all verbs: POST, GET, PUT, PATCH and DELETE - but in my opinion it's better to use correct verb and not all of them.

Categories