Laravel 5.2 Flash Old and errors empty after redirect - validation

I have a problem in laravel. This problem it's only in production server, in my local server it's work property. So maybe it's something in the configuration that I don't know.
So when I Send a form, with wrong values the laravel validator system should redirect the user to the form and show the errors.
This is the code my controller:
$rules = array(
'nombre' => 'required|min:3|max:80',
'email' => 'required|email',
'asunto'=>'required|min:3|max:200',
'mensaje'=>'required|min:5|max:1000',
//'g-recaptcha-response' => 'required|recaptcha',
);
$validation = Validator::make($request->all(), $rules);
//si la validación falla redirigimos al formulario de registro con los errores
//y con los campos que nos habia llenado el usuario
if ($validation->fails())
{
return Redirect::to('/#contacto')->withErrors($validation->messages())->withInput();
}
/#contacto is the Home route with the anchor contacto so this should redirect to the home. This is ok.
This is my route.php
Route::get('/', function () {
return view('web.index');
});
Route::post('/contacto/enviar', 'WebController#contacto');
This is my Kernel
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* #var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
This is my view that should show the error result.
<form name="contacto" method="post" action="/contacto/enviar"><input type="hidden" name="_token" value="<?php echo csrf_token(); ?>">
<div class="col-lg-6 col-sm-5 wow fadeInUp delay-05s">
<div class="form"><font color="#ff0000" size="1"><b>{{$errors->first('nombre', ':message')}}</b></font><input class="input-text" type="text" name="nombre" value="<?=Request::old('nombre', 'Nombre y apellido *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('email', ':message')}}</b></font><input class="input-text" type="text" name="email" value="<?=Request::old('email', 'Correo electrónico *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('telefono', ':message')}}</b></font><br><input class="input-text" type="text" name="telefono" value="<?=Request::old('telefono', 'Teléfono (incluya código de área) *');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('asunto', ':message')}}</b></font><input class="input-text" type="text" name="asunto" value="<?=Request::old('asunto', 'Asunto');?>" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><font color="#ff0000" size="1"><b>{{$errors->first('mensaje', ':message')}}</b></font><textarea class="input-text text-area" cols="0" rows="0" name="mensaje" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"><?=Request::old('mensaje', 'Escriba aquí el mensaje *');?></textarea><font color="#ff0000" size="1"><b>{{$errors->first('g-recaptcha-response', ':message')}}</b></font>{!! Recaptcha::render(['lang'=>'es']) !!}<input class="input-btn" type="submit" value="ENVIAR"></div>
</div></form>
On the top of my view I have a var_dump(Session::all()) and this is the result allways when I submit the form.
array(3) {
["_token"]=>
string(40) "WrQWk9qTH47QrKD6J0Qld8sOhKcUp8xssGpy0F2g"
["_previous"]=>
array(1) {
["url"]=>
string(25) "http://dsnet.dsnet.com.ar"
}
["flash"]=>
array(2) {
["old"]=>
array(0) {
}
["new"]=>
array(0) {
}
}
In execution of php artisan route:list this is my result, so I have checked that the web middleware is not duplicate.
The estrange thing is that the same code in my local server is working, and in all the form redirect the result are:
array(4) {
["_token"]=>
string(40) "4s1rhoydlH7l84Em792N79ymemNjh4Ep6I8WLNSG"
["errors"]=>
object(Illuminate\Support\ViewErrorBag)#177 (1) {
["bags":protected]=>
array(1) {
["default"]=>
object(Illuminate\Support\MessageBag)#178 (2) {
["messages":protected]=>
array(1) {
["email"]=>
array(1) {
[0]=>
string(40) "The email must be a valid email address."
}
}
["format":protected]=>
string(8) ":message"
}
}
}
["flash"]=>
array(2) {
["new"]=>
array(0) {
}
["old"]=>
array(2) {
[0]=>
string(6) "errors"
[1]=>
string(10) "_old_input"
}
}
["_old_input"]=>
array(7) {
["_token"]=>
string(40) "jzCq4CGGgutPJ3qB2ls1rp7uaiHpcra9Aer1vApC"
["nombre"]=>
string(19) "Nombre y apellido *"
["email"]=>
string(21) "Correo electrónico *"
["telefono"]=>
string(38) "Teléfono (incluya código de área) *"
["asunto"]=>
string(6) "Asunto"
["mensaje"]=>
string(26) "Escriba aquí el mensaje *"
["g-recaptcha-response"]=>
string(0) ""
}
}
I remember that I had the same issue in the local server and I fixed setting the domain configuration on the session config file as null, but this solution doesn't work in the production server. Any Idea?

Finally, I say that the code it's great! There is not problem with the code, but is a problem with the server configuration. I don't know where. But I upload the site to another server and with the setting of the domain = null, of the session configuration work great.

Related

Image CRUD in laravel 9 with vue Js

I have a form that and I want it to have a CRUD function, I have made the function for the text, but I have no idea how to do CRUD with images,
Here is my code :
Model
protected $fillable= [
'nama',
'alamat',
'nomor',
'email',
];
Controller :
public function index()
{
return Form::all();
}
public function store(Request $request)
{
$data = $request->all();
$response = Form::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
The Form :
<Form #submit="saveData()">
<div class="form-row form-section" id="formParent">
<div class="col-12 mb-3">
<Field name="nama" type="text" class="form-control1" v-model="form.nama" placeholder=" Nama Lengkap" :rules="isRequired" />
<br>
<ErrorMessage name="nama" />
<br>
<Field name="alamat" type="text" class="form-control2" v-model="form.alamat" placeholder=" Alamat" :rules="isRequired" />
<br>
<ErrorMessage name="alamat" />
<br>
<Field name="nomor" type="text" class="form-control3" v-model="form.nomor" placeholder=" Nomor Telfon" :rules="isRequired" />
<br>
<ErrorMessage name="nomor" />
<br>
<Field name="nomor" type="file" class="form-control3" v-model="form.nomor" placeholder=" Nomor Telfon" :rules="isRequired" />
<Field name="email" type="text" class="form-control4" v-model="form.email" placeholder=" Email" :rules="validateEmail" />
<br>
<ErrorMessage name="email" />
</div>
<button class="btnSubmit" type="submit">
Gabung Mitra
</button>
</div>
</Form>
Script :
<script>
import axios from 'axios';
import { Form, Field, ErrorMessage} from 'vee-validate';
export default {
components: {
Form,
Field,
ErrorMessage
},
data() {
return {
form: {
nama: '',
alamat: '',
nomor: '',
email: '',
},
};
},
methods: {
isRequired(value){
if (value && value.trim()){
return true;
}
return 'This is required';
},
validateEmail(value) {
// if the field is empty
if (!value) {
return 'This field is required';
}
// if the field is not a valid email
const regex = /^[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
if (!regex.test(value)) {
return 'This field must be a valid email';
}
// All is good
return true;
},
saveData(){
axios.post('/form/submit', this.form).then(
response => {
console.log(response);
this.$toast.success(`Data berhasil dikirim`,{
position: "bottom",
});
}
). catch(error => {
console.log('error');
this.$toast.error(`Terjadi kegagalan`,{
position: "bottom",
});
})
}
}
};
</script>
What should I do so that the user can upload an image to the form and save it to the database. I tried to change the field type to file, but I have no idea how the function works in the controller.
For storing images with Form you need to add few lines inside contoller for handling and storing image and also you need to add enctype inside form submit.
First you need to change :
<Form #submit="saveData()" enctype="multipart/form-data">
Now you need to change image input field :
<Field name="image" type="file" class="form-control3" v-model="form.image" :rules="isRequired" />
And inside the controller you need to change code for request :
public function store(Request $request)
{
$data = $request->all();
if ($request->hasFile('image')) {
$image = $request->file('image');
$path = $image->store('public/images');
$data['image'] = $path;
}
$response = Form::create($data);
return response()->json([
'status' => 'success',
'data' => $response
], 200);
}
And finally in your model :
protected $fillable = [
'nama',
'alamat',
'nomor',
'email',
'image',
];

Forgot password is not sending email verification (Codeigniter)

I have a password retriever function. But the problem is, the verification is not sending on my email or whatsoever. My goal is to reset my password using gmail authentication. just like how you can reset your password on social medias. I have provided my codes below. Any help will be appreciated. Thank you very much.
Views:
<h2>Reset</h2>
<div id="resest_password_form">
<form action="/page/reset_password" method="POST">
<div>
<label for="email">Email:</label>
<input type="email" value="<?php echo set_value('email');?>" name="email" />
</div>
<div>
<input type="submit" name="submit" value="Reset" />
</div>
</form>
<?php
echo validation_errors('<p class="error">');
if(isset($error)){
echo '<p class="error">'.$error.'</p>';
}
?>
</div>
Controllers:
//reset_password email checker validation is working
public function reset_password(){
if(isset($_POST['email'])&& !empty($_POST['email'])){
$this->load->library('form_validation');
$this->form_validation->set_rules('email','Email_Address', 'trim|required|min_length[6]|max_length[50]|valid_email|xss_clean');
if ($this->form_validation->run()==FALSE){
$this->load->view('view_reset_password', array('error' => 'Please'));
}else {
$email = trim($this->input->post('email'));
$result = $this->pages->email_exists($email);
if($result){
$this->send_reset_password_email($email, $result);
$this->load->view('vw_register', array('email' => $email));
}else {
$this->load->view('page/view_reset_password', array('error' => 'Please else'));
}
}
} else {
$this->load->view('page/view_reset_password');
}
}
//sending email_verification is not working. I'm not receiving any reset link to my gmail.
private function send_reset_password_email($email, $firstname) {
$config = Array(
'protocol' => 'smtp',
'smtp_host' => 'ssl://smtp.googlemail.com',
'smtp_port' => 465,
'smtp_user' => 'd****#gmail.com',
'smtp_pass' => 'd*****',
'mailtype' => 'html',
'charset' => 'iso-8859-1'
);
$this->load->library('email', $config);
$this->email->set_newline("\r\n");
$this->load->library('email');
$email_code = md5($this->config->item('salt') . $firstname);
$this->email->set_mailtype('html');
$this->email->from($this->config->item('bot_email'), 'Freight Forum');
$this->email->to($email);
$this->email->subject('Please');
$message = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head><body>';
$message .= '<p> Dear' . $firstname .',</p>';
$message .= '<p>WE<strong>click here</strong> to reset</p>';
$message .= '<p>Thanks</p>';
$message .= '<p>The Team</p>';
$message .= '</body></html>';
$this->email->message($message);
$this->email->send();
}
Model:
//working
public function email_exists($email){
$sql = "SELECT firstname, email FROM users WHERE email = '{$email}' LIMIT 1";
$result = $this->db->query($sql);
$row = $result->row();
return ($result->num_rows() === 1 && $row->email) ? $row->firstname : false;
}

Undefined Index:email Error In Laravel 5.6

I want to make login functionality for my website. But unfortunately it is giving undefined Index:email in my AdminController:
public function login(Request $request)
{
if($request->isMethod('post'))
{
$data = $request->input();
if (Auth::attempt(['email' => $data['email'], 'password' => $data['password'],'admin' => '1'])) {
echo "Success";
//console.log("Successfull");
die;
}
else
{
echo "Failed";
//console.log("Failed");
die;
}
}
return view('admin.admin_login');
}
In Blade:
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text bg-success text-white" id="basic-addon1"><i class="ti-user"></i></span>
</div>
<input type="email" name="email" class="form-control form-control-lg" placeholder="Email" aria-label="Email" aria-describedby="basic-addon1" required="">
</div>
change $data['email'] to $request->email.Because $request contain object not an array
You can do the following
public function login(Request $request)
{
if($request->isMethod('post'))
{
if (Auth::attempt(['email' =>$request->email, 'password' => $request->password,'admin' => '1'])) {
echo "Success";
//console.log("Successfull");
die;
}
else
{
echo "Failed";
//console.log("Failed");
die;
}
}
return view('admin.admin_login');
}
even i dont see password field in your blade template

codeigniter login validation not validating rules

am using codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
$this->load->library('form_validation');
$this->form_validation->set_rules('email', 'Email', 'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');
if($this->form_validation->run() ){
$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));
$data = array (
'user_id' => $user_id,
'email' => $this->input->post('email'),
'user_status' =>$user_status,
'is_logged_in' => 1
);
$this->session->set_userdata($data);
}
if ($this->session->userdata('user_status')=='0') {
redirect('main/admins');
}
elseif ($this->session->userdata('user_status')=='1') {
redirect('main/members');
}else{
redirect('welcome/login_page');
}
}
public function validate_credentials(){
$this->load->model('model_users');
if($this->model_users->can_log_in() ){
return TRUE;
} else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
}
}
....the view(login.php)......
echo form_open("first/signup_validation");
echo'<div class="row">';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="email">Email<span></span></label>';
echo'<input type="text" class="form-control" id="email">';
echo'</div>';
echo'<div class="form-group col-md-6 col-xs-12 col-sm-6">';
echo'<label for="password">Password<span></span></label>';
echo'<input type="password" class="form-control" id="password">';
echo'</div>';
echo'</div>';
$data2 = array(
'class' => 'btn btn-default',
);
echo form_submit($data2, 'Login');
echo form_close('');
?>
echo '<input type="text" class="form-control" id="email">';
Your input elements don't contain a name attribute. The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute
Do this...
echo'<input type="text" class="form-control" id="email" name="email">';

methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php laravel 5.0

I want to login as I submit the form but I am getting an error.
The form code is as follows:
{!! Form::open() !!}
{{ $errors->first("parentPassword") }}<br />
<div>
<legend>Parent</legend>
Email<br>
<input type="email" id="email" name="parentEmail" required>
<br>
Password<br>
<input type="password" name="parentPassword">
<br><br>
</div>
{!!Form::submit('Submit',array('class' => 'btn btn-outline btn-primary')) !!} </fieldset>
{!! Form::close() !!}
The controller code is as follows:
App\Http\Controllers;
use Illuminate\Support\Facades\Redirect;
class loka extends Controller
{
public function login()
{
if ($this->isPostRequest()) {
$validator = $this->getLoginValidator();
if ($validator->passes()) {
$credentials = $this->getLoginCredentials();
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
}
return Redirect::back()->withErrors([
"parentPassword" => ["Credentials invalid."]
]);
} else {
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return view("signup.index");
}
protected function isPostRequest()
{
// return Request::isMethod('post');
}
protected function getLoginValidator()
{
return Validator::make(Request::all(), [
"parentEmail" => "required",
"parentPassword" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"parentEmail" => Request::input("parentEmail"),
"parentPassword" => Request::input("parentPassword")
];
}
}
The route is as follows:
Route::patch("/index", [
"as" => "login/index",
"uses" => "loka#login"
]);

Resources