Validation not returning errors Laravel 7 - php

I have been trying to validate input fields on a project I'm working on. It has not been returning the validation errors. Also each time I remove the validation and I attempt to submit the form data after filling it, it returns an undefined index error.
This is my Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\staffLogin;
use Validator;
use App\Country;
use App\Category;
use App\User;
use App\Resume;
use Image;
use Auth;
use Session;
use DB;
class EnrolController extends Controller
{
public function home(){
$title = 'home';
return view('staff.home');
}
public function profile(Request $request){
$title ='profile';
$user_id = Auth::user()->id;
$user_name = Auth::user()->name;
$user_email = Auth::user()->email;
$userDetails = User::find($user_id);
if($request->isMethod('post')){
$data = $request->all();
// echo "<pre>"; print_r($data); die;
$data = request()->validate([
'category_id' => 'required',
// 'firstname' => 'required|regex:/^[\pL\s\-]+$/u|max:255',
// 'lastname' => 'required|regex:/^[\pL\s\-]+$/u|max:255',
'age' => 'required',
'phone' => 'required',
'gender' => 'required',
'address' => 'required',
'country' => 'required',
'image' => 'required',
'cv' => 'required',
'experience' => 'required',
'education' => 'required',
'salary' => 'required',
'employment_type' => 'required',
'summary' => 'required',
]);
$resume = new Resume;
$resume->user_id = $user_id;
$resume->user_name = $user_name;
$resume->user_email = $user_email;
$resume->category_id = $data['category_id'];
$resume->age = $data['age'];
$resume->gender = $data['gender'];
$resume->address = $data['address'];
$resume->country = $data['country'];
$resume->phone = $data['phone'];
// $resume->image = $data['image']->store('uploads/passport');
// $resume->image = $data['cv']->store('uploads/cv');
// Upload Passport
if($request->hasFile('image')){
$image_tmp = $request->image;
if ($image_tmp->isValid()) {
// Upload Images after Resize
$extension = $image_tmp->getClientOriginalExtension();
$fileName = rand(111,99999).'.'.$extension;
$large_image_path = 'images/uploads/passport/large'.'/'.$fileName;
$medium_image_path = 'images/uploads/passport/medium'.'/'.$fileName;
$small_image_path = 'images/uploads/passport/small'.'/'.$fileName;
Image::make($image_tmp)->save($large_image_path);
Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
$resume->image = $fileName;
}
}
// Upload CV
if($request->hasFile('cv')){
$image_tmp = $request->cv;
if ($image_tmp->isValid()) {
// Upload Images after Resize
$extension = $image_tmp->getClientOriginalExtension();
$fileName = rand(111,99999).'.'.$extension;
$large_image_path = 'images/uploads/cv/large'.'/'.$fileName;
$medium_image_path = 'images/uploads/cv/medium'.'/'.$fileName;
$small_image_path = 'images/uploads/cv/small'.'/'.$fileName;
Image::make($image_tmp)->save($large_image_path);
Image::make($image_tmp)->resize(600, 600)->save($medium_image_path);
Image::make($image_tmp)->resize(300, 300)->save($small_image_path);
$resume->cv = $fileName;
}
}
$resume->education = $data['education'];
$resume->experience = $data['experience'];
// $resume->salary = $data['salary'];
if(!empty($data['salary'])){
$resume->salary = $data['salary'];
}else{
$resume->salary = '';
}
$resume->employment_type = $data['employment_type'];
$resume->verification = $data['verification'];
// if(empty($data['verification'])){
// $verification='0';
// }else{
// $verification='1';
// }
$resume->summary = $data['summary'];
// if(!empty($data['summary'])){
// $resume->summary = $data['summary'];
// }else{
// $resume->summary = '';
// }
$resume->status = $data['status'];
// if(empty($data['status'])){
// $status='0';
// }else{
// $status='1';
// }
// $resume->save();
return redirect()->back()->with('flash_message_success', 'Resume Added!!!');
}
// if($request->isMethod('post')){
// $data = $request->all();
// echo "<pre>"; print_r($data); die;
$countries = Country::get();
$categories = Category::where(['parent_id' => 0])->get();
$categories_drop_down = "<option value='' selected disabled>Select</option>";
foreach($categories as $cat){
$categories_drop_down .= "<option value='".$cat->id."'>".$cat->name."</option>";
$sub_categories = Category::where(['parent_id' => $cat->id])->get();
foreach($sub_categories as $sub_cat){
$categories_drop_down .= "<option value='".$sub_cat->id."'> -- ".$sub_cat->name."</option>";
}
}
return view('staff.add_profile')->with(compact('staffDetails', 'categories_drop_down', 'countries'));
}
public function viewProfile() {
$resume = Resume::get();
return view('staff.view_profile')->with(compact('resume'));
}
}
This is my form
#section('content')
<div class="section wb">
<div class="container">
#if(Session::has('flash_message_success'))
<div class="alert alert-success alert-block">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{!! session('flash_message_success') !!}</strong>
</div>
#endif
#if(Session::has('flash_message_error'))
<div class="alert alert-error alert-block" style="background-color:#f4d2d2">
<button type="button" class="close" data-dismiss="alert">×</button>
<strong>{!! session('flash_message_error') !!}</strong>
</div>
#endif
<div class="section-title text-center">
<h3>My Profile {{ Auth::user()->name }}</h3>
</div><!-- end title -->
<form enctype="multipart/form-data" name="addprofile" id="addprofile" method="post" action="{{ url('/add-resume') }}">{{ csrf_field()}}
<div class="form-group">
<label for="category_id">Category</label>
<select class="form-control" id="category_id" name="category_id">
<option value="">Select Category</option>
<?php echo $categories_drop_down; ?>
</select>
</div>
<div class="form-group">
<label for="age">Age</label>
<input type="text" class="form-control" name="age" id="age" placeholder="Age" >
</div>
<div class="form-group">
<label for="gender">Gender</label>
<select class="form-control" id="gender" name="gender" >
<option value="not specified">Select Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
<div class="form-group">
<label for="address">Address</label>
<textarea class="form-control" name="address" id="address" rows="3" ></textarea>
</div>
<div class="form-group">
<label for="country">Country</label>
<select class="form-control" id="country" name="country" >
<option value="">Select Country</option>
#foreach($countries as $country)
<option value="{{ $country->country_name }}">{{ $country->country_name }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="phone">Phone</label>
<input type="phone" class="form-control" name="phone" id="phone" placeholder="Phone" >
</div>
<div class="form-group">
<label for="education">Education Level</label>
<select name="education" class="form-control" >
<option value="" selected disable>Select Education Level</option>
<option value="High School/Secondary School">High School/Secondary School</option>
<option value="Diploma">Diploma</option>
<option value="Bachelors' Degree">Bachelors' Degree</option>
<option value="Masters">Masters</option>
<option value="Doctorate">PhD</option>
</select>
</div>
<div class="form-group">
<label for="experience">Experience</label>
<textarea type="text" class="form-control" rows="3" name="experience" id="experience" placeholder="Experience" ></textarea>
</div>
<div class="form-group">
<label for="salary">Salary</label>
<input type="phone" class="form-control" name="salary" id="salary" placeholder="Expected Base Salary" >
</div>
<div class="form-group">
<label for="employment_type">Employment Type</label>
<select name="employment_type" class="form-control" >
<option value="" selected disable>Select Employment Type</option>
<option value="Any">Any</option>
<option value="Part Time">Part Time</option>
<option value="Full Time">Full Time</option>
<option value="Freelance">Freelance</option>
</select>
</div>
<div class="form-group">
<label for="image">Passport (*jpg, *png, *jpeg)</label>
<input type="file" name="image" class="form-control-file" id="image" >
</div>
<div class="form-group">
<label for="cv">A Page CV (*jpg, *png, *jpeg)</label>
<input type="file" name="cv" class="form-control-file" id="cv" >
</div>
<div class="form-group">
<label for="summary">Summary</label>
<textarea type="text" class="form-control" rows="3" name="summary" id="summary" placeholder="Summary" ></textarea>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</div>
</div>
#endsection
This is my route web.php
// use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
// Route::get('/', function () {
// return view('index');
// });
Route::get('/', 'frontController#index');
Route::get('/home', 'EnrolController#home');
Route::match(['get', 'post'], '/admin', 'AdminController#login');
Route::match(['get', 'post'], '/about', 'frontController#about');
Route::match(['get', 'post'], '/contact', 'frontController#contact');
// Users Login/Register Page
Route::get('/login-register','UsersController#userLoginRegister');
// Staff Register Page
Route::match(['get', 'post'], '/staff-register','StaffController#register');
Route::match(['get','post'],'/forgot-password','UsersController#forgotPassword');
Route::get('/resume/{url}','ResumeController#resumes');
// Resume Detail Page
Route::get('/resume/{id}','ResumeController#resume');
// Users Register Form Submit
Route::post('/user-register','UsersController#register');
// Confirm Account
Route::get('confirm/{code}','UsersController#confirmAccount');
// Confirm Account
Route::get('home/confirm/{code}','StaffController#confirmAccount');
// Users Login Form Submit
Route::post('/user-login','UsersController#login');
// Staff Login Form Submit
Route::post('/staff-login','StaffController#login');
// Staff forgot password
Route::match(['get','post'],'/staff-forgot-password','StaffController#forgotPassword');
// Staff logout
Route::get('/staff-logout','StaffController#logout');
// Users logout
Route::get('/user-logout','UsersController#logout');
Route::match(['get','post'],'/staff-forgot-password','StaffController#forgotPassword');
Route::group(['middleware' => ['stafflogin']], function () {
Route::get('/staff/dashboard', 'StaffController#dashboard');
Route::get('/staff/settings','StaffController#settings');
Route::get('/staff/check-pwd','StaffController#chkPassword');
Route::match(['get', 'post'],'/staff/update-pwd','StaffController#updatePassword');
Route::match(['get', 'post'],'/add-profile','EnrolController#profile');
Route::match(['get', 'post'],'/view-profile','EnrolController#viewProfile');
Route::match(['get','post'],'/add-resume','EnrolController#profile');
Route::get('/admin/view-profile','ResumeController#viewProfile');
Route::match(['get', 'post'], '/admin/edit-resume/{id}','ResumeController#editResume');
});

Try the following
use use Illuminate\Support\Facades\Validator;
//...
$validator = Validator::make($request->all(), [
'category_id' => 'required',
...
]);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
->withInput();
}
$data = $validator->validated();

Related

blade file : $meeting is undefined

Whenever I visit the add-meeting URL, I receive an error message stating that $meeting is undefined. However, when I attempt to edit a meeting, everything works as expected. I am using the same blade file for both creating and updating meetings. Can you explain why this error is occurring?
Here is MeetingController:
public function add_meeting()
{
$customers = Customer::all();
$projects = Project::all();
return view('admin.meeting.add-meeting', get_defined_vars());
}
public function store(Request $request)
{
$this->validate($request, [
'meeting_scedule' => 'required',
'meeting_user_id' => 'required',
'project_id' => 'required',
'agenda' => 'required',
]);
if ($request->id) {
$input['meeting_scedule'] = $request->meeting_scedule;
$input['meeting_user_id'] = $request->meeting_user_id;
$input['project_id'] = $request->project_id;
$input['agenda'] = $request->agenda;
$meeting = Meeting::where('id', $request->id)->update($input);
return back()->with('success', 'Updated Successfully!');
} else {
$new['meeting_scedule'] = $request->meeting_scedule;
$new['meeting_user_id'] = $request->meeting_user_id;
$new['project_id'] = $request->project_id;
$new['agenda'] = $request->agenda;
$meeting = new Meeting();
$meeting->persist($new);
return back()->with('success', 'Meeting Created Successfully!');
}
}
public function edit_meeting($id)
{
$customers = Customer::all();
$projects = Project::all();
$meeting = Meeting::find($id);
return view('admin.meeting.add-meeting', get_defined_vars());
}
Here is add-meeting.blade.php file:
<form action="{{url('admin/update-meeting')}}" method="POST" id="add-rel-form"
enctype="multipart/form-data">
#csrf
#if(isset($meeting))
<input class="hidden" type="hidden" name="id" value="{{$meeting->id ?? ''}}">
#endif
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label> Meeting Schedule</label>
<div class="form-group">
<input type="datetime-local" value="{{$meeting->meeting_scedule ?? ''}}" required
class="form-control" name="meeting_scedule" id="meeting_scedule">
</div>
</div>
<div class="form-group col-md-6 mb-0">
<label> User</label>
<select id="customer-select" class='form-control' required name="meeting_user_id">
<option value="" id="">--Select User--</option>
#foreach($customers as $customer)
<option value="{{$customer->id}}"{{ $customer->id == $meeting->meeting_user_id ? 'selected' : '' }}>{{$customer->first_name." ".$customer->last_name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-row">
<div class="form-group col-md-6 mb-0">
<label> Project</label>
<select id="project-select" class='form-control' required name="project_id" disabled>
<option value="" id="">--Select Project--</option>
#foreach($projects as $project)
<option value="{{$project->id}}"{{$project->id == $meeting->project_id ? 'selected' : ''}}>{{$project->project_type}}</option>
#endforeach
</select>
</div>
<div class="form-group col-md-6 mb-0">
<label> Agenda</label>
<div class="form-group">
<textarea type="text" value="" required
class="form-control" name="agenda" id="agenda">{{$meeting->agenda ?? ''}}</textarea>
</div>
</div>
</div>
Since there is no $meeting variable when creating a new meeting, the error occurs.
You can use null coalescing operator (??) or ternary operator (?:) to check if $meeting is defined before attempting to access its properties :
#if(isset($meeting))
<input class="hidden" type="hidden" name="id" value="{{$meeting->id}}">
#endif
...
<select id="customer-select" class='form-control' required name="meeting_user_id">
<option value="" id="">--Select User--</option>
#foreach($customers as $customer)
<option value="{{$customer->id}}" {{ isset($meeting) && $customer->id == $meeting->meeting_user_id ? 'selected' : '' }}>{{$customer->first_name." ".$customer->last_name}}</option>
#endforeach
</select>
...
<select id="project-select" class='form-control' required name="project_id" disabled>
<option value="" id="">--Select Project--</option>
#foreach($projects as $project)
<option value="{{$project->id}}"{{ isset($meeting) && $project->id == $meeting->project_id ? 'selected' : ''}}>{{$project->project_type}}</option>
#endforeach
</select>
...
<textarea type="text" value="" required class="form-control" name="agenda" id="agenda">{{ isset($meeting) ? $meeting->agenda : '' }}</textarea>

How to import excel file into two tables with input tags at the same time?

I have two table one is users and the next one is students, the students table store the data of users based on their role. and the relation between user and student is user_id in students table.
And the form includes three inputs for text and one for excel file to import. I want to import the users by file and their data by inputs.
my form is like this:
<form method='post' action="{{ route('importExcel') }}" enctype="multipart/form-data">
#csrf
<div class="box-body row">
<div class="col-md-12">
<label for="faculty" class="col-md-12">فاکولته</label>
<div class="form-group">
<select name='faculty' class="form-control" id="faculty">
<option value=""> انتخاب فاکولته </option>
#foreach($faculties as $faculty)
<option value="{{ $faculty->id }}" >{{ $faculty->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-12">
<label for="department" class="col-md-12">دیپارتمنت</label>
<div class="form-group">
<select class="form-control" name="department" id="department">
<option value="">انتخاب دیپارتمنت</option>
#foreach($departments as $department)
<option value="{{ $department->id }}">{{ $department->name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-12">
<label for="sesson" class="col-md-12">فصل</label>
<div class="form-group">
<select name="sesson" id="sesson" class="form-control">
<option value="">انتخاب فصل</option>
<option value="spring">بهار</option>
<option value="fall">خزان</option>
</select>
</div>
</div>
<div class="col-md-12">
<label for="file" class="col-md-12">فایل اکسل</label>
<div class="form-group">
<input type="file" name="file" class="form-control" id="file">
</div>
</div>
<input type="hidden" name="role" value="user">
<input type="hidden" name="admin" value="admin">
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info pull-left submit">تایید</button>
</div>
<!-- /.box-footer -->
</form>
and my import class is like this:
class UsersImport implements ToCollection
{
public function collection(Collection $rows)
{
foreach ($rows as $row)
{
User::create([
'name' => str_replace(' ', '_', $row['name']),
'email' => $row['email'],
'password' => bcrypt(str_replace(' ', '_', $row['name'])),
'role' => 'user',
]);
Student::create([
'user_id' => DB::table('users')->getPdo()->lastInsertId(),
'department_id' => $row['department'],
'faculty_id' => $row['faculty'],
'sesson' => $row['sesson']
]);
}
}
}
and my controller is like this:
try{
$this->validate($request,[
'faculty' => 'required',
'department'=> 'required',
'sesson'=> 'required',
'file'=> 'required',
]);
$file = $request->file('file');
$faculty = $request-> faculty;
$department = $request -> department;
$sesson = $request -> sesson;
Excel::import(new UsersImport,[$file, $faculty, $department, $sesson]);
return redirect()->route('admin.students')->with('success','عملیات موفقانه انجام شد.');
}
catch(Exception $e){
return redirect()->back()->with('error','عملیات انجام نشد!');
}
but its not working, the error is like this: pathinfo() expects parameter 1 to be string, array given

Unable to upload a image ; laravel 6.0

I'm a new to Laravel and using Laravel6.0. While doing validation I'm getting a error.
The picture must be an image. The picture must be a file. The picture must be a file of type: jpeg, png, jpg, gif.
I'm searching a solution on google, but cannot find correct an answer.
I added dd(request) in my rules() ,but I got the same error.
This is my ContentController, ContentRequest and create.blade.php.
#extends('layouts.app')
#section('content')
<div class="card">
<div class="card-body">
<form action="{{route('content.store')}}" method="post" enctype="multipart/form-data" >
#csrf
<div class="form-group">
<label for="exampleFormControlInput1">タイトル</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="旅のタイトル" name="title" value="{{old('title')}}" >
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">大陸名</label>
<select class="form-control" id="exampleFormControlSelect1" name="continent" value="{{old('continent')}}">
<option>アジア</option>
<option>北アメリカ</option>
<option>中南米</option>
<option>ヨーロッパ</option>
<option>アフリカ</option>
<option>オセアニア</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlInput1">国名</label>
<input type="text" class="form-control" id="exampleFormControlInput1" placeholder="日本" name="country" value="{{old('country')}}">
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">滞在期間</label>
<select class="form-control" id="exampleFormControlSelect1" name="span" placeholder="滞在期間を選択" >
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
<option>11</option>
 <option>12</option>
 <option>13</option>
 <option>14</option>
 <option>15</option>
 <option>16</option>
 <option>17</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlSelect1">費用</label>
<select class="form-control" id="exampleFormControlSelect1" name="costs" placeholder="金額を選択" value='{{old('costs')}}'>
<option>10000</option>
<option>30000</option>
<option>50000</option>
<option>70000</option>
<option>100000</option>
<option>150000</option>
<option>200000</option>
<option>250000</option>
<option>300000</option>
</select>
</div>
<div class="form-group">
<label for="exampleFormControlFile1">写真</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1" name="picture" value="{{old('picture')}}">
<div class="input-group-append">
<button type="submit" class="btn btn-outline-secondary reset"><i class="fas fa-times fa-fw"></i>取消</button>
</div>
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">コンテンツ</label>
<textarea class="form-control" id="exampleFormControlTextarea1" rows="5" name="content" >{{old('content')}}</textarea>
</div>
<input type="hidden" name="user_id" value="{{Auth::id()}}">
<button type="submit" class="btn btn-primary btn-lg btn-block">投稿</button>
</form>
</div>
</div>
#endsection
ContentRequest
public function rules()
{
return [
'user_id'=>'required',
'title' => 'required|string|max:255',
'continent' => 'required|string',
'picture'=>'required|image|max:1000',
'country' => 'required|string',
'costs'=>'required|numeric',
'span'=>'required|numeric',
'content'=>'required|string|max:250',
];
}
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ContentRequest;
use App\Content;
class ContentController extends Controller
public function store(ContentRequest $request)
{
if($request->validated()){
$content =new Content;
$filename = $request->file('image')->store('public/image');
$content->picture = basename($filename);
$content->user_id = $request->user_id;
$content->content = $request->content;
$content->title = $request->title;
$content->span = $request->span;
$content->continent = $request->continent;
$content->country = $request-> country;
$content->costs = $request->costs;
$content->save();
}
return redirect('/');
}
You have to use like this
'picture' => 'required|image|mimes:jpeg,jpg,png|max:1000',
try this
public function rules()
{
return [
'user_id'=>'required',
'title' => 'required|string|max:255',
'continent' => 'required|string',
'picture'=>'required|mimes:jpeg,png,jpg,gif|max:1000',
'country' => 'required|string',
'costs'=>'required|numeric',
'span'=>'required|numeric',
'content'=>'required|string|max:250',
];
}
and in the store function
if($request->validated()){
$content =new Content;
$filename = $request->file('image')->store('public/image');
$content->picture = basename($filename);
$content->user_id = $request->user_id;
$content->content = $request->content;
$content->title = $request->title;
$content->span = $request->span;
$content->continent = $request->continent;
$content->country = $request-> country;
$content->costs = $request->costs;
$content->save();
}

One page CRUD form operation (Laravel6)

I have a table in my database with contact details. On my form, I have a Dropdown which displays the names of people, and which, once I click on the name, fills in the fields with the data (ajax).
The problem happens when I want to perform operations on the form data.
For example, I click on "M Bram Manu" (id = 1) in the Dropdown. My Ajax will fill out my form with the details of this contact.
But when I want to update, delete or add a new contact, it doesn't work properly.
So, if I click on "delete", it not delete the contact I choose but the last contact of the dropdown list. Why???
So I think my link retrieves the last ID from my dropdown, so I decided to put an hidden Input with the value of the contact ID that appears in the form. But I don't know how to retrieve this value to define it as the ID to send to the controller.
Dropdown bar and link button :
<form class="col-md-9">
<label class="col-md-2">Rechercher : </label>
<select class="form-control select2 col-md-7" id="selInscrit" name="selInscrit" onchange="selectID()">
<option value="0" selected="selected"></option>
#foreach($inscrit as $inscrits)
<option value="{{$inscrits->INS_ID}}">{{$inscrits->INS_CIVILITE}} {{$inscrits->INS_NOM}} {{$inscrits->INS_PREN}} {{$inscrits->INS_NUM_RUE}} {{$inscrits->INS_Rue}} </option>
#endforeach
</select>
</form>
<div class="btn-group btn-group-sm col-md-3" role="group">
<form action="" method="GET">
<button type="submit" class="btn btn-secondary btn-sm">Edit</button>
</form>
<button type="submit" form="registerForm" formmethod="POST" formaction="{{ route('inscrits.store') }}" class="btn btn-secondary btn-sm">Save</button>
<button type="submit" form="registerForm" formmethod="POST" formaction="{{ route('inscrits.update') }}" class="btn btn-secondary btn-sm">Update</button>
<form action="{{ route('inscrits.destroy') }}" method="POST">
<input id="INS_ID" name="INS_ID" value="" type="hidden">
#method('DELETE')
#csrf
<button type="submit" class="btn btn-secondary btn-sm">Delete </button>
</form>
</div>
Ajax for dropdown :
<script>
$('#selInscrit').change(function() {
var id = $(this).val();
var url = '{{ route("inscrits.show", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#INS_ID').val(response.INS_ID);
$('#INS_CIVILITE').val(response.INS_CIVILITE);
$('#INS_NOM').val(response.INS_NOM);
$('#INS_PREN').val(response.INS_PREN);
$('#INS_NAISS').val(response.INS_NAISS);
$('#INS_AGE').val(response.INS_AGE);
$('#INS_NUM_RUE').val(response.INS_NUM_RUE);
$('#INS_Rue').val(response.INS_Rue);
$('#INS_TEL1').val(response.INS_TEL1);
$('#INS_OBS').val(response.INS_OBS);
$('#INS_DATE').val(response.INS_DATE);
$('#INS_TEL2').val(response.INS_TEL2);
}
}
});
});
Route :
// INSCRITS
/ route for index
Route::get('/inscrits', 'InscritController#index')->name('inscrits.index');
// route for dropdown bar
Route::get('/inscrits/show/{id}', 'InscritController#show')->name('inscrits.show');
// route for update
// Route::match(['put', 'patch'], '/inscrits/update','InscritController#update')->name('inscrits.update');
Route::post('/inscrits/update','InscritController#update')->name('inscrits.update');
// route for store
Route::post('/inscrits/store', 'InscritController#store')->name('inscrits.store');
//route for delete
Route::delete('/inscrits/destroy', 'InscritController#destroy')->name('inscrits.destroy');
Form :
<form id="registerForm">
#csrf
<div class="form-group row">
<div class="col-lg-1">
<label for="INS_CIVILITE">Civilité</label>
<select class="form-control form-control-sm" id="INS_CIVILITE" name="INS_CIVILITE">
<option value="" selected="selected"></option>
<option value="Mme">Mme</option>
<option value="Mlle">Mlle</option>
<option value="M.">M.</option>
</select>
</div>
<div class="col-lg-4">
<label for="INS_NOM">Nom</label>
<input class="form-control form-control-sm" id="INS_NOM" name="INS_NOM" value="" type="text">
</div>
<div class="col-lg-3">
<label for="INS_PREN">Prénom</label>
<input class="form-control form-control-sm" id="INS_PREN" name="INS_PREN" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_NAISS">Année Naiss</label>
<input class="form-control form-control-sm" id="INS_NAISS" name="INS_NAISS" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_AGE">Age</label>
<input class="form-control form-control-sm" id="INS_AGE" name="INS_AGE" value="" type="text">
</div>
</div>
<div class="form-group row">
<div class="col-lg-1">
<label for="INS_NUM_RUE"># Rue</label>
<input class="form-control form-control-sm" id="INS_NUM_RUE" name="INS_NUM_RUE" value="">
</div>
<div class="col-lg-9">
<label for="INS_Rue">Libellé voie</label>
<select class="form-control form-control-sm" id="INS_Rue" name="INS_Rue">
#foreach($rue as $rues)
<option value="{{$rues->RUE_NUM}}">{{$rues->RUE_NOM}} ({{$rues->RUE_Type}})</option>
#endforeach
</select>
</div>
<div class="col-lg-2">
<label for="INS_TEL1">Téléphone 1</label>
<input class="form-control form-control-sm" id="INS_TEL1" name="INS_TEL1" value="" type="text">
</div>
</div>
<div class="form-group row">
<div class="col-lg-8">
<label for="INS_OBS">Observation</label>
<input class="form-control form-control-sm" id="INS_OBS" name="INS_OBS" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_DATE">Date d'inscription</label>
<input class="form-control form-control-sm" id="INS_DATE" name="INS_DATE" value="" type="text">
</div>
<div class="col-lg-2">
<label for="INS_TEL2">Téléphone 2</label>
<input class="form-control form-control-sm" id="INS_TEL2" name="INS_TEL2" value="" type="text">
</div>
</div>
<input id="INS_LIEU" name="INS_LIEU" value="WEB" type="hidden">
<input id="INS_EID" name="INS_EID" value="" type="hidden">
</form>
The controller :
public function index()
{
$inscrit = Inscrit::all();
return view('index', compact('inscrit'));
}
public function store(Request $request)
{
$storeData = $request->validate([
'INS_CIVILITE' => 'max:15',
'INS_NOM' => 'max:50',
'INS_PREN' => 'max:50',
'INS_NUM_RUE' => 'max:8',
'INS_TEL1' => 'max:10',
'INS_TEL2' => 'max:10',
'INS_AGE' => 'numeric',
'INS_OBS' => 'max:255',
'INS_Rue' => 'max:255',
'INS_DATE' => 'max:255',
'INS_NAISS' => 'max:255',
]);
$inscrit = Inscrit::create($storeData);
return redirect('/inscrits')->with('completed', 'Nouvel inscrit !');
}
public function show($id = 0)
{
$data = Inscrit::where('INS_ID', $id)->first();
return response()->json($data);
}
public function edit($id)
{
$inscrit = Inscrit::findOrFail($id);
return view('index', compact('inscrit'));
}
public function update(Request $request, $id)
{
$updateData = $request->validate([
'INS_CIVILITE' => 'max:15',
'INS_NOM' => 'max:50',
'INS_PREN' => 'max:50',
'INS_NUM_RUE' => 'max:8',
'INS_TEL1' => 'max:10',
'INS_TEL2' => 'max:10',
'INS_AGE' => 'numeric',
'INS_OBS' => 'max:255',
'INS_Rue' => 'max:255',
'INS_DATE' => 'max:255',
'INS_NAISS' => 'max:255',
]);
$id = request()->input('INS_EID');
Inscrit::where('INS_ID', $id)->update($updateData);
return redirect('/inscrits')->with('completed', 'inscrit mis à jour');
}
public function destroy($id)
{
$id = request()->input('INS_ID');
$inscrit = Inscrit::where('INS_ID', $id)->delete();
return redirect('/inscrits')->with('completed', 'inscrit supprimé');
}
The form
Database
Something like :
public function edit ($id) {
$inscritContent = Inscrit::where('id', $id)->firstOrFail();
return view('admin.inscrit.edit.form', [
'content' => $iscritContent
]);
}
public function update($id, Request $req) {
$inscrit = Inscrit::findOrFail($id);
$inscrit->update($req->all());
return redirect(route('admin.inscrit.index'));
}
admin.inscrit.edit.form and admin.inscrit.index are blade template

In laravel trying to register a company But when clicking on submit button it redirects me back on the form again and create no entry in DB

Here is my signup form
#extends('Layouts.master')
#section('title')
welcome
#endsection
#section('content')
#if(count($errors)>1)
<div class="row">
<div class="col-md-4">
<ul>
#foreach($errors->all() as $errors)
<li>{{$errors}}</li>
#endforeach
</ul>
</div>
</div>
#endif
<div class="row" style="background-color:#FFF8F2;">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<div class="panel panel-danger">
<div class="panel-heading">
<h3>Sign Up As A Company</h3>
</div>
<div class="panel-body">
<form action="{{route('companysignup')}}" method="post" role="form">
<div class="form-group">
<label>Enter Company Name</label>
<input placeholder="Enter Name" name="company_name" class="form-control">
</div>
<div class="form-group">
<label>Enter Owner Name</label>
<input placeholder="Enter Owner Name" name="owner_name" class="form-control">
</div>
<div class="form-group">
<label>Enter Owner Email</label>
<input placeholder="Enter Owner Email" name="email" class="form-control">
</div>
<div class="form-group">
<label>Enter Phone Number</label>
<input placeholder="Enter Phone Number" name="phone_number" class="form-control">
</div>
<div class="form-group">
<label>Company Type</label>
<select name="company_type" class="form-control">
<option>Combined</option>
<option>Individual</option>
<option>None</option>
</select>
</div>
<div class="form-group">
<label>Country</label>
<select name="country" class="form-control">
<option>Pakistan</option>
<option>Sudia Arabia</option>
<option>America</option>
<option>India</option>
</select>
</div>
{{--<div class="form-group">--}}
{{--<label>Attach Registration Extract</label>--}}
{{--<input type="file" name="file">--}}
{{--</div>--}}
<div class="form-group">
<label>Enter short description about your company</label>
<textarea name="description" rows="3" class="form-control"></textarea>
</div>
<div class="form-group">
<label>Enter Password</label>
<input name="password " type="password" placeholder="Enter Password" class="form-control">
</div>
{{csrf_field()}}
<input class="btn btn-outline btn-danger" type="submit" value="Submit">
</form>
</div>
<div class="panel-footer">
</div>
</div>
</div>
<div class="col-lg-2">
</div>
</div>
#endsection
here is my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
class Company extends Model
{
use Notifiable;
protected $table = 'company';
public function user()
{
return $this->belongsTo('App\User');
}
protected $fillable = [
'user_id',
'company_name',
'owner_name',
'phone_number',
'country',
'company_type',
'description'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'remember_token'
];
}
Here is my web.php code
Route::group(['middleware'=>['web']],function(){
Route::post('/companysignup',[
'uses' => 'CompanyController#companySignUp',
'as' => 'companysignup'
]);
});
Function is added company signup.
public function companySignUp(Request $request)
{
$this->validate($request,[
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
'company_name' => 'required|max:120',
'owner_name' => 'required|max:120',
'phone_number' => 'required|min:12|max:14',
'company_type' => 'required',
'country' => 'required',
'description' => 'required'
]);
$email = $request['email'];
$password = bcrypt($request['password']);
$user = new User();
$user->email = $email;
$user->password = $password;
$user->role = 1; // Regular = 0, Company - 1
$user->save();
$company_name = $request['company_name'];
$owner_name = $request['owner_name'];
$country = $request['country'];
$phone_number = $request['phone_number'];
$company_type = $request['company_type'];
$description = $request['description'];
$company = new Company();
$company->user_id = $user->id;
$company->company_name = $company_name;
$company->owner_name = $owner_name;
$company->phone_number = $phone_number;
$company->company_type = $company_type;
$company->country = $country;
$company->description = $description;
$company->save();
return view('frontend.user');
}
Now you can check my function in controller Please suggest me solution for this problem .
First your validation is failing for some reasons. One of the reasons is that country is required but you don't send any country. Your country options are all empty. You did
<select name="country" class="form-control">
<option>Pakistan</option>
<option>Sudia Arabia</option>
<option>America</option>
<option>India</option>
</select>
In each of your options, add a value like
<option value="paskistan">Pakistan</option>
You are displaying errors in your view, so somehow it is supposed to display those validation errors to the screen.
Then the way you save your data, it's a little bit too much because your grab your variable and then use them. You could do both in one go
$company = Company::create([
'user_id' => $user->id,
'company_name' => $request->company_name,
'owner_name' => $request->owner_name,
//add all in your input the same way
'description' => $request->description
]);
And this will create a company and return the object to you.

Categories