how to convert string data(from input form) to integer data(to db)? Laravel 8 - laravel

I am a newbie in laravel. I have a little problem. I am confused how to convert form input data to db. I want when filling out the form input field it's in the form of a STRING, but I want the db to receive data as an integer.
What should I do?
In my blade :
<label class="form-label mb-3"><b>Category</b></label>
<input name="category_id" class="form-control #error('category_id') is-invalid #enderror" list="datalistOptions" id="category_id" placeholder="Ketik untuk mencari jenis kategori pertanyaan">
<datalist id="datalistOptions">
#foreach ($categories as $category)
<option value="{{ $category->id }}" {{ old('category_id') == $category->name ? 'selected' : null }}>{{ $category->name }}</option>
#endforeach
</datalist>
#error('category_id')
<div class="invalid-feedback">{{ $message }}</div>
#enderror
In my controller
$validated = $request->validate([
'title' => 'required|string',
'category_id' => 'required|nullable',
'question_detail' => 'required|string',
]);
Please help

form data is always passed as a string.
You need to convert the variable in the backend.
Description: https://www.tutorialkart.com/php/php-convert-string-to-int/

Have you tried using the validation numeric?
$validated = $request->validate([
'title' => 'required|string',
'category_id' => 'required|nullable',
'question_detail' => 'required|string',
'your_number_field' => 'required|numeric'
]);
https://laravel.com/docs/9.x/validation#rule-numeric
You may need to pair this with a numeric form field, on the input, like so: type="number"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number

Related

Laravel not validate html select box

I have problem with validating html select. I put rules and all other form controls work fine but only select not show validate message.
Model
class Post extends Model
{
protected $table = 'post';
static $rules = [
'title' => 'required',
'slug' => 'required',
'user_id' => 'required|not_in:0',
'meta_title' => 'required',
'meta_description' => 'required',
'post_category_id' => 'required'
];
}
Blade
<div class="form-group">
{{ Form::label('post_category_id', 'Category') }}
<select name="post_category_id" class="form-control">
<option value="0">Select Category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
#endforeach
</select> {!! $errors->first('post_category_id', '<div class="invalid-feedback">:message</div>') !!}
</div>
Controller
public function store(Request $request)
{
request()->validate(Post::$rules);
$post = Post::create($request->all());
Alert::alert('Success', 'Post created successfully.', 'Type');
return redirect()->route('admin.post.index');
}
What i do wrong here?
Even if the option has the value 0 it is still present so, no error will be triggered for "required" rule
Use a disabled option instead
<select name="post_category_id" class="form-control">
<option disabled>Select a Category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
#endforeach
</select>
As far as I see, you have a default value set on your placeholder of the select, so the input will always be valid since its always sent to the backend.
take a look at this line : Select Category
you're setting a default value, remove it and try again:
in your blade do this:
<div class="form-group">
{{ Form::label('post_category_id', 'Category') }}
<select name="post_category_id" class="form-control">
<option>Select Category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}" {{ $category->id == $post->post_category_id ? 'selected' : ''}}>{{ $category->name }}</option>
#endforeach
</select> {!! $errors->first('post_category_id', '<div class="invalid-feedback">:message</div>') !!}
</div>

Laravel Livewire: Validation in array of object

I am new in laravel livewire and having a hard time doing a validation array of object.
In the application, there is an item section and the user can add item/s.
Now all the fields in the item section are required. Once the user submitted form, it did not show the error message in the item section
View
#foreach($items as $i => $item)
<tr>
<td>
<!-- <select class="form-select #error('item_selected_service.{{ $i }}') is-invalid #enderror" type="text" id="service-id" placeholder="Enter member" wire:model.defer="member_id" autofocus> -->
<select class="form-select #error('selected_service_id') is-invalid #enderror" type="text" name="selected_service_id" id="service-id" placeholder="Select Services" wire:model.defer="selected_service_id" autofocus>
<option value="">Please Select</option>
#foreach ($fees as $fee)
<option value="{{ $fee->id }}">{{ $fee->code }} - {{ $fee->name }}</option>
#endforeach
</select>
#error('selected_service_id') <div class="invalid-feedback">{{ $message }}</div> #enderror
</td>
</tr>
#endforeach
Controller
public $members;
public $fees;
public $member_id;
public $date_delivered;
public $terms;
public $date_due;
public $items = [];
public function render()
{
return view('livewire.fees.billings.billing-create');
}
public function mount()
{
$this->members = Member::where('company_id', Auth::user()->company_id)->where('status_id',22)->get();
$this->fees = Fee::where('company_id', Auth::user()->company_id)->where('status_id',20)->get();
$items = new \stdClass();
$items->selected_service_id = '';
$items->quantity = 0;
$items->amount = 0;
array_push($this->items, $items);
}
public function store()
{
$this->validate([
'member_id' => 'required',
'date_delivered' => 'required',
'terms' => 'required|numeric',
'date_due' => 'required',
'items.selected_service_id' => 'required',
]);
}
Question: How to display error message in array of object?
add like this
$this->validate([
'member_id' => 'required',
'date_delivered' => 'required',
'terms' => 'required|numeric',
'date_due' => 'required',
'items.selected_service_id' => 'required',
'member_id.required' => 'Member id is required' //Your Error message
]);

Form didn't insert data to database properly [Laravel][Eloquent]

I have problem with my code somewhere that make my data $request just didn't passed to my database table (?), I'm not sure what the problem is but every time I try to submit it just redirect back to my create blade view.But when I debug it using dd($request->all()); it have everything it need.
My table have 5 columns, id, book_id, member_id, user_id, borrow_date, return_date
My Model
protected $table = "borrow";
protected $guarded = [];
public $timestamps = false;
// Relationship Book
public function book()
{
return $this->belongsTo('App\Book');
}
// Relationship Member
public function member()
{
return $this->belongsTo('App\Member');
}
My Create Controller
public function create()
{
$book= Book::all();
$member= Member::all();
return view('borrow.create', compact('book', 'member'));
}
public function store(Request $request)
{
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'user_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
'status' => 'required'
]);
Borrow::create([
'book_id' => $request->book_id,
'member_id' => $request->member_id,
'user_id' => Auth::user()->id,
'borrow_date' => $request->borrow_date,
'return_date' => $request->return_date,
'status' => 'borrowed',
]); return redirect('/borrow');
}
My Create View
<form action="/borrow" method="POST">
#csrf
<div class="form-group row">
<label class="col-sm-2 col-form-label">Book</label>
<div class="col-sm-10">
<select data-placeholder="Enter Book Data"
data-allow-clear="1" name="book_id" id="book_id">
<option></option>
#foreach($book as $value)
<option value="{{ $value->id }}">ISBN {{ $value->isbn }} -
{{ $value->title }} ({{ $value->year }})
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Member</label>
<div class="col-sm-10">
<select data-placeholder="Enter Member Data"
data-allow-clear="1" name="member_id" id="member_id">
<option></option>
#foreach($member as $value)
<option value="{{ $value->id }}">{{ $value->name }}
#if ($value->gender == 'man')
(M) -
#else
(W) -
#endif
{{ $value->phone }}
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Borrow Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="borrow_date"
id="borrow_date">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Return Date</label>
<div class="col-sm-10">
<input type="date" class="form-control" name="return_date"
id="return_date">
</div>
</div>
<button type="submit" class="btn btn-primary">Add</button>
</form>
dd($request->all());
array:5 [▼
"_token" => "pN3PPQGpT4jmLln59tY3HBiLj27fWgf65ioIYlv0"
"book_id" => "99"
"member_id" => "99"
"borrow_date" => "2021-09-01"
"return_date" => "2021-09-30"
]
Thanks! Sorry if my English and explanation is bad
You are trying to validate a user_id and a status presents in your $request but of course it doesn't.
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'user_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
'status' => 'required'
]);
You are using Auth::user()->id as user_id and it isn't in $request
So, just remove 'user_id' => 'required', from validation. You also don't have status in your $request so you need to remove it too. It should be like this;
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
]);
Use fillable in Peminjaman model
protected $fillable = [
'id', 'book_id', 'member_id', 'user_id', 'borrow_date', 'return_date'
];
try to remove user_id and status from the validation, the request doesn't have these parameters, and you are validating them as required values.
$this->validate($request,[
'book_id' => 'required',
'member_id' => 'required',
'borrow_date' => 'required',
'return_date' => 'required',
]);
When using the create() method, you are using what is called massive assignment. As per docs https://laravel.com/docs/8.x/eloquent#mass-assignment:
...before using the create method, you will need to specify either a
fillable or guarded property on your model class. These properties are
required because all Eloquent models are protected against mass
assignment vulnerabilities by default.
Saying that, you have 2 options:
1 - Keep using create() method but define fillable property in your model
protected $fillable = ['id', 'book_id', 'member_id', 'user_id', 'borrow_date', 'return_date'];
2 - Use the save() method with not need to define fillable property:
$borrow = new Borrow();
$borrow->book_id = $request->book_id;
$borrow->member_id = $request->member_id;
$borrow->user_id = Auth::user()->id;
$borrow->borrow_date = $request->borrow_date;
$borrow->return_date = $request->return_date;
$borrow->status = 'borrowed';
$borrow->save();

How can I pre-fill form data entered by a user in Laravel 7

I'm making a registration form where users will be redirected to a preview page to confirm their details first before submitting the form. I'm using Laravel 7 and I'm quite new to Laravel. Once the user enters their details in registration form, the same details will be pre-filled in the preview form before submission. I have tried some code in my controller but it's giving me an error Trying to get property 'myForm' of non-object In my Controller, $data is an array, I'm not sure how I can achieve this. Please help.
In my Conroller:
public function confirmation(Request $request)
{
$categories = Category::all();
$request->validate([
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'telephone_number' => 'required|digits:10',
'email' => 'required|string|email|max:255|unique:users','regex:/^[\w\-\.\+]+\#[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,6}$/',
'password' => 'required|string|min:6|confirmed',
'password_confirmation' => 'required',
'region' => 'required|string',
'description' => 'required|string|max:2500',
'start_date' => 'required|date',
'client_region' => 'string|max:500',
'client_category' => 'integer|max:255',
]);
$data['myForm'] = $request->all();
return view('auth.client.preview', compact('categories', 'data'));
}
In my blade view:
<div class="form-group">
<label for="first_name">First Name</label><span class="text-danger">*</span>
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
<div class="invalid-feedback">
{{ $errors->first('first_name') }}
</div>
</div>
My Route:
Route::post('/preview-details', 'Auth\Client\PreviewRegisterDetailsController#confirmation')->name('preview-details');
Dropdown List:
<label for="fundi_type">Fundi Type</label><span class="text-danger">*</span>
<select class="custom-select" id="category_id" name="category_id">
#foreach($categories as $category )
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
Simplify like this below .So no need to create extra array key .
$myForm = $request->all();
return view('auth.client.preview', compact('categories', 'myForm'));
and in view
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Updated
<option value="{{ $category->id }}" {{($myForm['category_id']==$category->id)?'selected':null}}>{{ $category->name }}</option>
Edit your blade file code.
Actually your controller is sending array and you are accessing that array as a collection.
From :
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data->myForm['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
To
<input type="text" class="form-control{{ $errors->has('first_name')?'is-invalid':'' }}"
name="first_name" value="{{$data['myForm']['first_name']}}"
placeholder="Enter First Name" autofocus tabindex="1" required>
Hope this will be useful.

Laravel validation with create form: retrieve old input data for dropdown box

I have a Laravel application which uses a form to create items. The form uses validation as defined in the Laravel documentation under this section.
I have a StoreItem Request file:
public function rules() {
return [
'item_name'=>'required',
'category_id'=> 'required',
'collection_id'=> 'required',
'brewery_id'=> 'required',
];
}
and in the controller I have the following:
public function store(storeItem $request)
{
$validated = $request->validated();
$item = new Item([
'user_id' => Auth::id(),
'item_name' => $request->item_name,
'category_id' => $request->category_id,
'collection_id' => $request->collection_id,
'brewery_id' => $request->brewery_id,
]);
$item->save();
When validation is catching an error, the create form is presented again but I don't see the old input data.
For the input text fields, I have done the following:
<input type="text" class="form-control" name="item_name" value="{{ old('item_name') }}" />
and this shows the old input data, but what to do for the dropdown boxes like category_id, collection_id and brewery_id. I want them to have the old value as the 'selected' value.
Currently in the form I have (for the dropdown boxes):
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}">{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
This source seems to indicate that using the old() method might even not be needed, but if I don't use the
You need to manually add the selected attribute to the previously selected value. For example:
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ old("brewery_id") == $brewery->id ? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>
try this as well. I've added bracket open and close to (old('brewery_id')==$brewery->id)
<div class="form-group">
<label class="form-label" for="brewery">Brewery: (*)</label>
<select class="form-control" name="brewery_id" >
#foreach($breweries as $brewery)
<option value="{{ $brewery->id }}" {{ (old('brewery_id') == $brewery->id)? "selected" : "" }}>{{ $brewery->brewery_name }}</option>
#endforeach
</select>
</div>

Resources