How to seperate validation error list in laravel - laravel

Code in blade
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Name: <input type="text" name="name">
Phone: <input type="text" name="phone">
Email: <input type="text" name="email">
Validation Code
$data = $this->validate($request,[
'name' => 'required',
'phone' => 'required',
'email' => 'required',
]);
I wanna display each error under its input field.

You have to add error message after input field
<div class="form-group {{ $errors->has('name') ? 'has-error' : ''}}">
<label for="name" class="col-sm-3 control-label">Name: </label>
<div class="col-sm-7">
<input class="form-control" required="required" name="name" type="text" id="name">
{{ $errors->first('name', '<p class="help-block">:message</p>') }}
</div>
</div>

To display each error seperatly you can just use $errors->first() and pass in the field name you're requesting. See the following example.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Name: <input type="text" name="name">
{{ $errors->first('name') }}
Phone: <input type="text" name="phone">
{{ $errors->first('phone') }}
Email: <input type="text" name="email">
{{ $errors->first('email') }}
Notice after each field I call $errors->first()

Name: <input type="text" name="name">
<small class="text-danger">{{ $errors->first('name') }}</small>
Phone: <input type="text" name="phone">
<small class="text-danger">{{ $errors->first('phone') }}</small>
Email: <input type="text" name="email">
{{ $errors->first('email') }}
If condition is not needed if u don't want to show all errors at a place.
Also, two types the error message can be display
{{ $errors->first('name') }}
<small class="text-danger">{{ $errors->first('phone') }}</small>

Related

my project laravel when i click submit in form with errors in input my view refresh multiple time so i can't see message errors

this problem exist in chrome and not exist in opera
this my view code here i try to do form with validate and div with type of errors:
#if(count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="add" method="POST">
{{ csrf_field() }} <!--Securite-->
Product name <input type="text" value="{{ Request::old('name') }}" class="form-control {{ $errors->has('name') ? 'is-invalid' : ''}}" name="name" placeholder="enter product">
<br>
Product Price <input type="text" class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" value="{{ Request::old('price') }}" name="price" placeholder="enter price">
<br>
<input type="submit" value="Add Product">
</form>
#endsection
try this one .
this will be a function in your controller.
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'price' => 'required'
]);
if ($validator->fails()) {
return redirect('your-view-name')
->withErrors($validator)
->withInput();
}
}
Errors on view with foreach
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Your Form
<form action="{{url('/route-name')}}" method="POST">
#csrf
Product name <input type="text" value="{{ Request::old('name') }}" class="form-control {{ $errors->has('name') ? 'is-invalid' : ''}}" name="name" placeholder="enter product">
<br>
Product Price <input type="text" class="form-control {{ $errors->has('price') ? 'is-invalid' : '' }}" value="{{ Request::old('price') }}" name="price" placeholder="enter price">
<br>
<input type="submit" value="Add Product">
</form>

if data exist submit button turn into update function (Laravel)

i have this form, what i wanted to do is if the data for this id is exist, my submit button turn into update function.
i still use store data function for my controller because i didnt know how to do the logic.
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'description' => 'required',
'category_page_id' => 'required',
]);
$seo = new Seo;
$seo->category_page_id = $request->input('category_page_id');
$seo->title = $request->input('title') ?? '';
$seo->description = $request->input('description');
$seo->save();
return back()->withStatus(__('SEO successfully updated.'));
}
and this is the form for my update function
<form method="post" action="{{ route('seo.update') }}" autocomplete="off">
#csrf
#method('put')
<h3 class="heading-small mb-4">{{ __('PAGE SEO') }}</h3>
#if (session('status'))
<div class="alert alert-success alert-dismissible fade show" role="alert">
{{ session('status') }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
<div class="pl-lg-4">
<div class="form-group{{ $errors->has('category_page_id') ? ' has-danger' : '' }}">
<div class="form-group form-box">
<label for="category_page_id">Page</label>
<select class="form-control form-control-alternative{{ $errors->has('category_page_id') ? ' is-invalid' : '' }}" name="category_page_id">
#foreach ($categorypages->slice(0, 1) as $key => $value)
<option value="{{ $value->id }}" #if (old('category_page_id') == $value->id) {{ 'selected' }} #endif>{{ $value->name }}</option>
#endforeach
</select>
#error('category_page_id')
<small class="text-red">{{ $message }}</small>
#enderror
</div>
</div>
<div class="form-group{{ $errors->has('title') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-title">{{ __('SEO Title') }}</label>
<input type="text" name="title" id="input-title" class="form-control form-control-alternative{{ $errors->has('title') ? ' is-invalid' : '' }}" placeholder="{{ __('title') }}" value="{{ old('title', $seo->title) }}" required autofocus>
#if ($errors->has('title'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
<div class="form-group{{ $errors->has('description') ? ' has-danger' : '' }}">
<label class="form-control-label" for="input-description">{{ __('Description') }}</label>
<input type="description" name="description" id="input-description" class="form-control form-control-alternative{{ $errors->has('description') ? ' is-invalid' : '' }}" placeholder="{{ __('Description') }}" value="{{ old('description', $seo->description) }}" required>
#if ($errors->has('email'))
<span class="invalid-feedback" role="alert">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div class="text-center">
<button type="submit" class="btn btn-success mt-4">{{ __('Save') }}</button>
</div>
</div>
</form>
what can i do to resolve my problem? is there any way to do this properly?
There are many ways to do
#if($seo_data != null) //here you can check the data is present or not
<form action="{{ route('seo_data.store')" method="post" >
#csrf
<input type="text" value="{{ isset($seo_data) ? $seo_data->title : '' }}">
<button type="submit" class="btn btn-primary">submit </button>
</form>
#else //if data is present then it goes to here
<form action="{{ route('seo_data.update',encrypt($seo_data->id))" method="post">
#csrf
#method('PATCH')
<input type="text" value="{{ isset($seo_data) ? $seo_data->title : '' }}">
<button type="submit" class="btn btn-primary">Update </button>
</form>
#endif
otherwise if you dont want to hit anther route then check it into store function

Form checkbox input array gets flooded with textarea input

)
I have been struggling with a form for my Laravel App....
I have 3 fields which are checkboxes and therefore is getting POSTed as arrays and then I have a textarea field and somehow SOMETIMES one of the 3 checkbox inputs get flooded with data from the textarea input field... It is very weird and only happens sometime and therefore I get a data to long truncated error in the database...
But I DD the input at the $request level and can see already there the array from the checkbox is flooded with the data from the textarea field... I can not wrap my head around why this is, as it's only sometimes...
And I can even get the error and go back a page in the browser and submit again with all the same data and then it can be working.. WHAT can cause this weird behavioer
This is my Laravel blade where the form is
#extends('layouts.app')
#section('head')
#endsection
#section('content')
#php
// dd($errors);
#endphp
<h2 class="page-title">Opret Artist Side</h2>
<div class="artist-box">
<form class="formgrid" method="POST" action="{{ route('artist.store') }}">
#csrf
<div class="formleft">
<label for="artist_name" class="label">Artist navn</label>
<input type="text" id="artist_name" name="artist_name" class="formitem #error('artist_name') is-invalid #enderror" value="{{ old('artist_name', $post->artist_name ?? null) }}" />
#error('artist_name')
<div class="invalid-feedback">
#foreach($errors->get('artist_name') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="artist_name_help">Jeres band/artist navn. <span class="text-danger">OBS! Kan IKKE ændres</span></small>
#enderror
</div>
<div class="formright">
<label for="contact_person" class="label">Kontakt person</label>
<input type="text" name="contact_person" id="contact_person" class="formitem #error('contact_person') is-invalid #enderror" value="{{ old('contact_person', $post->content ?? null) }}" />
#error('contact_person')
<div class="invalid-feedback">
#foreach($errors->get('contact_person') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="contact_person_help">Kontakt persons navn</small>
#enderror
</div>
<div class="formleft">
<label for="email" class="label">Email</label>
<input type="text" name="email" id="email" class="formitem #error('email') is-invalid #enderror" value="{{ old('email', $post->email ?? null) }}" />
#error('email')
<div class="invalid-feedback">
#foreach($errors->get('email') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="email_help">Kontakt email</small>
#enderror
</div>
<div class="formright">
<label for="phone" class="label">Tlf nummer</label>
<input type="text" name="phone" id="phone" class="formitem #error('phone') is-invalid #enderror" value="{{ old('phone', $post->phone ?? null) }}" />
#error('phone')
<div class="invalid-feedback">
#foreach($errors->get('phone') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="phone_help">Kontakt tlf nummer</small>
#enderror
</div>
<div class="formleft">
<label for="hometown" class="label">Hjemby</label>
<input type="text" name="hometown" id="hometown" class="formitem #error('hometown') is-invalid #enderror" value="{{ old('hometown', $post->hometown ?? null) }}" />
#error('hometown')
<div class="invalid-feedback">
#foreach($errors->get('hometown') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="hometown_help">Jeres Hjemby</small>
#enderror
</div>
<div class="formright">
<label for="category" class="label">Kategori</label>
<select name="category" id="category" class="formitem #error('category') is-invalid #enderror">
{{-- Show a non selectable if with info of none selected --}}
#if(old('category') === null)
<option disabled="disabled" selected value="null">Vælg en kategori</option>
#endif
#foreach($categories as $category)
<option #if(old('category') !== null && old('category') == $category->id) selected #endif value="{{ $category->id }}"
>{{ $category->artist_category }}</option>
#endforeach
</select>
#error('category')
<div class="invalid-feedback">
#foreach($errors->get('category') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="">Hvilken kategori hører i under</small>
#enderror
</div>
<div class="formfull">
<label for="budget" class="label">Budget i spiller for</label>
<ul class="ks-cboxtags">
#foreach($budgets as $budget)
{{-- <div class="form-check form-check-inline"> --}}
<li><input #if(old('budget') !== null && in_array($budget->id,old('budget'))) checked #endif
type="checkbox" name="budget[]" id="budget{{ $budget->id }}" class="form-check-input #error('budget') is-invalid #enderror" value="{{ $budget->id }}" />
<label class="form-check-label" for="budget{{ $budget->id }}">{{ $budget->artist_budget }}</label></li>
{{-- </div> --}}
#endforeach
</ul>
#error('budget')
<div class="invalid-feedback d-block">
#foreach($errors->get('budget') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="budget_help">Vælg hvilket budget i optræder for, gerne flere</small>
#enderror
</div>
{{-- --}}
<div class="formfull">
<label for="genres" class="label">Genre</label>
<ul class="ks-cboxtags">
#foreach($genres as $genre)
{{-- <div class="form-check form-check-inline"> --}}
<li><input #if(old('genres') !== null && in_array($genre->id,old('genres'))) checked #endif
type="checkbox" name="genres[]" id="genres{{ $genre->id }}" value="{{ $genre->id }}" class="form-check-input #error('genres') is-invalid #enderror" />
<label class="form-check-label" for="genres{{ $genre->id }}">{{ $genre->genre }}</label></li>
{{-- </div> --}}
#endforeach
</ul>
#error('genres')
<div class="invalid-feedback d-block">
#foreach($errors->get('genres') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="">Hvike genrer hører i under</small>
#enderror
</div>
{{-- --}}
<div class="formfull">
<label for="area" class="label">Områder hvor i optræder</label>
<ul class="ks-cboxtags">
#foreach($areas as $area)
{{-- <div class="form-check form-check-inline"> --}}
<li><input #if(old('area') !== null && in_array($area->id,old('area'))) checked #endif
type="checkbox" name="area[]" id="area{{ $area->id }}" value="{{ $area->id }}" class="form-check-input #error('area') is-invalid #enderror" />
<label class="form-check-label" for="area{{ $area->id }}">{{ $area->artist_area }}</label></li>
{{-- </div> --}}
#endforeach
</ul>
#error('area')
<div class="invalid-feedback d-block">
#foreach($errors->get('area') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="">Vælg hvilke områder i optræder i</small>
#enderror
</div>
<div class="formleft">
<label for="desc" class="label">Beskriv jer selv</label>
<textarea name="description" id="description" class="formitem #error('description') is-invalid #enderror">{{ old('description', $post->description ?? null) }}</textarea>
{{-- <input id="description" value="{{ old('description', $post->description ?? null) }}" class="form-control #error('description') is-invalid #enderror" name="description" type="hidden">
#trix(\App\ArtistPage::class, 'trixinput',
[
'id' => 'description',
// 'class' => 'form-control',
'hideTools' => ['file-tools'],
'hideButtonIcons' => ['attach', 'link', 'code', 'strike', 'heading-1']
]) --}}
{{-- <input id="desc" value="{{ old('description', $post->description ?? null) }}" type="hidden" name="description">
<trix-editor input="desc" class="#error('description') is-invalid #enderror"></trix-editor> --}}
#error('description')
<div class="invalid-feedback">
#foreach($errors->get('description') as $error)
{{ $error }}
#endforeach
</div>
#else
<small class="text-muted form-text" id="description_help">Giv en god beskrivelse af jer selv og hvad i tilbyder<br>
Tilladte tags er <strong>{{ '<br><b><i><li><ul><ol><hr><strong><p>' }}</strong>
</small>
#enderror
</div>
<button type="submit" class="btn btn-primary">Opret</button>
</form>
</div>
#endsection
See also this image of the DD dump on the $request
Hmmmm Think I figured it out :-)
But it has been such a sporadic bug so I'm not sure yet... But seems like it has gone away :-)
Seems like it was this value line on each field I have gotten messed up
The value line structure on the input fields I had was
value="{{ old('artist_name', $post->artist_name ?? null) }}"
And it should be
value="{{ old('artist_name') ?? $post->artist_name ?? null }}"
Dont know why I ended up with such an obscure Value part on every input field :-)
But sometimes the eyes just gets blind on code :-)

Laravel save related data in database

I want to save question_id in answer table using post form
I tried to use foreach or functions but i always got null data
Controller
public function store(Request $request, Survey $survey)
{
$request->validate([
'answer' => 'required',
]);
$survey->option_name = unserialize($survey->option_name);
$answers = new Answer([
'answer' => $request->get('answer'),
'commentaire' => $request->get('commentaire'),
'user_id' => auth()->id(),
'last_ip' => request()->ip(),
'question_id' => $survey->questions,
'survey_id' => $survey->id,
]);
$answers->save();
return redirect()->action('SurveyController#view_survey_answers', [$survey->id]);
}
answers table
question table's row :
id
survey_id
title
timestamp
I got always null data or i tried using where but i got errors like id index doesn't exists...
View :
{!! Form::open(array('action'=>array('AnswerController#store', $survey->id))) !!}
#forelse ($survey->questions as $key=>$question)
<p class="flow-text">Question {{ $key+1 }} - {{ $question->title }}</p>
#if($question->question_type === 'text')
<div class="form-group">
<div class="input-field col s12">
<input id="answer" type="text" name="answer">
<label for="answer">Answer</label>
</div>
</div>
#elseif($question->question_type === 'textarea')
<div class="form-group">
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea" name="{{ $question->id }}[answer]"></textarea>
<label for="textarea1">Textarea</label>
</div>
</div>
#elseif($question->question_type === 'radio')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
#if($value === 'else')
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{$value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
<div id="textboxes" style="display: none">
<br>
<textarea class="form-control" name="commentaire" id="exampleFormControlTextarea1" rows="3" placeholder="Write a large text here ..."></textarea>
</div>
</div>
#else
<p style="margin:0px; padding:0px;">
<div class="form-group" style="margin-left: 20px;">
<input name="answer" class="custom-control-input" type="radio" id="{{ $value }}" value="{{ $value}}"/>
<label class="custom-control-label" for="{{ $value }}">{{ $value }}</label>
</div>
</p>
#endif
#endforeach
#elseif($question->question_type === 'checkbox')
#foreach($question->option_name as $key=>$value)
<p style="margin:0px; padding:0px;">
<div class="form-group">
<input type="checkbox" id="{{ $value }}" name="answer" value="{{$value}}"/>
<label for="{{$value}}">{{ $value }}</label>
</div>
</p>
#endforeach
#endif
<div class="divider" style="margin:10px 10px;"></div>
#empty
<span class='flow-text center-align'>Nothing to show</span>
#endempty
<div class="form-group">
{{ Form::submit('Submit Survey', array('class'=>'btn btn-success mt-4')) }}
</div>
{!! Form::close() !!}

In Laravel how to show error message beside specific field?

I am new to laravel. I created a simple page where a user can add a product to the database. If the product title or amount is empty; I can also show the errors. But I want to show error right beside the specific field. If the title is empty the error will show beside the title field.
I searched and found solutions using JS and some other. But is there a way to achieve this using only laravel?
my view is like this
<form method="POST" action="create">
#csrf
<input type="text" name="title" placeholder="Product name"><br>
<textarea name="description" placeholder="Description"></textarea><br>
<input type="string" name="amount" placeholder="Price per unit"><br>
<button type="submit">Add Product</button>
</form>
#if(count($errors))
<ul>
#foreach($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
#endif
and my controller is like this
public function store()
{
$this->validate(request(),[
'title'=> 'required',
'amount' => 'required',
]);
$product = new Product;
$product->title = request('title');
$product->seller_id = Auth::guard('seller')->user()->id;
$product->description = request('description');
$product->amount = request('amount');
$product->save();
return redirect('/dashboard');
}
You need to check for errors and display wherever you want like given below
#if ($errors->has('title')) <p style="color:red;">{{ $errors->first('title') }}</p> #endif
and
#if ($errors->has('amount')) <p style="color:red;">{{ $errors->first('amount') }}</p> #endif
In your code for view it can be placed as
<form method="POST" action="create">
#csrf
<input type="text" name="title" placeholder="Product name">
#if ($errors->has('title')) <p style="color:red;">{{ $errors->first('title') }}</p> #endif <br>
<textarea name="description" placeholder="Description"></textarea><br>
<input type="string" name="amount" placeholder="Price per unit">
#if ($errors->has('amount')) <p style="color:red;">{{ $errors->first('amount') }}</p> #endif <br>
<button type="submit">Add Product</button>
</form>
Additionally you can also print custom messages by returning the error text from controller as shown below
$customMessages = [
'title.required' => 'The title field is required to be filled',
'amount.required' => 'The amount field should be completely filled'
];
$this->validate(request,[
'title'=> 'required',
'amount' => 'required',
], $customMessages);
Instead, if you want to show all the errors for a field you can print them as follows
#if ($errors->has('title'))
<p style="color:red;">
#foreach ($errors->get('title') as $errormessage)
{{ $errormessage }}<br>
#endforeach
</p>
#endif
All errors you can get in $errors array
just get them by input field name
Example:
<div class="form-group {{ $errors->has('title') ? 'has-error' : ''}}">
<label for="titile" class="col-sm-3 control-label">Title: </label>
<div class="col-sm-6">
<input class="form-control" placeholder="Product name" required="required" name="title" type="text" id="title">
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
</div>
</div>
Here, $errors->first('title') mean its getting the first index of title errors in $errors array.
in your view you can do this as:
<form method="POST" action="create">
#csrf
<input type="text" name="title" placeholder="Product name"><br>
{!! $errors->first('title', '<p class="help-block">:message</p>') !!}
<br>
<textarea name="description" placeholder="Description"></textarea><br>
{!! $errors->first('description', '<p class="help-block">:message</p>') !!}
<br>
<input type="string" name="amount" placeholder="Price per unit"><br>
{!! $errors->first('amount', '<p class="help-block">:message</p>') !!}
<br>
<button type="submit">Add Product</button>
</form>

Resources