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
and
In your code for view it can be placed as
Additionally you can also print custom messages by returning the error text from controller as shown below
Instead, if you want to show all the errors for a field you can print them as follows
All errors you can get in
$errors
arrayjust get them by input field name
Example:
Here,
$errors->first('title')
mean its getting the first index of title errors in$errors
array.in your view you can do this as: