Laravel 6 Validation Bug? - laravel

I have a problem about my Laravel project.
$request->validate(
[
'blogs_file' => 'required|image|mimes:jpeg,jpg,png|max:2048',
'blogs_title' => 'required|unique:App\Blogs,blogs_title',
'blogs_content' => 'required',
]);
I made a limit to blogs_file. It should only allowed jpg,png,jpeg and max 2 MB.
But when i try to put a mp4 file, it pass. What is the problem there?
I have already added enctype="multipart/form-data" to my form on blade page.
If i want to put an mp4 file or zip lower than 2 MB the validation works fine. But if i upload any kind of data upper than 2 MB; it passes. Actually, when i check to my db; blogs_file coming NULL on that way, but it returns with success message to user.
UPDATE:
my create.blade.php file;
<div class="box-body">
<form action="{{route('blogs.store')}}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label>Resim Seç</label>
<div class="row">
<div class="col-xs-12">
<input class="form-control" required name="blogs_file" type="file">
</div>
</div>
</div>
<div class="form-group">
<label>Başlık</label>
<div class="row">
<div class="col-xs-12">
<input class="form-control" required type="text" placeholder="Blog Başlığı..." name="blogs_title">
</div>
</div>
</div>
<div class="form-group">
<label>Sayfa Linki</label>
<div class="row">
<div class="col-xs-12">
<input class="form-control" placeholder="Sayfa linki girebilirsiniz(isteğe bağlı)"
name="blogs_slug" type="text">
</div>
</div>
</div>
<div class="form-group">
<label>İçerik</label>
<div class="row">
<div class="col-xs-12">
<textarea class="form-control" id="editor1" name="blogs_content"
required></textarea>
</div>
<script>
CKEDITOR.replace( 'editor1' );
</script>
</div>
</div>
<div class="form-group">
<label>Durum</label>
<div class="row">
<div class="col-xs-12">
<select name="blogs_status" class="form-control">
<option value="1">Aktif</option>
<option value="0">Pasif</option>
</select>
</div>
</div>
</div>
<div align="right" class="box-footer">
<button type="submit" class="btn btn-primary">Ekle</button>
</div>
</form>
</div>
route:
Route::resource('blogs','BlogController');
BlogController:
public function store(Request $request)
{
if (strlen($request->blogs_slug)>3)
{
$slug=Str::slug($request->blogs_slug);
} else {
$slug=Str::slug($request->blogs_title);
}
if ($request->hasFile('blogs_file'))
{
$request->validate(
[
'blogs_file' => 'required|file|mimes:jpeg,jpg,png|max:2048',
'blogs_title' => 'required|unique:App\Blogs,blogs_title',
'blogs_content' => 'required',
]);
$file_name=uniqid().".".$request->blogs_file->getClientOriginalExtension();
$request->blogs_file->move(public_path('images/blogs'),$file_name);
$request->blogs_file=$file_name;
}
$blog= new Blogs;
$blog->blogs_file=$request->blogs_file;
$blog->blogs_title=$request->blogs_title;
$blog->blogs_slug=$slug;
$blog->blogs_content=$request->blogs_content;
$blog->blogs_status=$request->blogs_status;
$blog->uniqid=uniqid();
$blog->save();
if ($blog)
{
return redirect(route('blogs.index'))->with('success','İşlem Başarılı!');
} else {
return back()->with('error','İşlem Başarısız!');
}
}

1st. You have missed file rule.
2nd. You may use either image rule (that validates a file to be jpeg, png, bmp, gif, svg, or webp) or use mimes:jpeg,jpg,png:
So your validation would be either:
'blogs_file' => 'required|file|mimes:jpeg,jpg,png|max:2048',
Or:
'blogs_file' => 'required|file|image|max:2048',
3rd. You've put your validation $request->validate inside an if, it's wrong and makes the problem! You may conditionally adding rules or use after validation hook for more complex validations instead.

Related

laravel livewire error Undefined variable $_instance

I have a form with which I add posts. I want to integrate CKEDITOR, to manipulate the content in textarea. to initialize the editor, I use the following code :
<script src="ckeditor/ckeditor.js">
ClassicEditor
.create(document.querySelector('#post_content'))
.then(editor=>{
editor.model.document.on('change:data',(e)=>{
#this('post_content').set('post_content', e.editor.getData());
});
})
.catch(error=>{
console.error(error);
});
</script>
When I submit form, I get the following error :
> Undefined variable $_instance
here's my form, I mention that without CKEDITOR, it works
<form wire:submit.prevent="addNewPost()" method="post" id="createPostForm" enctype="multipart/form-data">
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-9">
<div class="mb-3">
<label for="" class="form-label">
Titlu
</label>
<input type="text" wire:model="post_title" name="post_title" class="form-control" placeholder="Titlul articolului" value="{{old('post_title')}}">
<span class=" text-danger ">#error('post_title') {{$message}}#enderror</span>
</div>
<div wire:ignore class="mb-3">
<label for="" class="form-label">
Continutul articolului
</label>
<textarea wire:model="post_content"class="ckeditor form-control" id="post_content" name="post_content" cols="30" rows="10" >{{$post_content}}</textarea>
<span class="text-danger">#error('post_content'){{$message}}#enderror</span>
</div>
</div>
<div class="col-md-3">
<div class="mb-3">
<div class="form-label">
Categoria articolului
</div>
<select wire:model="post_category" name="post_category" id="" class="form-select">
<option value="">--Nu ati ales nimic--</option>
#foreach (\App\Models\SubCategory::all() as $category)
<option value="{{$category->id}}">{{$category->subcategory_name}}</option>
#endforeach
</select>
<span class="text-danger">#error('post_category'){{$message}}#enderror</span>
</div>
<div class="mb-3">
<div class="form-label">
Imaginea articolului
</div>
<input type="file" wire:model="post_image" name="post_image" class="form-control">
<span class="text-danger ">#error('post_image'){{$message}}#enderror</span>
</div>
<div class="image-holder mb-2" style="max-width: 250px;">
<img src="" alt="" class="img-thumbnail" id="image-previewer" data-ijabo-default-img=''>
</div>
<button type="submit" id="sub" class="btn btn-primary">Salveaza</button>
</div>
</div>
</div>
</div>
</form>
And this is my component Posts.php
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use Livewire\Component;
Use Livewire\WithFileUploads;
use App\Traits\ShowToastrTrait;
class Posts extends Component
{
use withFileUploads;
use showToastrTrait;
public $post_title, $post_content, $post_category, $post_image;
protected $rules = [
'post_title' => 'required|unique:posts,post_title|max:255',
'post_content' => 'required',
'post_image' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
'post_category' => 'required'];
protected $messages = [
'post_title.required' => 'Introduceti titlul articolului',
'post_title.unique' => 'Exista deja un asemenea titlu',
'post_content.required' => 'Introduceti continutul articolului',
'post_image.required' => 'Atasati o imagine articolului',
'post_image.mimes' => 'Imaginea trebuie sa fie in format jpeg/png/jpg/gif/svg',
'post_category.required' => 'Selectati categoria articolului',
];
public function addNewPost(){
dd($this);
$this->validate();
$post = Post::addNewPost($this);
if(!$post){
$this->showToastr('Articolul nu a putut fi adaugat','error');
}
$this->showToastr('Articolul a fost adaugat cu succes','success');
$this->reset();
}
public function render()
{
return view('livewire.posts');
}
}
I assume you have the script and the component view in separate files and that's why you get an error on #this('post_content').set('post_content', e.editor.getData()); line.
According to the docs, both should be placed in the same file (component file), then #this will be available in the script (you can read more about that here)
Example: let's assume you have a form component that will look like this:
<form>
<!-- your form elements -->
</form>
#push('scripts')
<script>
// accessing #this here should work
</script>
#endpush
Hope it helps :)

Laravel form submit unsuccessful returns blank page instead of redirect home

I have a laravel form to create a new product entry in a database on submit, am supposed to be redirected back but I get a completely blank page without any errors. There is no new entry in my database when I check. The form is made up of various text fields, an image URL, and a multi-selected Image URL
please this is my blade template
<form method="POST" action="{{ route('products.store') }}" enctype="multipart/form-data">
<h4 class="card-title">Create Product</h4><br><br>
#csrf
<div class="row">
<div class="col">
<div class="row mbr-1">
<label for="example-text-input" class="col-sm-2 col-form-label">Name</label>
<div class="col-sm-6">
<input name="name" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input"
class="col-sm-2 col-form-label">Category</label>
<div class="col-sm-6">
<input name="name" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Price</label>
<div class="col-sm-6">
<input name="catchy_title" class="form-control" type="number"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Status</label>
<div class="col-sm-6">
<input name="status" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Product
Description</label>
<div class="col-sm-8">
<textarea id="elm1" name="long_description" placeholder="Please enter a vivid description of the product"></textarea>
</div>
</div>
<!-- end row -->
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Tags</label>
<div class="col-sm-6">
<input name="tags" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Estimated
Delivery
Time</label>
<div class="col-sm-6">
<input name="estimated_delivery_time" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Available
Quantity</label>
<div class="col-sm-6">
<input name="available_quantity" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Colors</label>
<div class="col-sm-6">
<input name="colors" class="form-control" type="text" value=""
id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Supplier's
Name</label>
<div class="col-sm-6">
<input name="supplier_name" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Supplier's
Contact</label>
<div class="col-sm-6">
<input name="supplier_contact" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Video Url /
Link</label>
<div class="col-sm-6">
<input name="video_description" class="form-control" type="text"
value="" id="example-text-input">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Primarry
Image</label>
<div class="col-sm-6">
<input name="primary_image" accept="image/*" class="form-control"
type="file" id="image">
</div>
</div>
<!-- end row -->
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label"> Primary Image
Preview</label>
<div class="col-sm-6">
<img id="showImage" class="" width="300px"
src="{{ !empty($Product->image) ? url('upload/products/' . $product->image) : url('upload/no_image.jpg') }}"
alt="Hero image">
</div>
</div>
<!-- end row -->
</div>
<div class="col">
<div class="row mb-3">
<label for="example-text-input" class="col-sm-2 col-form-label">Add Other
Images</label>
<div class="col-sm-6">
<input name="multi_image[]" accept="image/*" class="form-control"
type="file" id="image" multiple="">
</div>
</div>
<!-- end row -->
</div>
</div>
<input type="submit" class="btn btn-info waves-effect waves-light"
value="Create Product">
</form>
and this is my store function
public function store(Request $request)
{
if ($request->file('image')) {
$image = $request->file('image');
$name_gen = hexdec(uniqid()).'.'.$image->getClientOriginalExtension(); // 3434343443.jpg
Image::make($image)->resize(523,605)->save('upload/home_about/'.$name_gen);
$save_url = 'upload/products/'.$name_gen;
$this->validate($request, [
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'tags' => $request -> tags,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'other_images' => $save_url,
]);
$notification = array(
'message' => 'Product created successfully',
'alert-type' => 'success'
);
return redirect()->back()->with($notification);
}
Please what am I doing wrong?
thank you for taking some time to review
you are validating the request but not saving it to database.
after the validation and before the return you should do like this to save in database.
$item=new YOUR_MODEL_NAME:
$item->name => $request->name,
$item->category => $request->category,
$item->price => $request->price,
$item->description => $request->description,
$item->status => $request -> status,
$item->tags => $request -> tags,
$item->estimated_delivery_time => $request->estimated_delivery_time,
$item->available_quantity => $request->available_quantity,
$item->colors => $request->colors,
$item->supplier_name => $request->supplier_name,
$item->supplier_phone => $request->supplier_phone,
$item->video_description => $request->video_description,
$item->primary_image => $save_url,
$item->other_images => $save_url,
$item->save();
$this->validate($request, [
'name' => $request->name,
'category' => $request->category,
'price' => $request->price,
'description' => $request->description,
'status' => $request -> status,
'tags' => $request -> tags,
'estimated_delivery_time' => $request->estimated_delivery_time,
'available_quantity' => $request->available_quantity,
'colors' => $request->colors,
'supplier_name' => $request->supplier_name,
'supplier_phone' => $request->supplier_phone,
'video_description' => $request->video_description,
'primary_image' => $save_url,
'other_images' => $save_url,
]);
In the snippet above you're performing the validation, but I don't see a request to persist the data to your database in your store() function.
It's recommended to utilize the functionality provided by the framework when checking for request input presence. These functions usually provide quality-of-life aspects such as checking for multiple input presence and conditional callbacks as well.
https://laravel.com/docs/9.x/requests#determining-if-input-is-present
if ($request->has('name')) {
//
}
You should also be calling the validate() method on $request, not $this.
First, I'd like to recommend that you utilize a Form Request
https://laravel.com/docs/9.x/validation#form-request-validation
Second, use the validated data and mass assignment when storing the new model. If the validated data structure is not 1:1 with the table schema, you could always assign the values manually but this will result in a bloated controller. One possible solution is to utilize a DTO (Data Transfer Object) and provide the validated() array to the DTO when using mass assignment.
// Without DTO
Model::create($modelStoreRequest->validated());
// With DTO
$DTO = new MyDTO($modelStore$request->validated())->toArray();
Model::create($DTO);
Note that if the incoming request fields do not pass the given validation rules Laravel will automatically redirect the user back to their previous location. In addition, all of the validation errors and request input will automatically be flashed to the session.
Try to be specific, pass route where you want to redirect like below:
return redirect()->route('route-name-here')->with($notification);

Posting data over post route - Page expired

I'm attempting to post data to my database using Laravel, but I can't seem to do so. The post route sends to a an expired page.
Here is the route
Route::post('/expenses', 'PropertyExpenseController#store')->middleware('auth');
This is the create and store functions which render the form, and process the form.
public function create($id){
$property = PropertyAdvert::where('id', $id)->first();
return view('/pages/expenses/create', compact('property'));
}
public function store(Request $request){
$PropertyExpenses = PropertyExpenses::create([
"property_id" => $request->property_id,
"user_id" => Auth::user()->id,
"expenseDescription" => $request->description,
"cost" => $request->amount,
"date" => $request->date,
"category" => $request->category
]);
return "Expense Log";
}
This is the view page, where the form is loaded. All the data is got in the controller via the names on the input elements.
<form method="POST" action="/expenses">
<span name="property_id" class="text-muted">{{$property->id}}</span>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label class="" for"description">Expense Description<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4">
<input class="form-control " type="text" name="description">
</div>
</div>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label for"amount">Amount<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4 input-group">
<span class="input-group-addon mr-1 mt-1">€</span>
<input class="form-control" type="text" name="amount">
</div>
</div>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label for"category">Category<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4">
<select class="form-control" id="category" name="category">
<option>Mortgage Payment</option>
<option>Maintainence</option>
<option>Management Fee</option>
</select>
</div>
</div>
<div class="row mt-4 justify-content-center">
<div class="col-md-6">
<label for"description">Date<label>
</div>
</div>
<div class="row form-group justify-content-center">
<div class="col-md-4">
<input class="form-control" type="date" name="date">
</div>
</div>
<input type="submit" class="btn btn-primary" value="Log Expense">
</form>
THis is the model, with the fillable array.
class PropertyExpense extends Model
{
protected $fillable = ['property_id'. 'user_id', 'expenseDescription', 'cost', 'date', 'category'];
public function property(){
return $this->belongsTo('App\PropertyAdverts');
}
}
In your form, you need a CSRF Token field.
<input type="hidden" name="_token" value="{{ csrf_token() }}">
Read more here.

How to get Ckeditor textarea value in laravel

i am using Ckeditor for blog posting in my project when i submit the form nothing i am get in controller can any one suggest me solution for that.
my view is looking like
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Post</div>
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ route('store-post') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="category_id" class="col-md-2 control-label">Select Categories</label>
<div class="col-md-8">
<select class="form-control" id="category_id" name="category_id">
#foreach($categories as $category)
<option value="{{$category->url_name}}">
{{$category->category_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Post Title</label>
<div class="col-md-8">
<input id="post_title" type="text" class="form-control" name="post_title" value="{{ old('post_title') }}">
</div>
</div>
<div class="form-group">
<label for="post_content" class="col-md-2 control-label">Post Description</label>
<div class="col-md-8">
<textarea id="post_content" rows="10" cols="60" class="span8" placeholder="Image Title Goes Here" name="post_content"></textarea>
</div>
</div>
<div class="form-group">
<label for="p_url" class="col-md-2 control-label">Post Url</label>
<div class="col-md-8">
<input id="p_url" type="text" class="form-control" name="p_url" value="{{ old('p_url') }}">
</div>
</div>
<div class="form-group">
<label for="p_title" class="col-md-2 control-label">Meta Title</label>
<div class="col-md-8">
<input id="p_title" type="text" class="form-control" name="p_title" value="{{ old('p_title') }}">
</div>
</div>
<div class="form-group">
<label for="p_keyword" class="col-md-2 control-label">Meta Keyword</label>
<div class="col-md-8">
<input id="p_keyword" type="text" class="form-control" name="p_keyword" value="{{ old('p_keyword') }}">
</div>
</div>
<div class="form-group">
<label for="email" class="col-md-2 control-label">Meta Description</label>
<div class="col-md-8">
<textarea class="form-control" id="p_mdesc" name="p_mdesc" rows="3">
</textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-8 col-md-offset-2">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
<!--Error start-->
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!--error ends-->
</form>
</div>
</div>
</div>
</div>
</div>
my controller code is
public function store(Request $request){
/*$this->validate($request, [
'category_id' => 'required',
'post_title' => 'required',
//'post_content' => 'required',
'p_url' => 'required',
'p_title' => 'required',
'p_keyword' => 'required',
'p_mdesc' => 'required',
]);*/
$post=new Post;
echo $post_content=$request->input('post_content');
}
in previous project ie designed in CI i just use
$tc=$this->input->post('tc'); in controller for getting the Ckeditor value but in laravel i am not sure how to get it done.
Your view contain 2 name attribute for the post_content field (textarea). Please check.
You can do it like this -
{!! Form::textarea('tc', $tc,array('required', 'class'=>'form-control', placeholder'=>'Your message')) !!}
and then you will have to initialise it
$(document).ready(function () {
CKEDITOR.replace( 'tc' );
});
The documentation has clear examples.
In your Blade you should add ckeditor like this:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>A Simple Page with CKEditor</title>
<!-- Make sure the path to CKEditor is correct. -->
<script src="../ckeditor.js"></script>
</head>
<body>
<form>
<textarea name="editor1" id="editor1" rows="10" cols="80">
This is my textarea to be replaced with CKEditor.
</textarea>
<script>
// Replace the <textarea id="editor1"> with a CKEditor
// instance, using default configuration.
CKEDITOR.replace( 'editor1' );
</script>
</form>
</body>
</html>
So the javascript code triggers a replace of a textarea to the editor
Now for the retrieving data part
<script>
var data = CKEDITOR.instances.editor1.getData();
// Your code to save "data", usually through Ajax.
</script>
You need to create an endpoint if you want to send this data indeed trough Ajax. Don't forget to add a CSRF token
As mentioned by #user3888958,
<textarea name="tc" id="post_content" rows="10" cols="60"
class="span8" placeholder="Image Title Goes Here" name="post_content">
the textarea has two name attribute.
You could access the textarea content using the name attribute, remove any one name attribute and pass that in as a parameter to the request
$request->input('tc'); // OR
$request->input('post_content');
and to access the value of
<textarea class="form-control" id="p_mdesc" name="p_mdesc" rows="3">
</textarea>
you could access it using the name
$request->input('p_mdesc');

Multiple forms with same inputs name check which form input has error Laravel

I have something like this in my code:
#foreach($cars as $key => $car)
{!!Form::open(['action' => 'CarController#Update'])!!}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Color</label>
<div class="col-lg-6">
{!!Form::text('carColor', $car->color, ['class' => 'form-control input-sm'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Price</label>
<div class="col-lg-6">
{!!Form::text('carPrice', $car->price, ['class' => 'form-control input-sm'])!!}
</div>
</div>
</div>
{!!Form::close()}
#endforeach
The objective of this view is to update a car's price and color. But there are a lot so there's one form per car. In case the inputs don't pass the validation, how can I know which form inputs are the invalid since the inputs are named the same.
The problem is that the laravel has a session of old inputs but not for forms.
But this task is easy with javascript or jquery.
#foreach($cars as $key => $car)
{!!Form::open(['action' => 'CarController#Update'])!!}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Color</label>
<div class="col-lg-6">
{!!Form::text('carColor', $car->color, ['class' => 'form-control input-sm', 'id' => 'carColor'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<label class="col-lg-6 control-label">Price</label>
<div class="col-lg-6">
{!!Form::text('carPrice', $car->price, ['class' => 'form-control input-sm', 'id'=> 'carPrice'])!!}
</div>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="form-group">
<input type="hidden" id="carID" value="{{ $car->id }}">
<button class="btn btn-warning" id="editDetails">edit</button>
</div>
</div>
{!!Form::close()}
#endforeach
and in your javascript
$('#editDetails').on('click', function () {
carColor = $(this).parent().parent().parent().find('#carColor').val();
carPrice = $(this).parent().parent().parent().find('#carPrice').val();
car_id = $(this).parent().parent().parent().find('#carID').val();
_token= $('meta[name="csrf-token"]').attr('content'); //add meta header in top head section see below
//here you can also check validation like check for empty fields
$.ajax({
url : 'url/to/edit/route',
method : 'patch', //this could be post. whatever you defined as your route
data : {
carColor : carColor,
carPrice : carPrice,
carId : carId,
_token : _token
},
success : function() {
alert('successful edit!');
//you can do something like
$(this).parent().parent().append('<p>success</p>');
//to show which line was successful
},
error : function(xhr,status,err) {
//you can do something like append an alert div to the parent form element of the erroneous input row.
$(this).parent().parent().append('<p>error editing here</p>');
}
});
});
add this meta tag with a csrf session as content in the head tag of your master layout
<meta name="csrf-token" content="{!! csrf_token() !!}">
Hope this would give you an idea on how you solve your problem.
EDIT
due to OP needing to handle this with no javascript
First add a hidden input of the key in foreach loop form to pass which row throws the error
<input type="hidden" id="key" value="{{ $key }}">
then in your controller you can add this to the error handling block
Session::flash('error', Input::get('key')); //use flash which behaves the same as as old input session
//a one time use session
and on inside the loop add an if statement checking for errors
#if(Session::has('error') || Session::get('error') == $key)
<div class="alert-box success">
<h2>error here</h2>
</div>
#endif
Hope this helps

Resources