i have some error in my validate data, the errors message not show in my blade file.Maybe you can help me
This is my code
tambah_jamaah.blade.php
{!! Form::open(['route' => 'jamaah.store']) !!}
#if (count($errors) > 0)
<div class="alert alert-danger">
Error :<br />
<ul>
#foreach ($errors->all() as $error)
<li></li>
#endforeach
</ul>
</div>
#endif
<div class="box-body">
<div class="form-group">
{!! Form::label('Name', 'Nama Jamaah') !!}
{!! Form::text('Name', null, ['class' => 'form-control',
'placeholder' => 'Masukan Nama Jamaah ...']) !!}
</div>
<div class="form-group">
{!! Form::label('Number', 'Nomor Telepon') !!}
{!! Form::number('Number', null, ['class' => 'form-control',
'placeholder' => 'Masukan Nomor Telepon ...']) !!}
</div>
<div class="form-group">
{!! Form::label('Birth', 'Tanggal Lahir') !!}
{!! Form::date('Birth', null, ['class' => 'form-control']) !!}
</div>
<div class="form-group">
{!! Form::label('Wa', 'Nomor Whatsapp') !!}
{!! Form::number('Wa', null, ['class' => 'form-control',
'placeholder' => 'Masukan Nomor Whatsapp (Opsional) ...'])
!!}
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-primary">Simpan</button>
</div>
{!! Form::close() !!}
JamaahsController.php (store method)
This is my code in JamaahsController#store
public function store(Request $request)
{
//Validasi data
$this->validate($request, [
'Name' => 'required|max:255',
'Number' => 'required',
'Birth' => 'required'
]);
$pbk = new Pbk;
$pbk->Name = $request->Name;
$pbk->Number = $request->Number;
$pbk->Birth = $request->Birth;
$pbk->save();
return redirect()->route('jamaah.index');
}
Im not sure by adding some group(middleware) in my routes
routes.php
Route::group(['middleware' => ['web']], function() {
Route::resource('jamaah', 'JamaahsController');
Route::get('/', 'PagesController#getIndex');
});
Thanks
I think you need to update your blade file code like :
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Hope this work for you !!!
Official document recommends this code for validation errors. Right now you do not display any errors in your li items.
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
For debugging I also suggest adding this code
public function store(Request $request)
{
//Validasi data
$this->validate($request, [
'Name' => 'required|max:255',
'Number' => 'required',
'Birth' => 'required'
]);
dd($request->all());
If dd outputs anything, then validation does not fail at all.
If validation fails then in your blade try this code. After posting with dd() in controller and then refresh the post without dd() in controller so you will see errors in blade.
{!! Form::open(['route' => 'jamaah.store']) !!}
{{dd($errors)}}
This shows you whats inside the $errors and if there are any errors found.
Related
In my Laravel application, I have the following form to submit data:
{!! Form::open(array('route' => 'testresults.store','method'=>'POST')) !!}
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test ID:</strong>
#foreach ($getTests as $object)
{!! Form::text('test_id', ''.$object->id .'', array('placeholder' => 'Test Name','class' => 'form-control','readonly')) !!}
#endforeach
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<table class="table table-bordered">
<tr>
<th>Test</th>
<th width="280px">Result</th>
</tr>
#foreach ($getTests as $key => $getTest)
#foreach (explode(',', $getTest->samp_list) as $samp_list)
<tr>
<td>
{!! Form::text('test_type[]', ''.$samp_list.'', array('placeholder' => 'Test Type','class' => 'form-control','readonly')) !!}
</td>
<td>{!! Form::text('test_result[]', null, array('placeholder' => 'Test Result','class' => 'form-control')) !!}</td>
</tr>
#endforeach
#endforeach
</table>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Test By:</strong>
{!! Form::text('test_by', ''.Auth::user()->name .'', array('placeholder' => 'Test Name','class' => 'form-control','readonly')) !!}
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</div>
{!! Form::close() !!}
This is my create.blade.php
And my controller looks like this:
public function store(Request $request)
{
try{
request()->validate([
'test_id' => 'required',
'test_type' => 'required',
'test_result' => 'required',
'test_by' => 'required',
]);
TestResult::create($request->all());
return redirect()->route('testresults.index')
->with('success','Test Type created successfully.');
}
catch(Exception $e){
return redirect()->route('testresults.create')
->with('failed','An error has been occured.');
}
}
Now the problem is, whenever I tried to submit the data, it gives me an error saying
ErrorException
Array to string conversion
test_type and test_result fields are repeaters. Due to that, I've used those field names as test_type[] and test_result[].
As you're trying to save an array in your database, you need to define a text or json column in your database and cast the field to one of array, json or collection types.
Define cast in TestResult model:
TestResult
{
protected $casts = [
'test_type' => 'array',
'test_result' => 'array',
];
}
Learn more about casting in laravel models from here
I am trying to insert data into the database neither it shows an error nor saves the data into my database below are the codes. here is the create blade php page .
#extends('layouts.app')
#section('content')
<h1>Create a Camp</h1>
<!-- if there are creation errors, they will show here -->
{{ HTML::ul($errors->all()) }}
{{ Form::open(array('url' => 'camps')) }}
<div class="form-group">
{{ Form::label('name', 'Name') }}
{{ Form::text('name', Request::old('name'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('district', 'District') }}
{{ Form::text('district', Request::old('district'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('address', 'Address') }}
{{ Form::text('address', Request::old('address'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('block', 'Block') }}
{{ Form::text('block', Request::old('block'), array('class' => 'form-control')) }}
</div>
<div class="form-group">
{{ Form::label('population', 'population') }}
{{ Form::text('population', Request::old('population'), array('class' => 'form-control')) }}
</div>
{{ Form::submit('Create the Camp!', array('class' => 'btn btn-primary')) }}
{{ Form::close() }}
#endsection
here is the controller the index controller works fine when I manually enter the data it fetches from the database
here is the store controller and also it not validate the forms data , i am new i dont know how to do it
public function store(Request $request)
{
$rules = array(
'name' => 'required',
'district'=> 'required',
'address' => 'required',
'block' => 'required|numeric',
'Population' => 'required|numeric',
);
$validator = Validator::make(Request::all(), $rules);
if ($validator->fails()) {
return Redirect::to('camp/create')
->withErrors($validator)
->withRequest(Request::except('password'));
} else {
// store
$camp = new Camp;
$camp->name = Request::get('name');
$camp->district = Request::get('district');
$camp->address = Request::get('address');
$camp->block = Request::get('block');
$camp->population = Request::get('population');
$camp->save();
// redirect
Session::flash('message', 'Successfully created Camp!');
return view('camp\camps',['camps'=>$camps]);
}
}
You forgot to add parenthesis after Camp it should be like this:
$camp = new Camp();
$camp->name = $request->name;
$camp->district = $request->district;
$camp->save();
inside EmployeeController in the edit function, i have this code
public function edit($id)
{
$employees = Employee::find($id);
$departmentlists = Department::pluck('id', 'name');
return view('employees.edit', compact('employees', 'departmentlists'));
}
and inside edit.blade.php to display the dropdown i have this code
{!! Form::open(['action' => ['EmployeeController#update', $employees->id], 'method' => 'POST', 'autocomplete' => 'off', 'class' => 'form-horizontal', 'enctype' => 'application/x-www-form-urlencoded']) !!}
<div class="card">
<div class="card-header card-header-primary">
<h4 {{ Form::label('', 'Change Employee Data', ['class' => 'card-title']) }}
</h4>
<p class="card-category"></p>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-12 text-right">
<a href="{{ route('employees.index') }}" class="btn btn-sm btn-primary" style="font-size:12px">
<i class="material-icons">keyboard_backspace</i>
{{ __('kembali') }}
</a>
</div>
</div>
<div class="row">
{{ Form::label('Name', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="form-group col-sm-7">
{{Form::text('name', $employees->name, ['class' => 'form-control', 'placeholder' => 'Name', 'required'])}}
<p style="color: red;">#error('name') {{ $message }} #enderror</p>
</div>
</div>
<div class="row">
{{ Form::label('Department', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="col-md-7">
<div class="form=group">
#foreach($departmentlists as $dl)
<option value="{{ $dl->id }}" #if($dl->id==$employees->department_id) selected='selected' #endif >{{ $employees->name }}</option>
#endforeach
<p style="color: red;">#error('id') {{ $message }} #enderror</p>
</div>
</div>
</div>
<div class="row">
{{ Form::label('Keterangan', '', ['class' => 'col-sm-2 col-form-label']) }}
<div class="form-group col-sm-7">
{{ Form::textarea('information', $employees->information, ['class' => 'form-control', 'placeholder' => 'Keterangan', 'rows' => '6', 'cols' => '50']) }}
</div>
</div>
</div>
<div class="card-footer ml-auto mr-auto">
{{ Form::hidden('_method','PUT') }}
{{ Form::submit('Ubah', ['class' => 'btn btn-primary']) }}
</div>
</div>
{!! Form::close() !!}
This is the employees table
and this is departments table
Now, the goal is i want the dropdown on edit page to display department name of the employee belongs to, while the dropdown still have all of the department name.
so i change can it, but when i run this code it gives me this error.
Trying to get property 'id' of non-object (View:
C:\xampp\htdocs\ims-it-laravel7\resources\views\employees\edit.blade.php)
i have read other threads here but those code still doesn't solve the problem
$departmentlists = Department::pluck('id', 'name');
Later You use
#foreach($departmentlists as $dl) and $dl->id
$dl is NOT an object, it is an array because of the pluck() function.
More precisely it looks like this
[
"abc" => 1
"xyz" => 2
"foo" => 3
]
Note: To see it Yourself try using dd($departmentlists) or dump($departmentlists)
Please see Laravel Eloquent Pluck
In this case You might want to use Department::select(['id', 'name'])->get() as it will return collection of objects with specified properties.
How can I insert Multiple Row of Cart:: content() in Laravel 5.
I'm using Crinsane/LaravelShoppingcart for my cart, however, when you click on proceed to payment, I want the user to fill Customer details like (Terminal ID, sale date, and customer name. But I'm having issue with inserting Cart::(Content) into my database (I dont want to insert instance. I like to break the cart down to my database column. example, if someone pick like 2-5 items, I want it to be inserted to my db, with each item in each row. I've break the Cart::content down in my view, but I need to be able to use Laravel to insert multiple row based on the number of Items selected.
PLEASE NOTE: IF I ONLY ADD ONLY ONE ITEM TO CART, I'M ABLE TO INSERT TO DATABASE, IT'S ONLY WHEN THE ITEM IN CART IS MORE THAN ONE THAT I HAVE ISSUE WITH.
Below is my proceed.blade.php
<div class="panel-heading">Customer Detail</div>
<div class="panel-body">
#if (sizeof(Cart::content()) > 0)
{!! Form::open(['method'=>'POST', 'action'=> 'SalesController#store','files'=>true]) !!}
{!! Form::text('counter', $counter=Cart::content()->groupBy('id')->count(), ['class'=>'form-control'])!!}
#foreach (Cart::content() as $item)
<div class="form-group">
{!! Form::label('product_name', 'Product Name:') !!}
{!! Form::text('product_name', $item->name, ['class'=>'form-control'])!!} </div>
<div class="form-group">
{!! Form::label('quantity', 'Quantity:') !!}
{!! Form::text('quantity', $item->qty, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('unit_price', 'Unit Price:') !!}
{!! Form::text('unit_price', $item->price, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('rowId', 'Row ID:') !!}
{!! Form::text('rowId', $item->rowId, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('tax', 'Tax:') !!}
{!! Form::text('tax', $item->tax, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('total_price', 'Sub Total:') !!}
{!! Form::text('total_price', $item->subtotal, ['class'=>'form-control'])!!}
</div>
#endforeach
#endif
<div class="form-group">
{!! Form::label('terminal_id', 'Terminal ID:') !!}
{!! Form::text('terminal_id', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('customer_name', 'Customer Name:') !!}
{!! Form::text('customer_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('sale_date', 'Sale Date:') !!}
{!! Form::text('sale_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Check Out', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
`
MY CONTROLLER
$counter= $request['counter'];
for ($i = 0; $i < count($counter); $i++) {
Sale::create([
'terminal_id' => $request['terminal_id'],
'customer_name' => $request['customer_name'],
'unit_price' => $request['unit_price'],
'total_price' => $request['total_price'],
'tax' => $request['tax'],
'quantity' => $request['quantity'],
'product_name' => $request['product_name'],
'sale_date' => $request['sale_date'],
'rowId' => $request['rowId']
]);
}
return redirect('shop');
}
First your fields are not arrays so with each #foreach in your view, the old value overrides.
Make your inputs to Array inputs by changing your view this way:
<div class="panel-heading">Customer Detail</div>
<div class="panel-body">
#if (sizeof(Cart::content()) > 0)
{!! Form::open(['method'=>'POST', 'action'=> 'SalesController#store','files'=>true]) !!}
{!! Form::text('counter', $counter=Cart::content()->groupBy('id')->count(), ['class'=>'form-control'])!!}
<?php $idx = 0; ?>
#foreach (Cart::content() as $item)
<div class="form-group">
{!! Form::label("product_name[$idx]", 'Product Name:') !!}
{!! Form::text("product_name[$idx]", $item->name, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("quantity[$idx]", 'Quantity:') !!}
{!! Form::text("quantity[$idx]", $item->qty, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("unit_price[idx]", 'Unit Price:') !!}
{!! Form::text("unit_price[idx]", $item->price, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("rowId[$idx]", 'Row ID:') !!}
{!! Form::text("rowId[$idx]", $item->rowId, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("tax[$idx]", 'Tax:') !!}
{!! Form::text("tax[$idx]", $item->tax, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label("total_price[$idx]", 'Sub Total:') !!}
{!! Form::text("total_price[$idx]", $item->subtotal, ['class'=>'form-control'])!!}
</div>
<?php $idx++; ?>
#endforeach
#endif
<div class="form-group">
{!! Form::label('terminal_id', 'Terminal ID:') !!}
{!! Form::text('terminal_id', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('customer_name', 'Customer Name:') !!}
{!! Form::text('customer_name', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::label('sale_date', 'Sale Date:') !!}
{!! Form::text('sale_date', null, ['class'=>'form-control'])!!}
</div>
<div class="form-group">
{!! Form::submit('Check Out', ['class'=>'btn btn-primary']) !!}
</div>
{!! Form::close() !!}
I suggest you also putting your for loop in a transaction in order to improve it's safety.
Like this:
public function store(SalesCreateRequest $request) {
$counter = Input::get('counter');
\DB::transaction(function() use ($counter){
for ($i=0; $i < $counter; $i++){
Sale::create([
'terminal_id' => Input::get("terminal_id")[$i],
'customer_name'=> Input::get("customer_name")[$i],
'unit_price'=> Input::get("unit_price")[$i],
'total_price'=> Input::get("total_price")[$i],
'tax'=> Input::get("tax")[$i],
'quantity'=> Input::get("quantity")[$i],
'product_name'=> Input::get("product_name")[$i],
'sale_date'=> Input::get("sale_date")[$i],
'rowId'=> Input::get("rowId")[$i]
]);
}
});
return "working";
}
Note that you could simply add a [] suffix instead of [$idx] in your input names to make your inputs arrays, but usually indexing your inputs explicitly is safer.
Edit the $idx key from Cart::content() was returning a weird number, that was why simple numerical numbers threw Out of range exception.
Change your view code as I did above, I hope fixing it this way.
Hope it helps
Just modify your controller
$counter = $request['counter'];
\DB::transaction(function() use ($counter, $request) {
for ($i = 0; $i < count($counter); $i++) {
Sale::create([
'terminal_id' => $request["terminal_id"],
'customer_name' => $request["customer_name"],
'unit_price' => $request["unit_price"][$i],
'total_price' => $request["total_price"][$i],
'tax' => $request["tax"][$i],
'quantity' => $request["quantity"][$i],
'product_name' => $request["product_name"][$i],
'sale_date' => $request["sale_date"],
'rowId' => $request["rowId"][$i]
]);
}
});
NOTE
Not all input fields are array (terminal_id, sale_date...)
I have a simple contact form in Laravel 5. If I submit it with empty fields, the page reloads but it doesn't show me the error messages of the validation. If I fill in the form and submit, I get this error:
InvalidArgumentException in FileViewFinder.php line 140: View [emails.message] not found.
That's because I don't have such view, I'm not sure what to put in it and Laravel's documentation is not clear on the subject:
The first argument passed to the send method is the name of the view that should be used as the e-mail body.
Not sure what that means.
Routes
Route::get('contact','HomeController#contactus');
Route::post('contact_request', 'HomeController#contactRequest');
HomeController
public function contactus()
{
if (Auth::check()) {
$count = Cart::count();
} else {
$count = 0;
}
$contact = Contact::all();
return view('contact')->with('contact', $contact)->with('count', $count);
}
public function contactRequest() {
if (Auth::check()) {
$count = Cart::count();
} else {
$count = 0;
}
$contact = Contact::all();
//Get all the data and store it inside Store Variable
$data = Input::all();
//Validation rules
$rules = array (
'name' => 'required',
'email' => 'required|email',
'message' => 'required|min:5'
);
//Validate data
$validator = Validator::make ($data, $rules);
//If everything is correct than run passes.
if ($validator -> passes()){
Mail::send('emails.message', $data, function($message) use ($data)
{
//$message->from($data['email'] , $data['first_name']); uncomment if using first name and email fields
$message->from('feedback#gmail.com', 'feedback contact form');
//email 'To' field: cahnge this to emails that you want to be notified.
$message->to('feedback#gmail.com', 'John')->cc('feedback#gmail.com')->subject('feedback form submit');
});
// Redirect to page
return view('contact')
->with('message', 'Your message has been sent. Thank You!');
//return View::make('contact');
}else{
//return contact form with errors
return view('contact')
->with('error', 'Feedback must contain more than 5 characters. Try Again.')
->with('contact', $contact)
->with('count', $count);
}
}
View
<h1 class='siteh1'>Contact Us</h1>
<hr class='sitehr'/>
<div class="col-md-6 siteleft">
<h2 class='siteh2'>Contact Info</h2>
<div class='contaddr'><label>Address:</label> {!!$contact[0]['Address']!!}</div>
<div class='contphone'><label>Phone:</label> {!!$contact[0]['Phone1']!!} | {!!$contact[0]['Phone2']!!}</div>
<div class='contemail'><label>E-mail:</label> {!!$contact[0]['Email']!!}</div>
<div class='contfollow'><label>Follow us:</label><p>
<img src="images/fb.png" alt="Facebook">
<img src="images/youtube.png" alt="Youtube">
<img src="images/skype.png" alt="Skype">
<img src="images/gplus.png" alt="Google Plus">
</p></div>
</div>
<div class="col-md-4 col-md-offset-2 col-sm-12 col-xs-12">
<p class='siteright'>
Get in touch with us
</p>
<div class='contform'>
{!! Form::open(['action' => 'HomeController#contactRequest', 'METHOD' => 'PUT']) !!}
<ul class="errors">
#foreach($errors->all('<li>:message</li>') as $message)
#endforeach
</ul>
<div class="form-group">
{!! Form:: text('name', '', array('placeholder' => 'Your Name', 'class' => 'form-control', 'id' => 'contname', 'rows' => '4' )) !!}
</div>
<div class="form-group">
{!! Form:: text('email', '', array('placeholder' => 'Your Email', 'class' => 'form-control', 'id' => 'contemail', 'rows' => '4' )) !!}
</div>
<div class="form-group">
{!! Form:: text('phone', '', array('placeholder' => 'Your Phone', 'class' => 'form-control', 'id' => 'contphone', 'rows' => '4' )) !!}
</div>
<div class="form-group">
{!! Form:: textarea('message', '', array('placeholder' => 'Message', 'class' => 'form-control', 'id' => 'contmessage', 'rows' => '4' )) !!}
</div>
</div>
<div class="modal-footer">
{!! Form::submit('Submit', array('class' => 'btn btn-primary')) !!}
{!! Form:: close() !!}
</div>
</div>
Emails are just blade templates, and the dots note the directory structure. Blade templates are stored in resources/views, so in this case, emails.message will cause Laravel to look in resources/views/emails for the file message.blade.php.
Create the file resources/views/emails/message.blade.php with the content of your message.
All of the data from the form is being passed (via the $data argument), so you should be able to access it in the message view file like this.
Hello {{ $name }}, your phone number is {{ $phone }}
As far as the main view template goes, your error handling code should be:
#foreach($errors->all() as $message)
<li>{{ $message }}</li>
#endforeach`