Laravel : On 5.5 validation message not showing on view.blade - laravel

Validation not showing any message on view page. I just can't figure out.
My controller code
public function save(Request $request) {
try {
$file = $request->file('flag_image');
$this->validate($request, Country::rules()); // checking validation
/*Image Upload code*/
If(Input::hasFile('flag_image')){
$file = Input::file('flag_image');
$destinationPath = public_path(). '/images/admin/country/';
$filename = $file->getClientOriginalName();
$image = time().$filename;
$file->move($destinationPath, $image);
$imgpath = 'images/admin/country/'.$image;
}
if($file !="") {
$request->merge(['flag_image' => $imgpath]);
}
/*Image Upload code end*/
$country = Country::saveOrUpdate($request);
if($file !="") {
$country->flag_image = $imgpath;
$country->save();
}
if($country !== false) {
return redirect()->route('lists-country')->with('success', trans('Country data added successfully.!!'));
} else {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
} catch (\Exception $ex) {
return back()->with('error', "Unable to save country data.!!")->withInput();
}
}
Here is my model code for validation check :
public static function rules() {
return [
'title' => 'required|string|max:255',
'short_name' => 'required',
'status' => 'required|string|in:' . implode(",", Country::STATUSES)
];
}
On view page didn' get any validation message : On my view
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div> #endif
Also added in a app/exceptions/handler.php file code
protected $dontReport = [
\Illuminate\Auth\AuthenticationException::class,
\Illuminate\Auth\Access\AuthorizationException::class,
\Symfony\Component\HttpKernel\Exception\HttpException::class,
\Illuminate\Database\Eloquent\ModelNotFoundException::class,
\Illuminate\Session\TokenMismatchException::class,
\Illuminate\Validation\ValidationException::class,
];
Not working at all.what am i missing ?

Try using -
#if (session()->has('error'))
<div class="alert alert-danger">
<ul>
<li>{{ session('error') }}</li>
</ul>
</div>
#endif
In this way you can access only the key, that has been set by with methods

Change this line:
$this->validate($request, Country::rules());
To:
$request->validate(Country::rules());

Related

Test Driven Laravel : Invalid Argument supplied for foreach

So i have a form with multiple fields like below
<ul class="list-group list-group-flush">
#foreach ($group as $perm)
<li class="list-group-item">{{$perm->name}}
<div class="float-right">
<select name="perms[{{$perm->id}}]" class="form-control">
<option value="1">Yes</option>
<option value="0" selected>No</option>
</select>
</div>
</li>
#endforeach
</ul>
My controller is like below
public function permission(int $id)
{
$permission = request()->perms;
foreach ($permission as $perm => $status)
{
if($status == 1)
{
//echo $perm . " " . $status;
$user_perm = User_perms::create([
'user_id' => $id,
'perm_id' => $perm,
]);
}
}
$user = Users::find($id);
return redirect($user->path());
}
This code does what I want but I have a test
public function permissions_applied_for_user()
{
$this->withoutExceptionHandling();
//create a user
$this->post('/users/add', $this->data());
$user = Users::first();
//first clear out all data from user_perm table for specific user
$response = $this->post('/users/permission/' . $user->id, [
'user_id' => $user->id,
'perm_id' => '1',
]);
$this->assertCount(1, User_perms::all());
$response->assertRedirect('/users/view/' . $user->id);
//$response->assertOk();
//second insert all new permissions into the table
}
which throws the exception invalid argument supplied for foreach any advice on what I'm doing wrong?

Laravel problem insert multiple images to session on multi-form

I have multiple form that i followed on https://github.com/5balloons/multi-step-form-laravel, every input was going well except when i input the multiple images. It cannot inserted to session. I'm using multiple session object to insert that corresponds with each model. Here are my codes:
I tried various things and ends up with the object returns null when i used dd()
View
<div class="form-group">
<label for="images">Foto-foto Properti</label>
<input type="file" {{(!empty($secondaryImage->images)) ? "disabled" : ''}} id="images" name="images[]" required autofocus multiple>
#if ($errors->has('images'))
<span class="invalid-feedback" style="color:red" role="alert">
<strong>{{ $errors->first('images') }}</strong>
</span>
#endif
</div>
Controller
public function submitStep2(Request $request)
{
$property = $request->session()->get('property');
$secondary = new Secondary();
$secondaryImage = new SecondaryImage();
$validated = $request->validate([
'no_listing' => 'required|string',
'nama_marketing' => 'required|string',
'address' => 'required|string',
]);
// Secondary
if(empty($request->session()->get('secondary'))) {
$secondary->fill($validated);
$request->session()->put('secondary', $secondary);
} else {
$secondary = $request->session()->get('secondary');
$request->session()->put('secondary', $secondary);
}
// SecondaryImage
if(!isset($secondaryImage->images)) {
$imgreq = $request->validate([
'images' => 'required',
'images.*' => 'image|mimes:jpeg,png,jpg|max:2048',
]);
$gambar = $request->file('images');
if($request->hasFile('images')) {
foreach ($gambar as $img) {
$imgsname = date('YmdHis').'-'.$img->getClientOriginalName();
$pathimgs = $img->storeAs('public/filesSession', $imgsname);
$secondaryImage->images = $pathimgs;
$images[] = $imgsname;
}
}
$secondaryImage = $request->session()->get('secondaryImage');
// $secondaryImage->fill($imgreq);
$request->session()->put('secondaryImage', $secondaryImage);
}
dd($request->session()->all());
return redirect()->route('admin.secondary.create.step3');
}
This works perfectly for me on laravel 5.7
$images= $request->file('images');
if ($images!= null) {
foreach ($images as $image) {
if ($request->hasFile('images')) {
$imagePath = $request->file('image')->store('whateverFolder');
$getimageName = time() . '.' . $request->image->getClientOriginalExtension();
$request->image->move(public_path('whateverFolder'), $getimageName);
}
}
}

Laravel validation not working after submit

This did not show the errors after submit
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
$this->validate($request,[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
Inserting values into the database.I want to validate on submitting the form
public function store(Request $request)
{
//
$this->validate($request->all(),[
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
I displayed errors like this, but not working for me
#if(count($errors) > 0)
<div class="alert alert-danger">
#foreach($errors->all() as $error)
<p>{{ $error }}</p>
#endforeach
</div>
#endif
Add this piece of code on your controller method.
return back()->withErrors()->withInput()
you can also access old input value with old(field_name)
Use ->all() here to provide all input value in to validate
$this->validate($request->all(),[
Or you can try like this
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
// The blog post is valid...
}
And display error as
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
first, edit your method like this :
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Cars;
use App\Images;
use DB;
use Validator;
and inside this method please edit your redirect route and make sure your redirect url, redirect you in the page that had the error message:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name'=>'required|min:3',
'specifications'=>'required|min:10'
]);
if ($validator->fails()) {
return redirect(route('make your route here '))
->withErrors($validator)
->withInput();
}
$cars = New Cars;
$cars->name = $request->name;
$cars->specifications = $request->specifications;
$cars->price = $request->price;
$cars->model_id = $request->model_id;
$cars->year = $request->year;
$cars->milage = $request->milage;
if($cars->save()) {
$id = DB::getPdo()->lastInsertId();
}
return redirect('home');
}
and for displaying error messages inside your blade template make this :
#if(!empty($errors))
#if($errors->any())
<div class="alert alert-danger">
<ul>
#foreach($errors->all() as $error)
<li>{!! $error !!}</li>
#endforeach
</ul>
</div>
#endif
#endif

Laravel return flash message

I am trying to return a flash message depending on the outcome of an function however I don't really know how to do this properly, can someone help me with fixing this?
Controller:
public function postDB(Requests\NameRequest $request) {
$newName = trim($request->input('newName'));
$newLat = $request->input('newCode');
$websites = new Website();
$websites->name = $newName;
$websites->html = $newLat;
$websites->save();
if ($websites->save())
{
$message = 'success';
}else{
$message = 'error';
}
return redirect()->back()->withInput()->with('message', 'Profile updated!');
}
Request:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
'img' => 'file|image',
];
}
public function messages()
{
return [
'img.image' => 'File type is not supported! Use files with extension .jpg/.jpeg/.gif',
];
}
Template:
#if (session('status'))
#if (session('status')=="success")
<div class="alert alert-success">
{{ session('message') }}
</div>
#else
<div class="alert alert-error">
{{ session('message') }}
</div>
#endif
#endif
Route:
Route::group(['middleware' => ['web']], function () {
Route::get('home', 'BuilderController#homepage');
Route::get('pages', 'BuilderController#websites');
Route::get('template', 'BuilderController#templates');
Route::post('template2', 'BuilderController#postDB');
Route::post('template', 'BuilderController#testing');
Route::get('logout', 'BuilderController#getLogout');
Route::get('/website/{name}', 'BuilderController#website');
});
Solution :
There could be only one reason for this issue.
The laravel will pass the flash messages only if it's registered inside the middleware web
i.e.,
Route::group(['middleware' => ['web']], function () {
//The back()'s url should be registered here
});
Update :
It seems you need to redirect back with message and inputs
So, You can do like this
if ($request->hasFile('img')) {
$message = 'success';
} else {
$message = 'error';
}
return redirect()->back()->withInput()->->with('message', $message);
Update 2 :
#if (session('status'))
#if (session('status')=="success")
<div class="alert alert-success">
Congrats! Everything was fine
</div>
#else
<div class="alert alert-error">
Oops! Something went wrong
</div>
#endif
#endif
Note : You can pass the status param to your wish
If you pass message as a flash parameter name, use it, not status.
#if (session('message'))
#if (session('message')=="success")
<div class="alert alert-success">
Congrats! Everything was fine
</div>
#else
<div class="alert alert-error">
Oops! Something went wrong
</div>
#endif
#endif

laravel pass validation error to custom view

I created a validation but cant show it on view, its important to return search view and don't redirect back user. help me please, thanks all?
Controller :
public function search(Request $request)
{
$msg = Validator::make($request->all(), [
'search' => 'required'
]);
if ($msg->fails()) {
return view('layouts.search')->withErrors($msg->messages());
} else {
return "Thank you!";
}
}
View :
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error}} </li>
#endforeach
</ul>
#else
You can use $error->first('name_of_error_field') to show error messages.
You can do it like this:
public function search(Request $request)
{
$validator = Validator::make($request->all(), [
'search' => 'required'
]);
if ($validator->fails()) {
return view('layouts.search')->withErrors($validator); // <----- Send the validator here
} else {
return "Thank you!";
}
}
And in view:
#if($errors->any())
<ul class="alert alert-danger">
#foreach($errors as $error)
<li> {{$error->first('name_of_error_field')}} </li>
#endforeach
</ul>
#endif
See more about Laravel Custom Validators
Hope this helps

Resources