Laravel Getting Error with Validations - php

I am trying to Get Validation Errors on index.blade.php having issues:
When I fill both the fields then it goes well if i just put an Echo or Return in getLogin Controller.
When I just fill one field and it works good if i just put and echo or Return but not giving validation errors, with Validation Errors it only shows, "Something went Wrong"
Code for index.blade.php
<section class="mainWrap">
<div class="headingfirst"><img src="{{ URL::asset('css/des.png') }}" width="78"></div>
<div class="sedhead">Hey User!!!! Try to Login</div>
<div class="againtext">Sign In To Your Account</div>
<article class="FormContainer">
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
<img class="profile-img" src="{{ URL::asset('css/avatar_2x.png')}}">
{{ Form::open(array('class'=> 'SetMe')) }}
{{ Form::text('email',null, array('placeholder'=>'Email','class'=>'insi')) }}
{{ Form::password('password',array('placeholder'=>'Password','class'=>'dnsi')) }}
{{ Form::submit('Sign In', array('class'=>'SignIn')) }}
{{ Form::close() }}
</article>
</section>
Code for AuthController.php
<?php
class AuthController extends Controller{
public function GetLogin() {
return View::make('layouts.index');
}
public function LogInfo() {
$rules = array('email' => 'required','password' =>'required');
$validator = Validator::make(Input::all(),$rules);
if($validator->fails()){
return Redirect::route('login')
->withErrors($validator);
}
else{
}
}
}
Code for Routes.php
Route::get('login', array('uses'=>'AuthController#GetLogin' ));
Route::post('login', array('uses'=>'AuthController#LogInfo'));
even when i put the Auth Code it don't show anything except "Something goes wrong". but while working with just Echos it works properly

In validation failed statement,
You need to use return Redirect::to('login') instead of return Redirect::route('login').
In index.blade.php, it should be like -
#foreach($errors->all() as $error)
<div class="errors">{{ $error }} </div>
#endforeach
instead of
#foreach($errors as $error)
<div class="errors">{{ $error }} </div>
#endforeach
Also here is my suggestion. if you are currently developing an application using laravel, it is the best to enable debug. Open laravel/app/config/app.php and make sure 'debug' => 'true'. It will help you see what is detailed error messages with stack traces.

Related

Call to a member function any() on string in Laravel

I'm trying to access the $errors variable to my view but it returns an error. Please see my code below.
Controller
$validator = Validator::make($request->all(), [...]);
if($request->required == 1){
$validator = Validator::make($request->all(), [...]);
}
if($validator->fails()){
return Redirect::back()->withErrors($validator)->withInput();
}
View
#if($errors->any())
... Some HTML code here
#endif
Error
Call to a member function any() on string
Any idea? This should work, but it is not.
Reference: https://laravel.com/docs/5.5/validation#quick-displaying-the-validation-errors
Laravel version: 5.5
You need to change your line as per below:
From
return Redirect::back()->withErrors($validator)->withInput();
To
return Redirect::back()->withErrors($validator->errors())->withInput();
Then in you blade file you can access it as:
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
I use validation in view like this below
<div class="{{'form-group required'.$errors->first('name',' has-error')}}">
<label>Title</label>
<input type="text" name="name" class="form-control" required>
<div class="text-danger">{{$errors->has('name') ? $errors->first('name') : ''}}</div>
</div>

form validation not working in laravel

I am working on laravel 5.3.30 and created a profile page with form and try to validate the data when the form is submitted but I am not getting any errors after submitting the form, its just refresh the page.
Route File:
Route::get('/', function () {
return view('main');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
Route::get('logout', '\App\Http\Controllers\Auth\LoginController#logout');
Route::resource('profile','ProfileController');
Profile Form:
{!! Form::open(array('route'=>'profile.store')) !!}
<div class="form-group">
{{Form::label('first_name','Firstname')}}<span class="required">*</span>
{{Form::text('first_name',null,['class'=>'form-control','placeholder'=>'Enter Firstname'])}}
</div>
<div class="form-group">
{{Form::label('last_name','Lastname')}}<span class="required">*</span>
{{Form::text('last_name',null,['class'=>'form-control','placeholder'=>'Enter Lastname'])}}
</div>
{{Form::submit('Create',array('class'=>'form-submit btn btn-success btn-block btn-lg'))}}
{!! Form::close() !!}
Validation in Profile Controller:
public function store(Request $request)
{
$this->validate($request,array(
'first_name'=>'required|max:255',
'last_name'=>'required|max:255'
));
}
When I submit the form without filling anything, it just refresh the page and does not show any errors. Please suggest something. Thanks in advance.
It looks like you forget to send error from controller and print in view.
here is controller code should look like
public function store(Request $request)
{
$this->validate($request,array(
'first_name'=>'required|max:255',
'last_name'=>'required|max:255'
));
// include this line incase of validation error
return $validator->errors()->all();
}
You need to print error in view in order to know user
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Laravel 5.2 redirect back with success message

I'm trying to get a success message back to my home page on laravel.
return redirect()->back()->withSuccess('IT WORKS!');
For some reason the variable $success doesn't get any value after running this code.
The code I'm using to display the succes message:
#if (!empty($success))
<h1>{{$success}}</h1>
#endif
I have added the home and newsletter page to the web middleware group in routes.php like this:
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/', function () {
return view('home');
});
Route::post('/newsletter/subscribe','NewsletterController#subscribe');
});
Does anyone have any idea why this doesn't seem to work?
You should remove web middleware from routes.php. Adding web middleware manually causes session and request related problems in Laravel 5.2.27 and higher.
If it didn't help (still, keep routes.php without web middleware), you can try little bit different approach:
return redirect()->back()->with('message', 'IT WORKS!');
Displaying message if it exists:
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
you can use this :
return redirect()->back()->withSuccess('IT WORKS!');
and use this in your view :
#if(session('success'))
<h1>{{session('success')}}</h1>
#endif
Controller:
return redirect()->route('subscriptions.index')->withSuccess(['Success Message here!']);
Blade
#if (session()->has('success'))
<div class="alert alert-success">
#if(is_array(session('success')))
<ul>
#foreach (session('success') as $message)
<li>{{ $message }}</li>
#endforeach
</ul>
#else
{{ session('success') }}
#endif
</div>
#endif
You can always save this part as separate blade file and include it easily.
fore example:
<div class="row">
<div class="col-md-6">
#include('admin.system.success')
<div class="box box-widget">
You can simply use back() function to redirect no need to use redirect()->back() make sure you are using 5.2 or greater than 5.2 version.
You can replace your code to below code.
return back()->with('message', 'WORKS!');
In the view file replace below code.
#if(session()->has('message'))
<div class="alert alert-success">
{{ session()->get('message') }}
</div>
#endif
For more detail, you can read here
back() is just a helper function. It's doing the same thing as redirect()->back()
One way to do that is sending the message in the session like this:
Controller:
return redirect()->back()->with('success', 'IT WORKS!');
View:
#if (session()->has('success'))
<h1>{{ session('success') }}</h1>
#endif
And other way to do that is just creating the session and put the text in the view directly:
Controller:
return redirect()->back()->with('success', true);
View:
#if (session()->has('success'))
<h1>IT WORKS!</h1>
#endif
You can check the full documentation here: Redirecting With Flashed Session Data
I hope it is very helpful, regards.
All of the above are correct, but try this straight one-liner:
{{session()->has('message') ? session()->get('message') : ''}}
In Controller
return redirect()->route('company')->with('update', 'Content has been updated successfully!');
In view
#if (session('update'))
<div class="alert alert-success alert-dismissable custom-success-box" style="margin: 15px;">
×
<strong> {{ session('update') }} </strong>
</div>
#endif
You can use laravel MessageBag to add our own messages to existing messages.
To use MessageBag you need to use:
use Illuminate\Support\MessageBag;
In the controller:
MessageBag $message_bag
$message_bag->add('message', trans('auth.confirmation-success'));
return redirect('login')->withSuccess($message_bag);
Hope it will help some one.
Adi
in Controller:
`return redirect()->route('car.index')->withSuccess('Bein ajoute')`;
In view
#if(Session::get('success'))
<div class="alert alert-success">
{{session::get('success')}}
</div>
#endif

Laravel Auth Redirect to Previous Page

I am attempting to create a single page like application with Laravel 4. When the user arrives at the site, they should be prompted to log in. Once the user logs in, the view (not the URL) will switch and the user will be able to see information as if they are authenticated.
My HTML (if authroized should show "Auth" in h1, if not, it shows login form)
<div class="container">
#if(Auth::check())
<h1>Auth</h1>
#else
{{ Form::open(array('url'=>'login', 'method'=>'post')) }}
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('email', 'Email Address') }}
{{ Form::text('email', Input::old('email'), array('class'=>'form-control', 'placeholder'=>'example#test.com')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<div class="form-group">
{{ Form::label('password', 'Password') }}
{{ Form::password('password', array('class'=>'form-control')) }}
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12">
{{ Form::submit('Log In', array('class'=>'btn btn-primary pull-right')) }}
</div>
</div>
{{ Form::close() }}
#endif
</div>
Controller
class SiteController extends BaseController {
public function getIndex()
{
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
return Redirect::route('index');
}
}
}
My user model is the default that ships with Laravel 4. As of now, I am passing the Auth::attempt and getting the return Redirect::route('index');, but the #if(Auth::check()) doesn't seem to be firing. Instead it continues to show me the log in form. Am I doing something wrong here?
I don't see anything wrong here, but you need to be sure what's happening, it looks like your authenticated session is not sticking, but to be sure you could:
<?php
class SiteController extends BaseController {
public function getIndex()
{
Log::info('index - authed: '. Auth::check() ? 'yes' : 'no');
return View::make('index');
}
public function postLogin() {
$email = Input::get('email');
$password = Input::get('password');
if (Auth::attempt(array('email'=>$email, 'password'=>$password)))
{
Log::info('postLogin - attempt successful');
return Redirect::route('index');
}
Log::info('postLogin - error on attempt');
}
}
And then check your logs:
php artisan tail

Laravel3: Loading a content inside a content dynamically

I have a form. When user submits the form and gets error, I show it like this:
Register Controller
return View::make('theme-admin.user_add')->with('error_msg', validation->errors->first());
register.blade.php
#if($error_msg !== null)
<div class="alert red hideit max">
<div class="left">
<span class="red-icon"></span>
<span class="alert-text">{{ $error_msg }}</span> <-- Error message is visible here.
</div>
<div class="right">
<a class="close-red"></a>
</div>
</div>
#endif
//
Actual HTML Form
//
However, I want to move that error div into a blade file. (error.blade.php) and I want to call it with parameters when there is an error.
It will look like this.
NEW register.blade.php
{{ MESSAGE_CONTENT }} //This should be replaced with error.blade.php dynamically
//
Actual HTML Form
//
MESSAGE_CONTENT will be included via error.blade.php
error.blade.php
<div class="alert red hideit max">
<div class="left">
<span class="red-icon"></span>
<span class="alert-text">{{ $message }}</span> <-- Error message is visible here.
</div>
<div class="right">
<a class="close-red"></a>
</div>
</div>
Let's say form failed and I got some errors. I will load error.blade.php so messages will get RED background etc.
Something like this;
return View::make('theme-admin.user_add')->with(message_content', (Load error.blade.php here))->with('message', $validation->errors->first();
If the form succeeds, I'll just load success.blade.php in messages area and messages will look with GREEN background.
return View::make('theme-admin.user_add')->with(message_content', (Load success.blade.php here))->with('message', 'You successfully registered');
You probably got the logic.
How can I do this?
Ps. Image example: http://i.imgur.com/QExAiuA.png
A clean solution may be to have a simple alert object with a type and msg.
//in controller
$alert->type = 'error'; // or 'success'
$alert->class = 'red'; // or 'green'
$alert->msg = $validation->errors->first(); // or 'You successfully registered'
return View::make('theme-admin.user_add')->with('alert', $alert);
//register.blade.php
#include('alert')
//Actual HTML Form
//alert.blade.php
#if(isset($alert))
<div class="alert {{$alert->class}} hideit max">
<div class="left">
<span class="red-icon"></span>
<span class="alert-text">{{ $alert->msg }}</span>
</div>
<div class="right">
<a class="close-{{$alert->class}}"></a>
</div>
</div>
#endif
You should create your view (View::make()) in a route defined for GET, and then handle your form input in your POST route:
//routes.php
Route::get('admin/adduser', array('as' => 'adduser', 'do' => function()
{
return View::make('theme-admin.user_add');
}));
//route for handling form input
Route::post('register', array('before' => 'csrf', function()
{
$rules = array(
//your vailidation rules here..
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->fails())
{
//re-populate form if invalid values, so add flashing input by with_input()
//also pass errors by using with_errors
return Redirect::to('adduser')->with_input()->with_errors($validation);
}
else {
//use the named route we defined in Route:get above
return Redirect:to('adduser')->with('message', 'Successfully added the new user!');
}
}));
There is no need to create new views for dislaying error and success messages. If you want to seperate your success and error into their own blade templates then you could use the following in your adduser.blade.php:
//adduser.blade.php
#if($errors->has())
#include('errormsg'); //use {{ $errors->first() }} or #foreach($errors->all() as $message) to print error message(s)
#else
#include('success'); //use {{ $message }} to print success
#endif
However you can also use sections in your view, and instead put both the success and error message inside the same view:
//feedback.blade.php
#section('error')
<em class="error">{{ $errors->first() }}</em>
#endsection
#section('success')
<em class="success">{{ $message }}</em>
#endsection
//adduser.blade.php
#include('feedback');
#if($errors->has())
#yield('error');
#else
#yield('success');
#endif
Hope that helps.
I found the solution myself. I needed Nested Views feature.
$view = View::make('home');
$view->nest('content', 'orders', array('orders' => $orders));
Refer to Laravel documentation for more information.

Categories