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">
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 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">
I am trying to Upload multiple images into a database but only one is uploading instead of multiple.
How to upload multiple images into a database?
Could anyone tell me what is wrong with my code?
[database table ][1]
[1]: https://i.stack.imgur.com/kgv4r.png
controller
public function singalprojectaction(Request $request)
{
$input=$request->all();
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path('projects'), $name);
$images[]=$name;
}
}
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> implode("|",$images),
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
if($query)
{
return response()->json([
'message' => 'Image is Successfully Inserted',
'class_name' => 'alert-success'
]);
}
else{
return response()->json([
'message' => 'Data is not inserted Inserted',
'class_name' => 'alert-warning'
]);
}
}
html view
<form action="Route('singal.action') }}" id="singal_project"
enctype="multipart/form-data">
{{ csrf_field() }}
<div class="alert" id="message" style="display:block;"></div>
<div class="group-form">
<label>Drop Multple Imges</label>
<input required type="file" class="form-control" name="images[]"
multiple>
</div>
</form>
Try This To insert multiple images
public function singalprojectaction(Request $request)
{
$input=$request->all();
$datas = [];
$result = [];
if ($request->hasfile('images')) {
foreach ($request->file('images') as $key => $file) {
$name = $file->getClientOriginalName();
$file->move(public_path() . '/projects/', $name);
$datas[$key] = $name;
}
}
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> implode("|",$datas);
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
if($query){
return response()->json(['message' => 'Image is Successfully Inserted','class_name' => 'alert-success']);
}
else{
return response()->json(['message' => 'Data is not inserted Inserted','class_name' => 'alert-warning'
]);
}
}
You will have to wrapped the insert code in the foreach statement: see below
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move(public_path('projects'), $name);
$query=DB::table('single_portfolio')->insert( [
'Project_name' =>$input['project_name'],
'Client_Name' =>$input['Client_name'],
'Completion_date' =>$input['Completion_date'],
'Duration' =>$input['Duration'],
'project_image_one'=> $name),
'Description' =>$input['Description'],
'project_id' =>$input['select_project'],
]);
}
I'm wondering how to map form field to eloquent model. Thing is that form input field has different name than eloquent model.
This is what i have
Model
class Message extends Model
{
protected $fillable = [
'name', 'email', 'subject_id',
];
}
Form
<form action="{{ action('MessageController#store') }}" method="post">
<input id="name" name="name" type="text">
<input id="email" name="email" type="text">
<select id="subject" name="subject">
#foreach ($subjects as $subject)
<option value="{{ $subject->id }}">{{ $subject->title}}</option>
#endforeach
</select>
</form>
Controller
public function store(Request $request)
{
$message = $this->validate(request(), [
'name' => 'required',
'email' => 'required',
'subject' => 'required',
]);
Message::create($message);
}
Notice that form select field name is subject and Message model field is subject_id.
Is it possible to map these two fields in Message model?
I guess it's possible in controller with something like
Message::create([
'name' => $request->input('name');
'email' => $request->input('email');
'subject_id' => $request->input('subject');
]);
but that's not what i want.
I don't expect some code improvements or suggestions as i'm complete Laravel noob :)
You could add a mutator on the Message model.
public function setSubjectAttribute($value) {
$this->attributes['subject_id'] = $value;
}
That essentially tells eloquent there is a subject attribute on the model but under the hood you're modifying subject_id