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

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>

Related

how to validate (check) data table values befour data insert in Laravel 5.2

I need validate and generate error message if same user try to insert existing project_name to the table in Laravel 5.2. My project table like this
user_id project_name
1 abc
2 sdf
3 kju
My project data store controller as follow
public function store(Request $request)
{
$this->validate($request, [
'name' => 'required|min:3'
]);
$project = new Project;
$project->project_name = $request->input('name');
$project->user_id = Auth::user()->id;
$project->save();
return redirect()->route('projects.index')->with('info','Your Project has been created successfully');
}
and I have alert.blade.php file as
#if ( session()->has('info'))
<div class="alert alert-info" role-"alert">
{{ session()->get('info') }}
</div>
#endif
#if ( session()->has('warning'))
<div class="alert alert-danger" role-"alert">
{{ session()->get('warning') }}
</div>
#endif
how can I do this?
If your form validation is failed then a 422(Unprocessable) response is returned by laravel. And an $error variable will be available in the response. So you can check if the variable is empty or not, and you can display the errors.
Like Below code. This is from laravel 5.2 documentation.
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
https://laravel.com/docs/5.2/validation
You could foreach the variable $errors if you want catch the error message,
or if you are asking the validation rule, you could use 'exists:database'
https://laravel.com/docs/5.2/validation#rule-exists

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

Displaying errors with Laravel Form validation

I am learning Laravel. I am doing Form Validation at the moment. In the documentation it is said the variable $errors is flashed to the session and is always available. I get an exception because an undefined variable. I only pasted the sample code from the documentation:
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Error message:
ErrorException in 318c473e4384f7c25db0019a770ee937b30041d1.php line 41: Undefined variable: errors (View: C:\xampp\htdocs\NightClubs\resources\views\add.blade.php)
This are the validation rules in the controller:
$this->validate($request, [
'youtube' => 'required|url',
'coordinatex' => 'required|between:-180,180',
'coordinatey' => 'required|between:-90,90',
'nameofclub' => 'required'
]);
Try to use the group for routes where you want to use $errors variable:
Route::group(['middleware' => ['web']], function () {
// Your routes
// Your routes
}
I assume you have validation rules in your controller.
Try this in your view
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif

Laravel Getting Error with Validations

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.

Categories