I have a view made with livewire and it contains two dynamically add sections for spoken languages and the other one for courses and certificates. The language section was working fine until I added the add certificates section. now when the user clicks on the add section for the certificate section to add a new one, one of the added language sections disappears and then will appear again once you add another one. I guess it will appear again once the view re-renders. I have been going back and force moving functions around from render method to update/updated/hydrate/dehydrate but got no luck. at first, I thought it had something to do with the $loop->index that I use in my view but after changing that I realized it was not it. I'm hitting a dead-end here and can't figure out what's going on here.
I also made a screen record of what is happening so it might help:
https://drive.google.com/file/d/1Hq2wTKcPvhs05SKFMICaRoOAzpSyj9Iz/view?usp=sharing
View section:
<!-- language section -->
<div class="card card-profile shadow-sm mt-4">
<div class="px-4 mt-4 mb-4">
<div class="h5 font-weight-bold mb-4">Spoken languages</div>
<div class="heading text-muted mb-4">you only can add 3 languages to your profile.</div>
#foreach ($languages as $lindex => $language)
<div class="card card-body mb-4" wire:key="{{ $lindex }}">
<div class="text-left"><span class="fa fa-trash text-gray language-delete" wire:click="removeLanguage({{ $lindex }}, {{ !empty($language['id']) ? $language['id'] : 0 }})"></span></div>
<div class="row">
<div class="form-group col-md-6">
<label class="" for="languageName">language</label>
<select class="form-control form-control-alternative" name="language-name" {{-- id="languageName" --}} wire:model="languages.{{ $lindex }}.language_name">
<option value="" class="form-control" selected disabled>select language</option>
#foreach ($language_names as $name)
<option value="{{ $name->abbreviation }}" class="form-control">{{ $name->language }}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-6">
<label class="" for="languageProficiency">proficiency level</label>
<select class="form-control form-control-alternative" name="language-proficiency" {{-- id="languageProficiency" --}} wire:model="languages.{{ $lindex }}.language_level">
<option value="" class="form-control" selected disabled>proficiency level</option>
#foreach ($language_levels as $level)
<option value="{{ $level->level }}" class="form-control">{{ $level->name }}</option>
#endforeach
</select>
</div>
</div>
</div>
#endforeach
#error('languages.*.language_level')
<small class="text-warning">{{ $message }}</small>
#enderror
#error('languages.*.language_language')
<small class="text-warning">{{ $message }}</small>
#enderror
#if (count($languages) < 3)
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-outline-secondary btn-round btn-block" wire:click="addLanguage"><span class="btn-inner--icon"><i class="fa fa-plus fa-2x"></i></span></button>
</div>
</div>
#endif
</div>
</div>
<!-- end language section -->
<!-- other certificates section -->
<div class="card card-profile shadow-sm mt-4">
<div class="px-4 mt-4 mb-4">
<div class="h5 font-weight-bold mb-4">Other related certificates</div>
<div class="heading text-muted mb-4">if you have other related certificates in your files you can add then here.</div>
#foreach ($certificates as $cindex => $certificate)
<div class="card card-body mb-4" wire:key="{{ $cindex }}">
<div class="row">
<div class="form-group col-md-6">
<label class="" for="other-certificates-name">certificate name</label>
<input type="text" class="form-control form-control-alternative" placeholder="" name="ptherCertificatesName">
</div>
<div class="form-group col-md-6">
<label class="" for="other-certificates-school-name">School name</label>
<input type="text" class="form-control form-control-alternative" placeholder="" name="otherCertificatesSchoolName">
</div>
<div class="form-group col-md-6">
<label class="" for="other-certificates-verification-link">URL<small>(optional)</small></label>
<input type="text" class="form-control form-control-alternative text-left" placeholder="" name="otherCertificatesVerificationLink">
</div>
<div class="form-group col" dir="ltr">
<label class="" for="other-certificates-grad-date" dir="rtl">finished date</label>
<div class="input-group input-group-alternative">
<div class="input-group-prepend">
<span class="input-group-text"><i class="ni ni-calendar-grid-58"></i></span>
</div>
<input type="text" class="form-control form-control-alternative datePicker" placeholder="" name="otherCertificatesGradDate" value="">
</div>
</div>
</div>
</div>
#endforeach
#if (count($certificates) < 5)
<div class="row">
<div class="col-md-12">
<button type="button" class="btn btn-outline-secondary btn-round btn-block" wire:click="addCertificate"><span class="btn-inner--icon"><i class="fa fa-plus fa-2x"></i></span></button>
</div>
</div>
#endif
</div>
</div>
<!-- end other certificates section -->
Livewire component controller:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\CityName;
use App\Models\Language;
use App\Models\LanguageLevel;
use App\Models\User;
use App\Models\UserLanguage;
use App\Models\UserProfile;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Auth;
class UserInfo extends Component
{
public $name;
public $email;
public $phone;
public $states = [];
public $selectedstate;
public $cities = [];
public $selectedcity;
public $jobTitle;
public $aboutMe;
public $employer;
public $position;
public $edu_course;
public $edu_school;
public $edu_level;
public $edu_start_date;
public $edu_end_date;
public $employment_looking;
public $employment_hired;
public $twitter;
public $linkedin;
public $github;
public $instagram;
public $website;
public $languages = [];
public $language_names;
public $language_levels;
public $languageToDelete = [];
public $certificates = [];
public $certificate_name;
public $certificate_school;
public $certificate_link;
public $certificate_date;
public $certificateToDelete = [];
public $skillsQuery;
public $skillResults;
public $skills;
public function render()
{
$this->retriveStates();
$this->retriveCities();
$this->retriveLanguages();
return view('livewire.user-info');
}
public function retriveStates()
{
$this->states = CityName::distinct()->get(['state']);
}
public function retriveCities()
{
$this->cities = CityName::where('state', $this->selectedstate)->get(['city']);
}
public function updatedSkillsQuery()
{
$this->skillResults = $this->skills->where('name', 'like', $this->skillsQuery) ?? collect();
}
public function retriveLanguages()
{
$this->language_names = Language::all();
$this->language_levels = LanguageLevel::all();
}
public function addLanguage()
{
if (count($this->languages) <= 3)
{
array_push($this->languages, ['language_name'=>'', 'language_level'=>'', 'id'=>'']);
}
else
{
$this->sweetAlert('error', 'you only can add 3 languages to your profile.');
}
}
public function getUserLanguages()
{
$this->languages = auth()->user()->userLanguages->toArray();
}
public function removeLanguage($languagePosition, $languageId)
{
if (isset($languageId))
{
if ($languageId == 0)
{
array_splice($this->languages, $languagePosition, 1);
}
else
{
array_push($this->languageToDelete, $languageId);
array_splice($this->languages, $languagePosition, 1);
}
}
}
public function addCertificate()
{
if (count($this->certificates) <= 5)
{
array_push($this->certificates, ['name'=>'', 'school'=>'', 'link'=>'', 'date'=>'', 'id'=>'']);
/* dd($this->languages); */
}
else
{
$this->sweetAlert('error', 'you only can add 5 certificates to your profile.');
}
}
public function mount()
{
$this->skills = collect([
['name' => 'vue'],
['name' => 'vue'],
['name' => 'vue'],
['name' => 'laravel'],
['name' => 'laravel'],
['name' => 'laravel'],
]);
$this->skillResults= [];
$this->skillsQuery = '';
/* $this->retriveLanguages();
$this->retriveStates();
$this->retriveCities(); */
$this->getUserLanguages();
$this->name = auth()->user()->name;
$this->email = auth()->user()->email;
$this->phone = auth()->user()->phone;
$this->selectedstate = auth()->user()->userprofile->state;
$this->selectedcity = auth()->user()->userprofile->city;
$this->jobTitle = auth()->user()->userprofile->job_title;
$this->aboutMe = auth()->user()->userprofile->about_me;
$this->employer = auth()->user()->userprofile->employer;
$this->position = auth()->user()->userprofile->position;
$this->edu_course = auth()->user()->userprofile->edu_course;
$this->edu_school = auth()->user()->userprofile->edu_school;
$this->edu_level = auth()->user()->userprofile->edu_level;
$this->edu_start_date = auth()->user()->userprofile->edu_start_date;
$this->edu_end_date = auth()->user()->userprofile->edu_end_date;
$this->employment_looking = auth()->user()->userprofile->employment_looking;
$this->employment_hired = auth()->user()->userprofile->employment_hired;
$this->twitter = auth()->user()->userprofile->twitter;
$this->linkedin = auth()->user()->userprofile->linkedin;
$this->github = auth()->user()->userprofile->github;
$this->instagram = auth()->user()->userprofile->instagram;
$this->website = auth()->user()->userprofile->website;
}
public function rules()
{
return [
'name' => ['required', 'string', 'max:250'],
'email' => [
'required',
'email',
'max:250',
Rule::unique('users')->ignore(auth()->id()),
],
'phone' => ['required', 'digits:11'],
'selectedstate' => 'required',
'selectedcity' => 'required',
'jobTitle' => ['required', 'string', 'max:250'],
'aboutMe' => ['required', 'string', 'max:250'],
'employer' => ['string', 'max:250'],
'position' => ['string', 'max:250'],
'edu_course' => ['nullable', 'string', 'max:250'],
'edu_school' => ['nullable', 'string', 'max:250'],
'edu_level' => ['nullable', 'string', 'max:250'],
'edu_start_date' => ['nullable', 'string'],
'edu_end_date' => ['nullable', 'string'],
'employment_looking' => ['nullable', 'boolean'],
'employment_hired' => ['nullable', 'boolean'],
'twitter' => ['nullable', 'string', 'max:250'],
'linkedin' => ['nullable', 'string', 'max:250'],
'github' => ['nullable', 'string', 'max:250'],
'instagram' => ['nullable', 'string', 'max:250'],
'website' => ['nullable', 'string', 'max:250'],
'languages.*.language_name' => ['required', 'exists:App\Models\Language,abbreviation'],
'languages.*.language_level' => ['required', 'exists:App\Models\LanguageLevel,level'],
];
}
public function submit()
{
$user = Auth::user();
$this->validate();
User::where('id', auth()->id())->update([
'name' => $this->name,
'email' => $this->email,
'phone' => $this->phone,
]);
UserProfile::where('user_id', auth()->id())->update([
'state' => $this->selectedstate,
'city' => $this->selectedcity,
'job_title' => $this->jobTitle,
'about_me' => $this->aboutMe,
'employer' => $this->employer,
'position' => $this->position,
'edu_course' => $this->edu_course,
'edu_school' => $this->edu_school,
'edu_level' => $this->edu_level,
'edu_start_date' => $this->edu_start_date,
'edu_end_date' => $this->edu_end_date,
'employment_looking' => $this->employment_looking,
'employment_hired' => $this->employment_hired,
'twitter' => $this->twitter,
'linkedin' => $this->linkedin,
'github' => $this->github,
'instagram' => $this->instagram,
'website' => $this->website,
]);
if (!empty($this->languageToDelete))
{
/* $user = Auth::user(); */
foreach ($this->languageToDelete as $delete)
{
$user->userLanguages()->where('id', $delete)->delete();
}
}
foreach ($this->languages as $language)
{
/* $user = Auth::user(); */
$user->userLanguages()->updateOrCreate([
'language_name' => $language['language_name'],
],
[
'language_name' => $language['language_name'],
'language_level' => $language['language_level']
]
);
}
$this->getUserLanguages();
$this->sweetAlert('success', 'changes saved!');
}
public function sweetAlert($type, $message)
{
$this->alert($type, $message, [
'position' => 'bottom-end',
'timer' => 5000,
'toast' => true,
'text' => null,
'showCancelButton' => false,
'showConfirmButton' => false
]);
}
}
The issue has been solved. the problem indeed was a DOM issue caused by multiple loop index. as what I thought at first the $loop->index was causing it and I was on the right track to change it to something else like $languages as $lindex => $language but apparently even by doing that those two sections will still have the same wire:key because of the loop iterations which returns 0,1,2 and so on in order. so by appending a string to the key like lang{{ $loop->index }} they will be unique and therefore problem solved.
Related
I have to develop a reservation system for a hotel.
You first have to create a user and than you can make a reservation.
There is an option to edit the registered users but that is the part where I'm stuck.
I follow a very good tutorial but at the moment I can't figure out my error from his video or the internet or documentation..
I've used the post method to insert new data inside my database but to edit the data and update it, I have to use the put method. But it gives an error "Too few arguments in my function .. 1 passed in and 2 expected".
I am aware I have to cache the routes at every change!!
This is my controller:
public function store(Request $request)
{
$guest = Guest::create
([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
return redirect('./clients.html');
}
public function edit($id)
{
$guest = Guest::find($id);
return view('edit')->with('guest', $guest);
}
public function update(Request $request, $id)
{
$guest = Guest::where('id', $id)
->update([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
}
These are my routes:
Route::get('/', [PagesController::class, 'home']);
Route::get('/home.html', [PagesController::class, 'home']);
Route::get('/clients.html', [GuestsController::class, 'saveGuests']);
Route::post('/clients.html', [GuestsController::class, 'store']);
Route::put('/clients.html', [GuestsController::class, 'update']);
Route::get('/reservations.html', [PagesController::class, 'reservations']);
Route::get('/clients_new.html', [GuestsController::class, 'newclients']);
Route::get('/clients/{id}/edit.html', [GuestsController::class, 'edit']);
Route::get('/reservations_new.html', [PagesController::class, 'newReservations']);
And the file I have make the changes is (using the post method at first but inserted a put method):
<form action="/clients.html" method="POST" class="w-3/12 m-auto flex flex-col justify-evenly items-center text-xl">
#csrf
#method('PUT')
<div class="medium-6 columns py-4 text-3xl w-full flex flex-row items-center justify-between">
<label class="font-semibold">Titel</label>
<select name="title" class="w-22 border-solid border-2 border-grey-200 rounded-lg bg-gray-100 p-2" value="{{ $guest->titel }}">
<option value="Mr." selected="selected">Mr.</option>
<option value="Ms.">Mw.</option>
<option value="Mrs.">Juf.</option>
<option value="Dr.">Dr.</option>
</select>
</div>
<div class="medium-6 columns m-auto py-4 text-3xl w-full flex flex-row items-center justify-between">
<label class="font-semibold">Voornaam</label>
<input name="fname" type="text" class="border-solid border-2 border-grey-200 rounded-lg bg-gray-100 p-2 " value="{{ $guest->voornaam }}">
</div>
<div class="medium-6 columns m-auto py-4 text-3xl w-full flex flex-row items-center justify-between">
<label class="font-semibold">Achternaam</label>
<input name="sname" type="text" class="border-solid border-2 border-grey-200 rounded-lg bg-gray-100 p-2" value="{{ $guest->achternaam }}">
</div>
Route::put('/clients/{id}', [GuestsController::class, 'update']);
Route::get('/clients/{id}/edit', [GuestsController::class, 'edit']);
Controller functions:
public function edit($id)
{
$guest = Guest::find($id);
return view('edit',['guest'=> $guest]);
}
public function update(Request $request, $id)
{
$guest = Guest::where('id', $id)
->update([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
}
in the form:
<form action="{{url("clients",$guest->id)}}" method="POST" class="w-3/12 m-auto flex flex-col justify-evenly items-center text-xl">
also i would encourage you to check the documentation for Laravel Validation and Routing
Use this code for routes :
Route::put('/clients/{id}', [GuestsController::class, 'update']);
Route::get('/clients/{id}/edit', [GuestsController::class, 'edit']);
Use this code for Controller:
public function edit($id)
{
$guest = Guest::query()->find($id);
return view('edit',['guest'=> $guest]);
}
public function update(Request $request, $id)
{
$guest = Guest::query()->where('id', $id)->first();
if (!$guest){
Redirect()->back()->withErrors(['msg' => 'guest not found']);
}
$guest->update([
'titel' => $request->input('title'),
'voornaam' => $request->input('fname'),
'achternaam' => $request->input('sname'),
'adres' => $request->input('address'),
'postcode' => $request->input('zipcode'),
'stad' => $request->input('city'),
'provincie' => $request->input('provincie'),
'email' => $request->input('email')
]);
return redirect()
->action([GuestsController::class, 'edit'])
->with('success', 'Product updated successfully');
}
in form :
<form action="{{url("clients",$guest->id)}}" method="POST" class="w-3/12 m-auto flex flex-col justify-evenly items-center text-xl">
Use this code to display errors when updating:
#if($errors->any())
<h4>{{$errors->first()}}</h4>
#endif
I hope it will be useful
I am making a blogging application with Laravel 8 and Bootstrap 5.
I run into a problem with adding an article into the articles table.
In the migration file that generated the articles table, I have:
public function up() {
Schema::create('articles', function (Blueprint $table) {
$table->id();
$table->unsignedInteger('user_id');
$table->foreign('user_id')->references('id')->on('users');
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('catergories');
$table->string('title');
$table->string('slug');
$table->string('short_description');
$table->longText('content');
$table->tinyInteger('featured')->default('0');
$table->string('image')->nullable();
$table->timestamps();
});
}
In the Article model, I have:
class Article extends Model {
use HasFactory;
protected $fillable = [
'user_id',
'category_id',
'title',
'slug',
'short_description',
'content',
'featured',
'image',
];
// Join users to articles
public function user() {
return $this->belongsTo(User::class);
}
// Join categories to articles
public function category() {
return $this->belongsTo(ArticleCategory::class);
}
}
In the controller, I have:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller {
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:255',
'short_description' => 'required|string|max:255',
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'content' => 'required|string',
'featured' => 'required'
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function index() {
$articles = Article::paginate(10);
return view('dashboard/articles',
['articles' => $articles]
);
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Upload article image
$current_user = Auth::user();
if (isset($request->image)) {
$imageName = md5(time()) . $current_user->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
}
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'image' => $fields['image'],
'featured' => $fields['featured']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
The form:
<form method="POST" action="{{ route('dashboard.articles.add') }}" enctype="multipart/form-data" novalidate>
#csrf
<div class="row mb-2">
<label for="title" class="col-md-12">{{ __('Title') }}</label>
<div class="col-md-12 #error('title') has-error #enderror">
<input id="title" type="text" placeholder="Title" class="form-control #error('title') is-invalid #enderror" name="title" value="{{ old('title') }}" autocomplete="title" autofocus>
#error('title')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="short_description" class="col-md-12">{{ __('Short description') }}</label>
<div class="col-md-12 #error('short_description') has-error #enderror">
<input id="short_description" type="text" placeholder="Short description" class="form-control #error('short_description') is-invalid #enderror" name="short_description" value="{{ old('short_description') }}" autocomplete="short_description" autofocus>
#error('short_description')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="category" class="col-md-12">{{ __('Category') }}</label>
<div class="col-md-12 #error('category_id') has-error #enderror">
<select name="category_id" id="category" class="form-control #error('category_id') is-invalid #enderror">
<option value="0">Pick a category</option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
#error('category_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<div class="col-md-12 d-flex align-items-center switch-toggle">
<p class="mb-0 me-3">Featured article?</p>
<input class="mt-1" type="checkbox" name="featured" id="featured">
<label class="px-1" for="featured">{{ __('Toggle') }}</label>
</div>
</div>
<div class="row mb-2">
<label for="image" class="col-md-12">{{ __('Article image') }}</label>
<div class="col-md-12 #error('image') has-error #enderror">
<input type="file" name="image" id="file" class="file-upload-btn">
#error('image')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-2">
<label for="content" class="col-md-12">{{ __('Content') }}</label>
<div class="col-md-12 #error('content') has-error #enderror">
<textarea name="content" id="content" class="form-control #error('content') is-invalid #enderror" placeholder="Content" cols="30" rows="6">{{ old('content') }}</textarea>
#error('content')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
</div>
<div class="row mb-0">
<div class="col-md-12">
<button type="submit" class="w-100 btn btn-primary">
{{ __('Save') }}
</button>
</div>
</div>
</form>
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
});
The problem:
Even though the form passes validation, and a redirect occurs, the record is not actually added to the articles table.
Laravel throws the error General error: 1366 Incorrect integer value: 'on' for column 'featured' at row 1.
What is my mistake?
When dealing with checkboxes you need to know that;
a) you cannot use required since the checkbox is not sent with the form data if it is unchecked.
b) the default value is 'on' but actually, the presence of the field in the data means it was checked so what I normally do is like;
'featured' => $request->has('featured')
this will return a boolean true or false, suitable for storing in your db
So you could write
// Turn the 'featured' field value into a tiny integer
//$fields['featured'] = $request->get('featured') == 'on' ? 1 : 0;
// If no image is uploaded, use default.jpg
$fields['image'] = $request->get('image') == '' ? 'default.jpg' : $imageName;
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'featured' => $request->has('featured'),
'image' => $fields['image']
];
Your column is defined as a tinyInteger that can only accept a single digit, but you seem to be passing a string on to it.
$table->tinyInteger('featured')->default('0');
General error: 1366 Incorrect integer value: 'on' for column
'featured' at row 1
Try setting the value of your checkbox to 1.
<input class="mt-1" type="checkbox" name="featured" id="featured" value="1">
Edit, make sure to add boolean to your validation rules after adding the value to your input element.
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:255',
'short_description' => 'required|string|max:255',
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'content' => 'required|string',
'featured' => 'required|boolean'
];
In case it helps anyone, here is the working code for creating an article:
The routes:
// Article routes
Route::group(['prefix' => 'articles'], function() {
Route::get('/', [ArticleController::class, 'index'])->name('dashboard.articles');
Route::get('/new', [ArticleController::class, 'create'])->name('dashboard.articles.new');
Route::post('/add', [ArticleController::class, 'save'])->name('dashboard.articles.add');
});
In the controller:
namespace App\Http\Controllers\Dashboard;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\Controller;
use App\Models\ArticleCategory;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
private $rules = [
'category_id' => 'required|exists:article_categories,id',
'title' => 'required|string|max:255',
'short_description' => 'required|string|max:255',
'image' => 'image|mimes:jpeg,png,jpg|max:2048',
'content' => 'required|string'
];
private $messages = [
'category_id.required' => 'Please pick a category for the article',
'title.required' => 'Please provide a title for the article',
'short_description.required' => 'The article needs a short description',
'content.required' => 'Please add content'
];
public function categories() {
return ArticleCategory::all();
}
public function index() {
$articles = Article::orderBy('id', 'desc')->paginate(10);
return view('dashboard/articles',
['articles' => $articles]
);
}
public function create() {
// Load the view and populate the form with categories
return view('dashboard/add-article',
['categories' => $this->categories()]
);
}
public function save(Request $request) {
// Validate form (with custom messages)
$validator = Validator::make($request->all(), $this->rules, $this->messages);
if ($validator->fails()) {
return redirect()->back()->withErrors($validator->errors())->withInput();
}
$fields = $validator->validated();
// Upload article image
$current_user = Auth::user();
if (isset($request->image)) {
$imageName = md5(time()) . $current_user->id . '.' . $request->image->extension();
$request->image->move(public_path('images/articles'), $imageName);
}
// Turn the 'featured' field value into a tiny integer
$fields['featured'] = $request->get('featured') == 'on' ? 1 : 0;
// If no image is uploaded, use default.jpg
$fields['image'] = $request->get('image') == '' ? 'default.jpg' : $imageName;
// Data to be added
$form_data = [
'user_id' => Auth::user()->id,
'category_id' => $fields['category_id'],
'title' => $fields['title'],
'slug' => Str::slug($fields['title'], '-'),
'short_description' => $fields['short_description'],
'content' => $fields['content'],
'featured' => $fields['featured'],
'image' => $fields['image']
];
// Insert data in the 'articles' table
$query = Article::create($form_data);
if ($query) {
return redirect()->route('dashboard.articles')->with('success', 'Article added');
} else {
return redirect()->back()->with('error', 'Adding article failed');
}
}
}
I'm working on a contact form with Codeigniter 4 and SQL Database. The form will submit through the button, so whenever it is clicked, it is validating, and if all of the fields are filled out, it has no trouble displaying the message and save the information to the database, but when the fields are empty, it does not display the error message, and it continues to state that the file does not exist.
Well, I'm stuck with the error message now. I'm not sure what wrong with the code. Am I missing something?
Can anybody help me with this? I appreciate all the help I can get.
Below are my codes:
App/config/Routes.php
$routes->get('contact', 'Contact::contact');
$routes->post('contact/save', 'Contact::save');
App/Controller/Contact.php
<?php
namespace App\Controllers;
use App\Models\ContactModel;
class Contact extends BaseController
{
public function __construct()
{
helper(['url', 'form']);
}
//CONTACT PAGE
public function contact()
{
$data = [
'meta_title' => 'Contact | MFD',
];
return view('page_templates/contact', $data);
}
//SAVE
public function save()
{
$validation = $this->validate([
'name' => [
'rules' => 'required',
'errors' => [
'required' => 'Your full name is required'
]
],
'email' => [
'rules' => 'required|valid_email|is_unique[users.email]',
'errors' => [
'required' => 'Email is required',
'valid_email' => 'You must enter a valid email',
]
],
'title' => [
'rules' => 'required',
'errors' => [
'required' => 'Title is required',
]
],
'content' => [
'rules' => 'required',
'errors' => [
'required' => 'Content is required',
]
],
]);
if (!$validation) {
return view('contact', ['validation' => $this->validator]);
} else {
// Let's Register user into db
$name = $this->request->getPost('name');
$email = $this->request->getPost('email');
$title = $this->request->getPost('title');
$content = $this->request->getPost('content');
$values = [
'name' => $name,
'email' => $email,
'title' => $title,
'content' => $content,
];
$contactModel = new ContactModel();
$query = $contactModel->insert($values);
if ($query) {
return redirect()->to('contact')->with('success', 'Your message are successful sent');
} else {
return redirect()->to('contact')->with('fail', 'Something went wrong');
}
}
}
}
App/Views/page_templates/contact.php
<form action="<?= base_url('contact/save'); ?>" method="post" role="form" class="php-email-form">
<?= csrf_field(); ?>
<?php if (!empty(session()->getFlashdata('error'))) : ?>
<div class="alert alert-danger"><?= session()->getFlashdata('error'); ?></div>
<?php endif ?>
<?php if (!empty(session()->getFlashdata('success'))) : ?>
<div class="alert alert-success"><?= session()->getFlashdata('success'); ?></div>
<?php endif ?>
<div class="row">
<div class="col-md-6 form-group">
<input type="text" name="name" class="form-control" id="name" placeholder="Your Name" value="<?= set_value('name'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'name') : '' ?></span>
</div>
<div class="col-md-6 form-group mt-3 mt-md-0">
<input type="email" class="form-control" name="email" id="email" placeholder="Your Email" value="<?= set_value('email'); ?>">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'email') : '' ?></span>
</div>
</div>
<div class="form-group mt-3">
<input type="text" class="form-control" name="title" id="title" placeholder="Title">
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'title') : '' ?></span>
</div>
<div class="form-group mt-3">
<textarea class="form-control" name="content" rows="5" wrap="hard" placeholder="Message"></textarea>
<span class="text-danger"><?= isset($validation) ? display_error($validation, 'content') : '' ?></span>
</div>
<div style="height: 10px;"></div>
<div class="text-left button">
<button type="submit" name="submit">Send Message</button>
</div>
<div style="height: 10px;"></div>
</form>
Okay, I have fixed the problem with my code. It's really is a small mistake or I could say careless mistake haha feel so dumb right now but all that I need to change and make it work.
Is this part: return view('contact', ['validation' => $this->validator]);
Instead of doing it like that I actually miss placing the file to call the view page properly so the code I only added my the folder name that is
page_templates
and if I include it in the code it should look like this:-
return view('page_template/contact', ['validation' => $this->validator]);
and it works after that haha.
Can anyone help me with this error? I am making an application, I am using the Laravel Framework version 5.8.35.
ERROR :
Argument 1 passed to App\Http\Controllers\Auth\RegisterController::validator() must be an instance of Illuminate\Http\Request
Register Controller :
The idea of control is to control the sending of data between the view and the database. This controller controls the application's remit.
<?php
namespace App\Http\Controllers\Auth;
use App\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\RegistersUsers;
class RegisterController extends Controller
{
use RegistersUsers;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest');
}
protected function validator(Request $request)
{
$this->validate($request, [
'nome' => 'required|max:255',
'sobrenome' => 'required|max:255',
'email' => 'required|email|unique:users,email|max:255',
'cpf' => 'required|min:11|unique:users,cpf',
'rg' => 'required|min:7|unique:users,rg',
'telefone' => 'required',
'celular' => 'required',
'rua' => 'required|max:255',
'bairro' => 'required|max:255',
'complemento' => 'max:255',
'numero' => 'required',
'cep' => 'required|min:8',
'datanascimento' => 'required|date|before:today',
'password' => 'required|min:8|confirmed|max:60',
]);
$user = User::create(request([
'nome',
'sobrenome',
'email',
'cpf',
'rg',
'telefone',
'celular',
'rua',
'bairro',
'complento',
'numero',
'cep',
'datanascimento',
'password'
]));
auth()->login($user);
return redirect()->to('/home');
}
}
View Register:
The idea of the view is to show the user in a friendlier way how to register to use the system.
#section('content')
<link href="{{ asset('css/sb-admin-2.min.css')}}" rel="stylesheet">
<div class="form-horizontal">
{{Form::model(['route' => 'register', 'method' => 'post'])}}
<div class="form-group">
{{Form::label('nome', 'Nome:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('nome',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('nome'))
{{$errors->first('nome')}}
#endif
</div>
<div class="form-group">
{{Form::label('sobrenome', 'Sobrenome:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('sobrenome',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('nome'))
{{$errors->first('nome')}}
#endif
</div>
<div class="form-group">
{{Form::label('datanascimento', 'Data de Nascimento:',['class' => 'col-lg-2 control-label'])}}
{{Form::date('datanascimento',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('datanascimento'))
{{$errors->first('datanascimento')}}
#endif
</div>
<div class="form-group">
{{Form::label('cpf', 'CPF:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('cpf',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('cpf'))
{{$errors->first('cpf')}}
#endif
</div>
<div class="form-group">
{{Form::label('rg', 'RG:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('rg',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('rg'))
{{$errors->first('rg')}}
#endif
</div>
<div class="form-group">
{{Form::label('telefone', 'Telefone:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('telefone',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('telefone'))
{{$errors->first('telefone')}}
#endif
</div>
<div class="form-group">
{{Form::label('celular', 'Celular:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('celular',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('celular'))
{{$errors->first('celular')}}
#endif
</div>
<div class="form-group">
{{Form::label('rua', 'Rua:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('rua',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('rua'))
{{$errors->first('rua')}}
#endif
</div>
<div class="form-group">
{{Form::label('bairro', 'Bairro:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('bairro',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('bairro'))
{{$errors->first('bairro')}}
#endif
</div>
<div class="form-group">
{{Form::label('complemento', 'Complemento:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('complemento',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('complemento'))
{{$errors->first('complemento')}}
#endif
</div>
<div class="form-group">
{{Form::label('numero', 'Número:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('numero',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('numero'))
{{$errors->first('numero')}}
#endif
</div>
<div class="form-group">
{{Form::label('cep', 'CEP:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('cep',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('cep'))
{{$errors->first('cep')}}
#endif
</div>
<div class="form-group">
{{Form::label('email', 'Email:',['class' => 'col-lg-2 control-label'])}}
{{Form::text('email',null,['class' => 'col-lg-8 form'])}}
#if ($errors->has('email'))
{{$errors->first('email')}}
#endif
</div>
<div class="form-group">
{{Form::label('password', 'Senha:',['class' => 'col-lg-2 control-label'])}}
{{Form::password('password',['class' => 'col-lg-8 form', 'type' => 'password'])}}
#if ($errors->has('password'))
{{$errors->first('password')}}
#endif
</div>
<div class="form-group">
{{Form::label('password_confirmation', 'Confirmação Senha:',['class' => 'col-lg-2 control-label'])}}
{{Form::password('password_confirmation',['class' => 'col-lg-8 form'])}}
#if ($errors->has('password_confirmation'))
{{$errors->first('password_confirmation')}}
#endif
</div>
<div class="form-group">
{{Form::reset('Limpar', array('class' => 'btn btn-danger limpar'))}}
{{Form::submit('Salvar',array('class'=> 'btn btn-success salvar', 'id' => 'validar'))}}
{{Form::close()}}
</div>
</div>
#endsection
The validator function you're overriding expects parameter 1 to be an array and you're passing a Request object to it through dependency injection
Change the parameter to an array and use the request() helper function to get the request object instead
protected function validator(array $data)
{
$this->validate(request(), [
// rest of code
Explanation
The App\Http\Controllers\Auth\RegisterController class is using the trait Illuminate\Foundation\Auth\RegistersUsers so any missing function like say register are going to be executed there.
Let's take a look here
/**
* Handle a registration request for the application.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$this->validator($request->all())->validate(); // <-- Here
event(new Registered($user = $this->create($request->all())));
$this->guard()->login($user);
return $this->registered($request, $user)
?: redirect($this->redirectPath());
}
We're passing the $request->all() which is an array, to the validator by default which means the function validator only accepts an array as
a parameter
Which is coming from vendor/laravel/framework/src/Illuminate/Foundation/helpers.php here
if (!function_exists('validator')) {
/**
* Create a new Validator instance.
*
* #param array $data
* #param array $rules
* #param array $messages
* #param array $customAttributes
* #return \Illuminate\Contracts\Validation\Validator|\Illuminate\Contracts\Validation\Factory
*/
function validator(array $data = [], array $rules = [], array $messages = [], array $customAttributes = [])
{
$factory = app(ValidationFactory::class);
if (func_num_args() === 0) {
return $factory;
}
return $factory->make($data, $rules, $messages, $customAttributes);
}
}
And it explictly states a requirement for parameter 1 to be an array
I hope this helps
Am having a "The 0 field is required." error while trying save data into database when I have no field called 0. without validation from the Controller, the data saves but if I validate even just one field out of the six field I want to validate, I still get the error. How do I solve the issue. Please help out here is my view
<form method="post" action="{{ url('agent/add_tenantProperty') }}" data-toggle="validator">
{{ csrf_field() }}
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtMovieTitle">Tenant</label>
<select id="ddlGenge" class="form-control" name="tenant_id" required="">
#foreach($tenants as $tenant)
<option value="{{ $tenant->id }}">
{{ $tenant->designation }} {{ $tenant->firstname }} {{ $tenant->lastname }}
</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="ddlGenge">Asset Category</label>
<select id="ddlGenge" class="form-control" name="asset_id" required="">
<option>Choose a Property</option>
#foreach($assets as $asset)
<option value="{{ $asset->id }}">{{ $asset->category }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtDirector">Asset description</label>
<select id="ddlGenge" class="form-control" name="description" required="">
<option>Choose a Description</option>
#foreach($assets as $asset)
<option value="{{ $asset->description }}">{{ $asset->description }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtProducer">Location</label>
<select id="ddlGenge" class="form-control" name="address" required="">
<option>Choose an Address</option>
#foreach($assets as $asset)
<option value="{{ $asset->address }}">{{ $asset->address }}</option>
#endforeach
</select>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="txtWebsite">Standard price</label>
<input id="txtWebsite" type="text" class="form-control" name="price" required="">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="txtWriter">Date</label>
<input id="txtWriter" type="date" class="datepicker form-control" name="occupation_date"
required="">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<button type="submit" class="btn btn-outline btn-primary pull-right">Submit</button>
<br/>
</form>
and my controller
public function store(Request $request)
{
//validation
$this->validate($request, array([
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]));
//create and save new data
$tenantProperty = New TenantProperty();
$tenantProperty->tenant_id = $request->tenant_id;
$tenantProperty->asset_id = $request->asset_id;
$tenantProperty->description = $request->description;
$tenantProperty->address = $request->address;
$tenantProperty->price = $request->price;
$tenantProperty->occupation_date = $request->occupation_date;
$tenantProperty->save();
//redirect
return redirect('agent/tenantProperty_list');
}
with the route as follows
Route::get('add_tenantProperty', 'TenantPropertyController#create')->name('/add_tenantProperty');
Route::post('add_tenantProperty', 'TenantPropertyController#store');
When you just write $request, it passes the entire request object but the validate function expect both the arguments to be arrays.
So make a little change and you will be good to go:
$this->validate($request, array( // Removed `[]` from the array.
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
));
The above answer is correct, this is another way to solve the validation problem on laravel 5.5 I asked
$validation = validator::make($request->all(), [
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',
]);
For more information visit https://laravel.com/docs/5.5/validation#manually-creating-validators
$request->validate([
'0'=>'',
'tenant_id' => 'required',
'asset_id' => 'required',
'description' => 'required',
'address' => 'required',
'price' => 'required',
'occupation_date' => 'required',]);