Laravel form data not saving in neo4j graph DB - php

I wrote a laravel form, its screen shot is as given below:
And I use neo4j for storing that form data.
Here is the code:
app/views/duck-form.blade.php
<!doctype html>
<html>
<head>
<title>Laravel Form Validation!</title>
<!-- load bootstrap -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<style>
body { padding-bottom:40px; padding-top:40px; }
</style>
</head>
<body class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="page-header">
<h1><span class="glyphicon glyphicon-flash"></span> Register! </h1>
</div>
#if ($errors->has())
<div class="alert alert-danger">
#foreach ($errors->all() as $error)
{{ $error }}<br>
#endforeach
</div>
#endif
<!-- FORM STARTS HERE -->
<form method="POST" action="/ducks" novalidate>
<div class="form-group #if ($errors->has('name')) has-error #endif">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" placeholder="Enter your name" value="{{ Input::old('name') }}">
#if ($errors->has('name')) <p class="help-block">{{ $errors->first('name') }}</p> #endif
</div>
<div class="form-group #if ($errors->has('email')) has-error #endif">
<label for="email">Email</label>
<input type="text" id="email" class="form-control" name="email" placeholder="Enter your email id" value="{{ Input::old('email') }}">
#if ($errors->has('email')) <p class="help-block">{{ $errors->first('email') }}</p> #endif
</div>
<div class="form-group #if ($errors->has('password')) has-error #endif">
<label for="password">Password</label>
<input type="password" id="password" class="form-control" name="password">
#if ($errors->has('password')) <p class="help-block">{{ $errors->first('password') }}</p> #endif
</div>
<div class="form-group #if ($errors->has('password_confirm')) has-error #endif">
<label for="password_confirm">Confirm Password</label>
<input type="password" id="password_confirm" class="form-control" name="password_confirm">
#if ($errors->has('password_confirm')) <p class="help-block">{{ $errors->first('password_confirm') }}</p> #endif
</div>
<button type="submit" class="btn btn-success">Submit</button>
</form>
</div>
</div>
</body>
</html>
1. I added 'Artdarek\Neo4j\Neo4jServiceProvider' to providers array in app/config/app.php.
2. I added neo4j configuration in app/config/database.php
'neo4j' => [
'default' => [
'host' => 'localhost',
'port' => 7474,
'username' => null,
'password' => null,
],
],
3. Then I added a controller for that form:
<?php
class DuckController extends BaseController {
public function showWelcome()
{
return View::make('duck');
}
}
4. This is my routes.php.
<?php
Route::get('/', function()
{
return View::make('hello');
});
// route to show the duck form
Route::get('ducks', function()
{
return View::make('duck-form');
});
// route to process the ducks form
Route::post('ducks', array('before' => 'csrf', function()
{
// create the validation rules ------------------------
$rules = array(
'name' => 'required', // just a normal required validation
'email' => 'required|email|unique:ducks', // required and must be unique in the ducks table
'password' => 'required',
'password_confirm' => 'required|same:password' // required and has to match the password field
);
// create custom validation messages ------------------
$messages = array(
'required' => 'The :attribute is really really really important.',
'same' => 'The :others must match.'
);
// do the validation ----------------------------------
// validate against the inputs from our form
$validator = Validator::make(Input::all(), $rules, $messages);
// check if the validator failed -----------------------
if ($validator->fails()) {
// redirect our user back with error messages
$messages = $validator->messages();
// also redirect them back with old inputs so they dont have to fill out the form again
// but we wont redirect them with the password they entered
return Redirect::to('ducks')
->withErrors($validator)
->withInput(Input::except('password', 'password_confirm'));
} else {
// validation successful ---------------------------
// our duck has passed all tests!
// let him enter the database
// create the data for our duck
$duck = new Duck;
$duck->name = Input::get('name');
$duck->email = Input::get('email');
$duck->password = Hash::make(Input::get('password'));
// save our duck
$duck->save();
// redirect ----------------------------------------
// redirect our user back to the form so they can do it all over again
return Redirect::to('ducks')
->with('messages', 'Hooray!');
}
}));
5. This is my model file for form:
<?php
class Duck extends Eloquent {
protected $fillable = array('name', 'email', 'password');
}
6. This is my model for neo4j:
<?php
//use Illuminate\Auth\EloquentUserProvider;
class database extends Eloquent {
public function index($name, $email, $password, $password_confirm) {
$formData = Neo4j::makeNode();
$formData->setProperty('name',$name)
->setProperty('email',$email)
->setProperty('password',$password)
->setProprty('password_confirm',$password_confirm)
->save();
}
}
When I click on that submit button in that form, I get this error:
[ Edit ]
I was working on it:
This is the new error which I got:
Is it a csrf token issue?
It is pointing to:
Route::filter('csrf', function()
{
if (Session::token() != Input::get('_token'))
{
throw new Illuminate\Session\TokenMismatchException;
}
});
I'm unable to resolve it since 5 hours and data isn't getting stored in neo4j DB. How can I fix it?

When using the CSRF Protection Filter, your form must be declared in your blade as such:
{{ Form::open(array('method' => 'POST', 'action' => URL::to("/ducks"))) }}
And closed:
{{ Form::close() }}
This will render the same form in your html as using:
<form method="POST" action="{{ URL::to("/ducks") }}">...</form>
But will also add the hidden _token element that you are missing:
<input type="hidden" name="_token" value="value_of_token"/>
Hope that helps!
Edit
Or, if you don't want to recreate your <form>, you may simply use:
{{ Form::token() }}
Somewhere inside your existing <form> tag to create it.

Your code looks fine, might be you need to run
composer dump-autoload

Related

Laravel validation returns to null using value="{{ old(firstname) }}" and still throw errorbag when i already typed data on textfield

What am I missing here, I am a newbie in Laravel and tried crash course on youtube, when I click the register button previous data returns to null, and the error required messages show up. Tried reading and looking for a solution on the internet came up with nothing. I couldn't figure out what I am missing or what I am doing wrong here.
Register.blade.php
<div class="col-lg-auto justify-content-center">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="{{route('register')}}" method="post">
#csrf
<h1>Register</h1>
<div>
<input type="text" id='firstname' placeholder="First Name" value="{{ old('firstname') }}">
<input type="text" id='lastname' placeholder="Last Name" value="{{ old('lastname') }}">
{{--<div class="error">
#error('firstname')
{{ $message }}
#enderror
</div>--}}
</div>
..........................................
PageController.php this is the controller page
use Illuminate\Http\Request;//validation ito for request
class PagesController extends Controller
{
public function index(){
return view('pages.index');
}
public function register(){
return view('auth.register');
}
public function store(Request $request) {
$this->validate($request, [
'firstname' => 'required|max:20',
'lastname' => 'required|max:20',
'address' => 'required|max:100',
'barangay' => 'required|max:100',
'email' => 'required|email|max:35',
'password' => 'required|confirmed',
]);
dd('store');
}
You missed the name of your inputs,
Try to add the name attribute for each inputs
like the example below :
<input
type="text"
name="firstname" // add this attribute
id='firstname'
placeholder="First Name"
value="{{ old('firstname') }}"
>

validate function not working in laravel form validation Laravel 5.2

Here the signin function is working fine but $this->validate() function returns nothing in view page. tried various method suggested in other Q&As. seems something wrong with helpers.
userController
public function postSignIn(Request $request)
{
$this->validate($request, [
'email' => 'bail|required',
'password' => 'required'
]);
if (Auth::attempt([ 'email' => $request['email'], 'password' => $request['password'] ])){
return redirect()->route('dashboard');
}
return redirect()->back();
}
Login Page
#if ($errors->any())
<div>
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
#endif
<form name="loginForm" action="{{ route('signin') }}" method="post" autocomplete="disable">
<div class="form-group mb-4">
<input type="email" class="form-control {{ $errors->has('email')? 'is-invalid' : ''}}" name="email" aria-describedby="emailHelp" placeholder=" " />
<label for="loginFormInputEmail">Email address</label>
</div>
<div class="form-group mb-4">
<input type="password" class="form-control {{ $errors->has('password')? 'is-invalid' : ''}}" name="password" placeholder="Password" />
<label for="loginFormInputPassword">Password</label>
</div>
Probably another issue would be with $errors not being saved to Session variable $errors and nothing being shown in the view.
Here is an example of the same issue: http://laravel.io/forum/03-28-2016-errors-variable-empty-after-failed-validation
For me the solution defined in the above link worked. Solution: Is in app\Http\Kernel.php Move \Illuminate\Session\Middleware\StartSession::class, from $middlewareGroups to $middleware
Before
After
Source Thrade
: Laravel MessageBag errors array is empty in view but with content if I kill script

Can't see why error is MethodNotAllowedHttpException

I'm trying to make login form in Laravel 4.2 + Sentry . The problem is that when I submit the form I got the error that method is not allowed.
When I check my form in source it has method="POST" and also in the route I've wrote post. What can be the problem?
MethodNotAllowedHttpException
but can't see why? This is the form
{{ Form::open(array('route' => 'check-auth')) }}
<div class="body bg-gray">
{{-- Display flash message --}}
#if (Session::has('flash_message'))
<span style="margin-left:18%; color: #ff0000">{{ Session::get('flash_message') }}</span>
#endif
<div class="form-group">
<input type="text" name="email" class="form-control" placeholder="User email"/>
#if($errors->has('login_errors')) <span class="has-error">{{ $errors->first('email') }}</span> #endif
</div>
<div class="form-group">
<input type="password" name="password" class="form-control" placeholder="User password"/>
</div>
<button type="submit" name="submitbtn" class="btn bg-olive btn-block">Sign me in</button>
</div>
{{ Form::close() }}
Route
Route::post('user-login', ['as'=>'check-auth', 'uses'=>'AuthenticationController#login']);
and controller
public function login()
{
try{
$credentials = array(
'email' => Input::get('email'),
'password' => Input::get('password')
);
$user = Sentry::authenticate($credentials, false);
if($user){
return Redirect::to('dashboard');
}
return Redirect::to('/')->with('title','Login errors');
}
catch(Exception $e){
echo $e->getMessage();
Session::flash('flash_message', 'No access!');
return Redirect::to('/')->with('title','Login errors');
}
}
UPDATE: Error
production.ERROR: Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException in /var/www/html/time/vendor/laravel/framework/src/Illuminate/Routing/RouteCollection.php:210
You're route is correct, the only thing I could suggest would be to append the type to the opening of the form:
{{ Form::open(['url' => 'check-auth', 'method' => 'post']) }}
{{ Form::open(array('route' => 'check-auth')) }}
See, You are using route check-auth and in routes file you defined a different route i.e user-login
Route::post('user-login', ['as'=>'check-auth', 'uses'=>'AuthenticationController#login']);
Correct route and try again this will work
Instead of post use get (it can still post things but your are able to retrieve too)

Laravel 5 Add errors in an array using After Validation Hook

I'm trying to add a function in my app where users are allowed to change their account password. I have three fields and my view looks like this:
<form class="form" role="form" action="{{ url('users/updatePassword') }}" method="post">
{{ csrf_field() }}
<div class="form-group label-floating {{ $errors->has('oldpassword') ? 'has-error' : '' }}">
<label class="control-label" for="oldpassword">Old Password</label>
<input type="password" name="oldpassword" class="form-control">
#if ($errors->has('oldpassword'))
<span class="help-block">
<strong>{{ $errors->first('oldpassword') }}</strong>
</span>
#endif
</div>
<div class="form-group label-floating {{ $errors->has('newpassword') ? 'has-error' : '' }}">
<label class="control-label" for="newpassword">New Password</label>
<input type="password" name="newpassword" class="form-control">
#if ($errors->has('newpassword'))
<span class="help-block">
<strong>{{ $errors->first('newpassword') }}</strong>
</span>
#endif
</div>
<div class="form-group label-floating">
<label class="control-label" for="newpassword_confirmation">Confirm Password</label>
<input type="password" name="newpassword_confirmation" class="form-control">
</div>
<div class="form-group">
<button class="btn btn-raised btn-primary">Change</button>
</div>
</form>
Firstly, I want to check if all fields are completely filled up and for that I used Validator. And then check if the oldpassword is match from the database so I use if (Auth::attempt(array('password' => $request->oldpassword))) condition. I also found in the laravel 5.2 documentation the After Validation hook. I don't know what is wrong but it seems it don't validates the oldpassword field when I typed a wrong password.
My controller:
$validator = Validator::make($request->all(), [
'oldpassword' => 'required|max:255',
'newpassword' => 'required|min:6|max:255|confirmed',
]);
$validator->after(function($validator) use($request) {
if (Auth::attempt(array('password' => $request->oldpassword))) {
$validator->errors()->add('oldpassword', 'Old password dont match in our database.');
}
});
if ($validator->fails()) {
// Toastr
$title = "Oops!";
$message = "Please make sure to fill all required fields.";
$options = [
'progressBar' => false,
'positionClass' => 'toast-top-right',
'timeOut' => 6000,
];
Toastr::error($message, $title, $options);
return redirect()->back()
->withErrors($validator);
} else {
return 'success'; // for testing only
}
Any idea regarding this?
According to your code when you enter correct oldpassword you get the error. So change if(Auth::attempt..... to if(!Auth:attempt.... And also if you use Auth:attempt you have to logout user again(this method also requires unique field like username or email to identify the user). so it's better if you use following method
if (!\Hash::check($request->get('oldpassword'), \Auth::user()->password)) {
$validator->errors()->add('oldpassword', 'Old password dont match in our database.');
}

Laravel 5.2 Validation Error not appearing in blade

I want to show validation Error in View page while user giving wrong input. It's Ok that it's not saving anything in database while a user giving wrong input. But there is no error message in user view page. If anyone find the error, please help me out.
Here is the controller:
public function saveUser(Request $request){
$this->validate($request,[
'name' => 'required|max:120',
'email' => 'required|email|unique:users',
'phone' => 'required|min:11|numeric',
'course_id'=>'required'
]);
$user = new User();
$user->name= $request->Input(['name']);
$user->email= $request->Input(['email']);
$user->phone= $request->Input(['phone']);
$user->date = date('Y-m-d');
$user->completed_status = '0';
$user->course_id=$request->Input(['course_id']);
$user->save();
return redirect('success');
}
Here is the route:
Route::group(['middleware' => 'web'], function () {
Route::get('/', function () {
return view('index');
})->name('main');
Route::post('/saveUser',[
'uses' => 'AppController#saveUser',
'as'=>'saveUser',
]);
});
Here is the blade view page:
#extends('layouts.master')
#section('title')
Create User
#endsection
#section('content')
#include('partials.message-block')
<div class="container" >
<h3> Student Register </h3>
{!! Form::open(array('route' => 'saveUser','class'=>'form-horizontal','method'=>'POST')) !!}
{!! Form::token(); !!}
{!! csrf_field() ; !!}
<div class="form-group">
<label>Name</label>
<input type="text" name="name" class="form-control" required placeholder="Name">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" class="form-control" required placeholder="email">
</div>
<div class="form-group">
<label>Phone Number</label>
<input type="text" name="phone" class="form-control" required placeholder="phone">
</div>
<div class="form-group">
<label for="">Class</label>
<select class="form-control input-sm" name="course_id" >
#foreach($input as $row)
<option value="{{$row->id}}">{{$row->name}}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
{!! Form::close() !!}
</div>
#endsection
And here is the error-message block:
#if(count($errors) > 0)
<div class="row">
<div class="col-md-4 col-md-offset-4 error">
<ul>
#foreach($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
</div>
</div>
#endif
#if(Session::has('message'))
<div class="row">
<div class="col-md-4 col-md--offset-4 success">
{{Session::get('message')}}
</div>
</div>
#endif
Try to remove web middleware if you're using 5.2.27 or higher. The thing is now Laravel automatically applies web middleware to all routes inside routes.php and if you're trying to add it manually you can get errors.
app/Providers/RouteServiceProvider.php of the 5.2.27 version now adds web middleware to all routes inside routes.php:
protected function mapWebRoutes(Router $router)
{
$router->group([
'namespace' => $this->namespace, 'middleware' => 'web',
], function ($router) {
require app_path('Http/routes.php');
});
}
Use Below line in your controller
use Validator;
Add below code in your controller function where your request is sent.
$validator = Validator::make($request->all(), [
'fname' => 'required|max:20|min:4',
'uemail' => 'required|email',
'message' => 'required',
]);
if ($validator->fails()) {
$messages = $validator->messages();
return Redirect::back()->withErrors($messages)->withInput($request->all());
}
In your view page
#if ($errors->any())
<label for="fname" class="error">{{ $errors->first('fname') }}</label>
#endif
For display individual field wise error.
if you are using laravel 5.2+ then please use the below code.
Moved \Illuminate\Session\Middleware\StartSession::class and \Illuminate\View\Middleware\ShareErrorsFromSession::class from web $middlewareGroups to $middleware in app\Http\Kernel.php
Alexey is correct and if you're not comfortable with that then you can just add this code into your view for the session messages to show.
#if(Session::has('message'))
<div class="alert alert-success">{{Session::get('message')}}</div>
#endif
#if(count($errors)>0)
<ul>
#foreach($errors->all() as $error)
<li class="alert alert-danger">{{$error}}</li>
#endforeach
</ul>
#endif
I've done this in laravel 5.5. Please do confirm if this helps you out.

Categories