I am trying to add a row to my database for the objects type "Event". Whenever I press the create button on my HTML form, I get the error "Undefined index: location".
This is my save function:
public function save(CreateEvent $request)
{
$validated = $request->validated();
$event = new Event();
$event->event_name = $validated['name'];
$event->event_description = $validated['description'];
$event->event_location_id = $validated['location'];
if ($validated['website'] != null) {
$event->event_website = $validated['website'];
}
if ($validated['facebook'] != null) {
$event->event_facebook = $validated['facebook'];
}
if ($validated['twitter'] != null) {
$event->event_twitter = $validated['twitter'];
}
if ($validated['instagram'] != null) {
$event->event_instagram = $validated['instagram'];
}
$starttime = strtotime($validated['starttime']);
$event->event_start_time = date('H:i', $starttime);
$event->event_duration = $validated['duration'];
$event->event_day = $validated['day'];
if ($validated['image'] != null) {
$imageName = time().'.'.request()->file('image')->getClientOriginalExtension();
$event->event_image = $imageName;
request()->image->move(public_path('images'), $imageName);
}
$event->save();
return redirect()->route('event.show', ['event_id' => $event->event_id]);
}
This is my Form Request:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class CreateEvent extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'name' => 'required',
'description' => 'required',
'location' => 'required',
'starttime' => 'required',
'duration' => 'required',
'day' => 'required',
'website' => '',
'twitter' => '',
'facebook' => '',
'instagram' => '',
'image' => '',
];
}
public function messages() {
return ["Invalid input"];
}
}
Here is the relevant part of the HTML:
<div class="input-wrapper">
<label for="location">Location *</label>
<select id="location">
#foreach ($event_locations as $location)
<option value="{{$location->location_id}}">{{$location->location_name}}</option>
#endforeach
</select>
</div>
When I press create, I get the following error:
ErrorException
Undefined index: location
This is the line the error is on: $event->event_location_id = $validated['location'];
Help is appreciated
your select tag is is missing name attribute and the value is not passing with the form. so location index is missing in $request. just add the name attribute in the select tag.
<select id="location" name="location">
#foreach ($event_locations as $location)
<option value="{{$location->location_id}}">{{$location->location_name}}
</option>
#endforeach
</select>
Your select element does not have a name.
<select id="location">
must be
<select name="location" id="location">
Related
i want to insert an array but it tells me Cannot access offset of type string on string
and i made foreach and when i do $return->request
it looks like
{
_token: "qb7dTYdsDVtw1RJnQQARzJMEqIfHPeQbHobiC8u2",
_method: "POST",
name: "Wanda Rojas",
phone: [
"+1 (841) 393-5088",
"+1 (769) 441-1936"
],
address: "Et est cum delectus"
}
and here is my model for clients
and i make phone field as array in protected $casts
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
protected $fillable = [
'name',
'address',
];
protected $casts = [
'phone' => 'array'
];
}
here is my form
<form action="{{route('clients.store')}}" method="POST">
#csrf
#method('POST')
<input type="text" placeholder="add name" name="name"><br>
#for ($i = 0; $i < 2; $i++) <div class="form-group">
<label>#lang('site.phone')</label>
<input type="text" name="phone[]" class="form-control">
</div>
#endfor
<input type="text" placeholder="add address" name="address"><br>
<button type="submit" class="btn btn-primary">add</button>
</form>
and here is my controller at store method
public function store(Request $request)
{
//return $request;
$this->validate($request,[
'name' => 'required',
'phone' => 'required|array|min:1',
'phone.*' => 'required',
'address' => 'required'
]);
$phone = $request->phone;
foreach ($phone as $p){
$add = new Client();
$add->name = $request->name;
$add->phone = $p['phone'];
$add->address = $request->address;
$add->save();
};
return redirect()->route('clients.index');
}
Your code when you store client should looks like this
public function store(Request $request)
{
//return $request;
$this->validate($request,[
'name' => 'required',
'phone' => 'required|array|min:1',
'phone.*' => 'required',
'address' => 'required'
]);
$phone = $request->phone;
$add = new Client();
$add->name = $request->name;
$add->phone = $phone; // $phone it's already an array, so you should only set it to property
$add->address = $request->address;
$add->save();
return redirect()->route('clients.index');
}
and in clients.index.blade.php to access phone
#foreach($client->phone as $phone)
...
{{ $phone }}
...
#endforeach
You are iterating through the array of phone numbers so $p is the phone number. $add->phone = $p should resolve your issue.
I have a little problem with the data validation with livewire ( laravel ).
I noticed that when I set up the validation in real time ( validateOnly() ), the information entered in the form is validated in real time. At this level everything is fine.
But when I click on the button to submit the form (even though the form contains errors), the form is unfortunately sent to my function defined in the wire:submit.
So my question is : is it possible to revalidate the information in the wire:submit method that receives the data after the form is submitted ? If so, how can I do that?
PS: I tried to set the validate method in my wire:submit function but nothing happens. It blocks the form from being submitted but it doesn't give me an error .
My source code :
<?php
class UserProfile extends Component
{
use WithFileUploads;
public $countries = [];
public $profile = [];
protected function rules() {
if ( !LivewireUpdateProfileRequest::authorize() ) {
return abort(403, "Your are not authorized to make this request !");
}
$rules = LivewireUpdateProfileRequest::rules();
if ( !empty($this->profile['phone']) ) {
$rules['profile.phone'] = [ 'required', 'phone_number:' . $this->profile['phone'] ];
}
return $rules;
}
public function mount()
{
$this->countries = Countries::all();
$this->profile = Auth::user()->toArray();
}
public function updateUserProfile()
{
$validatedData = $this->validate();
dd( $validatedData );
}
public function updated($key, $value)
{
$this->validateOnly($key);
}
public function render()
{
return view('livewire.user-profile');
}
}
Html source :
<form action="" method="POST" wire:submit.prevent="updateUserProfile">
<input name="profile.email" type="email" wire:model="profile.email" />
#error('profile.email') {{ $message }} #enderror
<input name="profile.phone" type="tel" wire:model="profile.phone" />
#error('profile.phone') {{ $message }} #enderror
</form>
Here is LivewireUpdateProfileRequest content :
<?php
namespace App\Http\Requests\Web;
use Illuminate\Foundation\Http\FormRequest;
class LivewireUpdateProfileRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public static function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public static function rules()
{
return [
'profile' => ['required', 'array', 'size:10'],
'profile.firstname' => ['required', 'string'],
'profile.lastname' => ['required', 'string'],
'profile.email' => ['required', 'email'],
'profile.phone' => ['required', 'phone_number:33'],
'profile.gender' => ['required', 'gender'],
'profile.image' => ['sometimes', 'image', 'mimes:png,jpg,jpeg'],
'profile.address' => ['required', 'string'],
'profile.city' => ['required', 'string'],
'profile.country_id' => ['required', 'exists:countries,id'],
'profile.birth_at' => ['required', 'date', 'min_age:18'],
];
}
}
Usually in your saving method you would run validation once more for all fields. The livewire docs share this example:
Livewire Component:
class ContactForm extends Component
{
public $name;
public $email;
protected $rules = [
'name' => 'required|min:6',
'email' => 'required|email',
];
public function updated($propertyName)
{
$this->validateOnly($propertyName);
}
public function saveContact()
{
$validatedData = $this->validate();
Contact::create($validatedData);
}
}
With this HTML:
<form wire:submit.prevent="saveContact">
<input type="text" wire:model="name">
#error('name') <span class="error">{{ $message }}</span> #enderror
<input type="text" wire:model="email">
#error('email') <span class="error">{{ $message }}</span> #enderror
<button type="submit">Save Contact</button>
</form>
This should validate the inputs near-realtime using the updated-method and on submit using the saveContact-method.
If you could share your code, we could debug it easier.
Source: https://laravel-livewire.com/docs/2.x/input-validation#real-time-validation
I would like to create a multi step form with validations, but the values are not stored in the inputs through the sessions.
In the controller I have:
use Illuminate\Support\Facades\Session;
My code at the moment is this:
public function addItemStep1(Request $request)
{
$product = $request->session()->get('product');
return view('admin.items.add', compact('product'))->with([
'page_name' => __('Add Item')
]);
}
public function storeNewItemStep1(Request $request)
{
$validatedData = $request->validate([
'title' => 'required',
'body' => 'required'
]);
if(empty($request->session()->get('product')))
{
$product = new Items();
$product->fill($validatedData);
$request->session()->put('product', $product);
} else {
$product = $request->session()->get('product');
$product->fill($validatedData);
$request->session()->put('product', $product);
}
return redirect('/');
}
The validations work, everything is ok, but unfortunately after sending the form the data just entered does not appear.
<input type="text" class="form-control #error('title') is-invalid #enderror" value="{{ Session::get('title') }}" name="title">
i create image module and i edit image more then 1mb then can not show errormsg.
i used codigniter fremwork.
controller:
public function edit($id) {
$this->edit_status_check($id);
$this->form_validation->set_rules('agent_name', 'Agent Name', 'required');
$this->form_validation->set_rules('mobile', 'Mobile No.', 'required');
$this->form_validation->set_rules('agent_vehicle', 'Agent Vehicle', 'required');
if ($this->form_validation->run() == FALSE) {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => validation_errors(),
'id' => $id
);
$this->load->view('template', $data);
} else {
$config['upload_path'] = '../uploads/agent/';
$config['allowed_types'] = 'jpg|jpeg';
$config['encrypt_name'] = TRUE;
$config['max_size'] = 1000; // 1 mb
$this->load->library('upload', $config);
if (!empty($_FILES['agent_image']['name'])) {
if ($this->upload->do_upload('agent_image')) {
$_POST['agent_img_url'] = 'uploads/agent/' . $this->upload->data('file_name');
} else {
$data = array(
'page_title' => 'Edit Agent',
'page_name' => 'agent/edit',
'result' => $this->agent_model->select_id($id),
'result_vehicle' => $this->vehicle_model->list_all(),
'error' => $this->upload->display_errors(),
'id' => $id
);
$this->load->view('template', $data);
}
}
$this->agent_model->update($_POST, $id);
alert('Update', $_POST['agent_name']);
redirect('agent');
}
}
Model:
public function update($data, $id) {
$updatedata = array(
'name' => $data['agent_name'],
'mobile' => $data['mobile'],
'password' => sha1($data['password']),
'vehicle' => $data['agent_vehicle'],
'address' => $data['agent_address'],
'category' => $data['category'],
'created_on' => date('Y-m-d h:i:sa')
);
if (!empty($data['agent_img_url'])) {
$updatedata['img_url'] = $data['agent_img_url'];
}
$this->db->where('id', $id);
$this->db->update('agent', $updatedata);
}
View:
<div class="form-group">
<img src="/<?= $result['img_url']; ?>" class="img-responsive" name="old_agent_image" width="133" height="100">
</div>
<div class="form-group">
<label>Agent Image</label>
<input type="file" name="agent_image">
</div>
MY question: I edit image for particular user then image uploaded,but if image size more then 1mb ,then image can not upload and display error message.
so my question how to show errormsg.
$uploaded = $this->upload->do_upload('file'); //'file' is input field name
if($uploaded) {
$upload_data = $this->upload->data();
// do database stuff
} else {
$data['errors'] = array("error" => $this->upload->display_errors());
}
When I submit my form my controller[] array post does not work throws errors.
Error 1
A PHP Error was encountered Severity: Notice Message: Array to string
conversion Filename: mysqli/mysqli_driver.php Line Number: 544
Error Number: 1054 Unknown column 'Array' in 'field list' INSERT INTO
user_group (name, controller, access, modify) VALUES
('Admin', Array, '1', '1') Filename:
C:\Xampp\htdocs\riwakawebsitedesigns\system\database\DB_driver.php
Line Number: 331
It is not inserting the controller names. Not sure best way to fix?
Model
<?php
class Model_user_group extends CI_Model {
public function addUserGroup($data) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $this->input->post('controller'),
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
?>
Controller
<?php
class Users_group extends Admin_Controller {
public function index() {
$data['title'] = "Users Group";
$this->load->model('admin/user/model_user_group');
$user_group_info = $this->model_user_group->getUserGroup($this->uri->segment(4));
if ($this->input->post('name') !== FALSE) {
$data['name'] = $this->input->post('name');
} else {
$data['name'] = $user_group_info['name'];
}
$ignore = array(
'admin',
'login',
'dashboard',
'filemanager',
'login',
'menu',
'register',
'online',
'customer_total',
'user_total',
'chart',
'activity',
'logout',
'footer',
'header',
'permission'
);
$data['controllers'] = array();
$files = glob(FCPATH . 'application/modules/admin/controllers/*/*.php');
foreach ($files as $file) {
$controller = basename(strtolower($file), '.php');
if (!in_array($controller, $ignore)) {
$data['controllers'][] = $controller;
}
}
if ($this->input->post('name') !== FALSE) {
$data['controller'] = $this->input->post('controller');
} else {
$data['controller'] = $user_group_info['controller'];
}
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'User Group Name', 'required');
if ($this->form_validation->run($this) == FALSE) {
$this->load->view('template/user/users_group_form.tpl', $data);
} else {
$this->load->model('admin/user/model_user_group');
$this->model_user_group->addUserGroup($this->input->post());
redirect('admin/users_group');
}
}
}
?>
View
<?php echo validation_errors('<div class="alert alert-warning text-center"><i class="fa fa-exclamation-triangle"></i>
', '</div>'); ?>
<?php if ($this->uri->segment(4) == FALSE) { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/add', $data);?>
<?php } else { ?>
<?php $data = array('class' => 'form-horizontal', 'id' => 'form-users-group');?>
<?php echo form_open('admin/users_group/edit' .'/'. $this->uri->segment(4), $data);?>
<?php } ?>
<div class="form-group">
<?php $data = array('class' => 'col-sm-2 control-label');?>
<?php echo form_label('User Group Name', 'name', $data);?>
<div class="col-sm-10">
<?php $data1 = array('id' => 'name', 'name' => 'name', 'class' => 'form-control', 'value' => $name);?>
<?php echo form_input($data1);?>
</div>
</div>
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>Controller Name</td>
<td>Access</td>
<td>Modify</td>
</tr>
</thead>
<?php foreach ($controllers as $controller) {?>
<tbody>
<tr>
<td><?php echo $controller;?>
<input type="hidden" name="controller[]" value="<?php echo $controller;?>" />
</td>
<td>
<select name="access" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
<td>
<select name="modify" class="form-control">
<option>1</option>
<option>0</option>
</select>
</td>
</tr>
</tbody>
<?php } ?>
</table>
<?php echo form_close();?>
The error is because you cannot insert php-array in database.
Instead store comma separated values.
In your model change data array as below:
public function addUserGroup($data) {
$controllers = $this->input->post('controller');
$name = $this->input->post('name');
$access = $this->input->post('access');
$modify = $this->input->post('modify');
for($i=0;$i<count($controllers);$i++) {
$data = array(
'name' => $name,
'controller' => $controllers[$i],
'access' => $access,
'modify' => $modify
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}
}
Your controller hidden field is an array. You're passing this array to your addUserGroup function, which is trying to insert this array into the database. It's implicitly trying to convert this array to a string. Maybe try changing your function to this:
'controller' => $this->input->post('controller')[0],
Problem fixed foreach in model Thanks for the ideas on how to fix problems every one.
foreach ($this->input->post('controller') as $controller) {
$data = array(
'name' => $this->input->post('name'),
'controller' => $controller,
'access' => $this->input->post('access'),
'modify' => $this->input->post('modify')
);
$this->db->set($data);
$this->db->insert_id();
$this->db->insert($this->db->dbprefix . 'user_group');
}