I am attempting to set and pass a flash message, when a form validation fails. When the validation passes, I am able to set Flash message in the controller.
I have tried to override the protected failedValidation() but I get an error.
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest; use Illuminate\Support\Facades\Validator;
class UserRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'first_name' => 'required|string|min:2|max:50',
'last_name' => 'required|string|min:2|max:50',
'date_of_birth' => 'required|date',
'gender' => 'required|in:male,female'
];
}
/**
* Handle a failed validation attempt.
*/
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
Flash::error("Profile could not be saved!");
// alert()->error('oops ... error');
return parent::failedValidation($validator);
} }
error:
Symfony\Component\Debug\Exception\FatalThrowableError Class
'App\Http\Requests\Flash' not found
I am setting my view in app.blade.php as follows
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div> <!-- end .flash-message -->
you need to add use Flash; in the controller at the top after namespace declaration where you want to use the flash library methods.
Related
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods: POST.
Validation is working but the data is not being saved in array or something like that because i am unable to pass the data into view.
+My SendEmailConroller.php consists of:
class SendEmailController extends Controller
{
public function send(Request $request)
{
$this->validate($request,[
'email' => 'required|email',
'phone' => 'required|min:10|max:10',
'messagefor' =>'required|min:5'
]);
$data =array(
'name' => $request->email,
'email' => $request->email,
'phone' => $request->phone,
'messagefor' => $request->messagefor
);
Mail::to('shishir.nepal.9#gmail.com')->send(new WelcomeMail($data));
return back()->with('success','Thank you for contacting us');
// return redirect()->to('/email')->with($data);
}
public function index(){
return view('emails.welcome')
}
+I am trying to Send data from form to email controller and then show in welcome.blade.php
+My Welcome mail consists of:
class WelcomeMail extends Mailable
{
use Queueable, SerializesModels;
public $data;
/**
* Create a new message instance.
*
* #return void
*/
public function __construct($data)
{
$this->data =$data;
}
/**
* Build the message.
*
* #return $this
*/
public function build()
{
return $this->from('help#gmail.com')->subject('new seo for my page')->markdown('emails.welcome')->with('data',$this->data);
}
}
And my web.php is:
Route::post('/email','SendEmailController#send');
Route::get('/sendemail','SendEmailController#index');
And at last my welcome.blade.php
#if($message=Session::get('success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">x</button>
<strong>{{$message}}</strong>
</div>
#endif
<p>Hi , This is {{$data['name']}}</p>
<p>I have some query like" {{$data['messagefor']}} "</p>
I am using FormRequest to do my validations. I am trying to set a top-level error message via Flash to show to the user that the form submission did not succeed.
Right now I have the following UserResquest
class UserRequest extends FormRequest {
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'first_name' => 'required|string|min:2|max:50',
'last_name' => 'required|string|min:2|max:50',
'date_of_birth' => 'required|date',
'gender' => 'required|in:male,female'
];
}
I am trying to do this in my Controller
$validator = $request->validated();
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
But the Flash message is turning up empty. whats the best way to set the Flash Error message when using FormRequest
Am setting my Flash Message as following the View Template.
<div class="flash-message">
#foreach (['danger', 'warning', 'success', 'info'] as $msg)
#if(Session::has('alert-' . $msg))
<p class="alert alert-{{ $msg }}">{{ Session::get('alert-' . $msg) }} ×</p>
#endif
#endforeach
</div> <!-- end .flash-message -->
FormRequest does it automatically, you dont have to handle it in the controller.
it does so in
protected function failedValidation(Validator $validator)
{
throw (new ValidationException($validator))
->errorBag($this->errorBag)
->redirectTo($this->getRedirectUrl());
}
You can overload the method if you want another behavior.
To get the error messages, you need to fetch it in the error bag
{{ $errors->default->first('first_name') }}
the error bag is named default by default, you can change it in your FormRequest extended class
Custom messages
To set the message per error, declare the following method in your UserRequest class
public function messages()
{
return [
'first_name.required' => 'A first name is required',
'first_name.min' => 'The first name can\'t be a single character',
...
];
}
And to know if there are errors, check the variable $errors->default in your blade then you can show the message "The Form did not save. Check below for the error and try again"
As N69S pointed out. We can set it under failedValidation as below.
/**
* Handle a failed validation attempt.
*/
protected function failedValidation(\Illuminate\Contracts\Validation\Validator $validator)
{
session()->flash('alert-danger', 'There was an error, Please try again!');
return parent::failedValidation($validator);
}
I am using a multi auth guard for my laravel app and everything seems to be working fine....registration, login etc perfect. but i need to get values of an authenticated user of a specific guard in my views but it kept saying undefined property
Here is the code to my model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Agent extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'firstname', 'lastname', 'aid', 'city', 'state', 'email', 'password', 'bankname', 'accountnumber',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
and for my view :
#extends('layouts.app')
#section('title')
OneNaira© Welcome Back {{ auth()->user()->firstname }}
#endsection
#section('footer')
<!--FOOTER-->
<div class="ui stackable pink inverted secondary pointing menu" id="footer">
<div class="ui container">
<a class="item">© OneNaira, 2019.</a>
<div class="right menu">
<a class="item">
<script>
var todaysDate = new Date();
document.write(todaysDate);
</script>
</a>
</div>
</div>
</div>
#endsection
and for the login controller
<?php
namespace App\Http\Controllers\Agent\Auth;
use Auth;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
class LoginController extends Controller
{
/**
* Show the login form.
*
* #return \Illuminate\Http\Response
*/
public function showLoginForm()
{
return view('agent.auth.login',[
'title' => 'Welcome Back, Sign Into Your OneNaira Initiative Agent Dashboard',
'loginRoute' => 'agent.login',
'forgotPasswordRoute' => 'agent.password.request',
]);
}
/**
* Login the agent.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\RedirectResponse
*/
public function login(Request $request)
{
$this->validator($request);
if(Auth::guard('agent')->attempt($request->only('aid','password'),$request->filled('remember'))){
//Authentication passed...
return redirect()
->intended(route('agent.dashboard'));
}
//Authentication failed...
return $this->loginFailed();
}
/**
* Logout the agent.
*
* #return \Illuminate\Http\RedirectResponse
*/
public function logout()
{
Auth::guard('agent')->logout();
return redirect()
->route('agent.login')
->with('status','Agent has been logged out!');
}
/**
* Validate the form data.
*
* #param \Illuminate\Http\Request $request
* #return
*/
private function validator(Request $request)
{
//validation rules.
$rules = [
'aid' => 'required|exists:agents,aid|min:8|max:191',
'password' => 'required|string|min:4|max:255',
];
//custom validation error messages.
$messages = [
'aid.exists' => 'These credentials do not match our records.',
];
//validate the request.
$request->validate($rules,$messages);
}
/**
* Redirect back after a failed login.
*
* #return \Illuminate\Http\RedirectResponse
*/
private function loginFailed()
{
return redirect()
->back()
->withInput()
->with('error','Login failed, please try again!');
}
}
I figured it out : {{ Auth::guard('agent')->user()->firstname }}
I am trying to create a subscription service using Laravel, Laravel Cashier and Braintree. I get the following error:
Unable to create Braintree customer: Unknown or expired payment_method_nonce.
CVV is required.
Expiration date is required.
Credit card number is required.
Credit card must include number, payment_method_nonce, or venmo_sdk_payment_method_code.
I've done the following in my HTML:
<form class="form-horizontal" role="form" method="POST" action="{{ route('register') }}">
<select name="plan" id="plan" class="form-control">
<option value="">Select plan</option>
<option value="free">Free plan - €0/month</option>
<option value="cool">Cool plan - €10/month</option>
<option value="epic">Epic plan - €100/month</option>
</select>
<div id="dropin-container"></div>
<input type="submit" class="btn btn-primary blue-button" value="Sign Up" style="margin-top: 6px;">
<!-- Load the Client component. -->
<script src="https://js.braintreegateway.com/js/braintree-2.31.0.min.js"></script>
<script>
braintree.setup('{{ $braintreeToken }}', 'dropin', {
container: 'dropin-container'
});
</script>
</form>
then I have the following RegisterController.php. The most important bit is in the create method:
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after registration.
*
* #var string
*/
protected $redirectTo = '/account';
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('guest');
}
/**
* Show the application registration form.
*
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function showRegistrationForm()
{
$braintreeToken = \Braintree\ClientToken::generate();
return view('auth.register')
->with('braintreeToken', $braintreeToken)
->with('plan', 'none')
->with('route', 'register');
}
/**
* Handle a registration request for the application.
*
* #param Request|\Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate();
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
/**
* Get a validator for an incoming registration request.
*
* #param array $data
* #return \Illuminate\Contracts\Validation\Validator
*/
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'plan' => 'required|in:free,cool,epic'
]);
}
/**
* Create a new user instance after a valid registration.
*
* #param array $data
* #return User
*/
protected function create(array $data)
{
$limit = 200;
$plan = 'free';
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'plan' => $plan,
'limit' => $limit,
'password' => bcrypt($data['password']),
]);
switch($data['plan'])
{
case 'cool':
$limit = 3000;
$plan = 'cool';
$planID = 'gt8m';
break;
case 'epic':
$limit = 32000;
$plan = 'epic';
$planID = '8v3g';
break;
}
$subscription = $user->newSubscription('main', $planID)->create($data['_token']);
if ($subscription)
{
$user->plan = $plan;
$user->limit = $limit;
$user->save();
}
return $user;
}
}
The error happens when I input the following credit card details (these are supposed to be the test credit card numbers used in the sandbox):
Credit card number: 4111 1111 1111 1111
Expiration date: 08/2018
CVV: 123
I've tried googling the error but nothing useful came up.
Problem was I was using the _token from the post data while I needed to use payment_method_nonce.
i am unable to login in laravel 5 at admin side
my users table data in mysql is
username=admin Primary key
password=admin
is there any problem in my code if there then let me know please...
my code is following
Route.php
Route::group(array('prefix'=>'admin'),function(){
Route::filter('pattern: admin/*', 'auth');
Route::get('login', 'admin\AdminHomeController#showLogin');
Route::post('check','admin\AdminHomeController#checkLogin');
Route::get('adminlogout', 'admin\AdminHomeController#logout');
Route::get('dashboard', 'admin\AdminHomeController#showDashboard');
});
Users.php // my module
<?php namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
public static $auth_rules=[
'username'=>'required',
'password'=>'required'
];
/**
* The database table used by the model.
*
* #var string
*/
public $timestamps=false;
protected $table = 'users';
public $primaryKey = 'username';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['username', 'password'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['password', 'remember_token'];
public function getAuthPassword()
{
return $this->password;
}
/**
* Automatically Hash the password when setting it
* #param string $password The password
*/
public function setPassword($password)
{
$this->password = Hash::make($password);
}
}
AdminHomeController.php
<?php namespace App\Http\Controllers\admin;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Auth;
class AdminHomeController extends Controller {
//
public function showLogin()
{
return view('admin.login');
}
public function checkLogin(Request $request)
{
$data=array(
'username'=>$request->get('username'),
'password'=>$request->get('password')
);
print_r($data);
if(Auth::attempt($data))
{
echo "ok";die;
return redirect::intended('admin/dashboard');
}
else
{
echo "not ok";die;
return redirect('admin/login');
}
}
public function logout()
{
Auth::logout();
return redirect('admin/login');
}
public function showDashboard()
{
return view('admin.dashboard');
}
}
I don't know what made you to use backslash (\) in your routes.php file.
In your checkLogin method, you are attempting to login, which I presume it does logs the admin in his dashboard provided the login credentials are correct.
You are using die; which will stop the execution of the script, hence, there is no redirection.
Also, you have not mentioned what is/are the error(s) that you get when you try login.
Change this code:
/**
* Automatically Hash the password when setting it
*
* #param string $password The password
*/
public function setPassword($password)
{
$this->password = Hash::make($password);
}
to this:
/**
* Automatically Hash the password when inserting
*
* #param string $password The password
*/
public function setPasswordAttribute($password)
{
// You need to import the Hash Facade in
// to hash your password.
$this->password = Hash::make($password);
// or use this if you do not want to import
// the Hash Facade.
$this->password = bcrypt($password);
}
Whenever you want to set the attribute to its corresponding / respective value, you should prefix the attribute with the word set and suffix the same attribute with the word Attribute. (Notice capital A in Attribute). So, in your code, it should be setPasswordAttribute. Laravel will then save the value that you want it to save in the database table.
But just to get you going, this is how I do it:
routes.php
Route::get('/admin', 'UsersController#getAdminLogin');
Route::get('/admin/dashboard', 'UsersController#dashboard');
Route::post('/admin', 'UsersController#postAdminLogin');
admin_login.blade.php
{!! Form::open(['url' => '/admin']) !!}
<div class="form-group">
{!! Form::label('email', 'Email Id:') !!}
{!! Form::text('email', null, ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::label('password', 'Password') !!}
{!! Form::password('password', ['class' => 'form-control input-sm']) !!}
</div>
<div class="form-group">
{!! Form::submit('Login', ['class' => 'btn btn-primary btn-block']) !!}
</div>
{!! Form::close() !!}
dashboard.blade.php
<h4 class="text-center">
Welcome Admin, {{ Auth::user()->username }}
</h4>
UsersController.php
/**
* Display the admin login form if not logged in,
* else redirect him/her to the admin dashboard.
*
*/
public function getAdminLogin()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return redirect('/admin/dashboard');
}
return view('admin_login');
}
/**
* Process the login form submitted, check for the
* admin credentials in the users table. If match found,
* redirect him/her to the admin dashboard, else, display
* the error message.
*
*/
public function postAdminLogin(Request $request)
{
$this->validate($request, [
'email' => 'required|email|exists:users,email,role,admin',
'password' => 'required'
]);
$credentials = $request->only( 'email', 'password' );
if(Auth::attempt($credentials))
{
return redirect('/admin/dashboard');
}
else
{
// Your logic of invalid credentials.
return 'Invalid Credentials';
}
}
/**
* Display the dashboard to the admin if logged in, else,
* redirect him/her to the admin login form.
*
*/
public function dashboard()
{
if(Auth::check() && Auth::user()->role === 'admin')
{
return view('admin.dashboard');
}
return redirect('/admin');
}
Visit this link for more learning on routes.
If you are using following function to set password while registering/adding admin user,
change
Hash::make($password)
to
bcrypt($password)