Why am getting unexpected redirect (302) error when saving the data in Laravel? - laravel

In my application, I am getting the error 302 when trying to save the data. I am posting my codes here, please someone look into this and help me.
HolidayAdd.vue
<template>
<layout>
<div class="container">
<form #submit.prevent="handleSubmit">
<div class="form-group">
<label for="fname">First Name</label>
<input id="fname" type="text" class="form-control" name="ftname" placeholder="Enter your First Name" v-model="holiday.fname">
</div>
<div class="form-group">
<label for="lname">Last Name</label>
<input id="lname" type="text" class="form-control" name="lastname" placeholder="Enter your Last Name" v-model="holiday.lname">
</div>
<div class="form-group">
<label for="sdate">Start Date</label>
<input type="date" class="form-control" name="sdate" v-model="holiday.sdate" id="sdate">
</div>
<div class="form-group">
<label for="edate">End Date</label>
<input type="date" class="form-control" name="edate" v-model="holiday.edate" id="edate">
</div>
<button class="btn btn-info">Apply</button>
</form>
</div>
</layout>
</template>
<script>
import Layout from './../../Shared/Layout'
export default {
components: {
Layout
},
data() {
return {
holiday: {
fname: '',
lname: '',
sdate: '',
edate: ''
}
}
},
methods: {
async handleSubmit() {
let response = await this.$inertia.post('/holiday', this.holiday)
}
}
}
</script>
HolidayController.php
public function store(Request $request)
{
$holiday = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
Holiday::create($holiday);
return redirect()->route('holiday.index');
}
web.php
Route::group(['middleware' => 'auth'], function() {
Route::resource('holiday', 'HolidayController');
});
As far as I know, there is no error, then why I am getting a 302 error here?

This is happening because of the validation at your store action. you need to change
holiday: {
fname: '',
lname: '',
sdate: '',
edate: ''
}
to
holiday: {
'firstname' : '',
'lastname' : '',
'startdate' : '',
'enddate' : ''
}
and then change v-model to the new names. then you need to do some validation in your front-end.also you shouldn't return a redirect response if request is ajax.

Related

Laravel multi select options ajax request

I'm trying to add multiple courses for a user using ajax. When I click on submit button, everything else updated but the courses. I don't know what I did wrong. Please help me...
This is my blade:
<input type="hidden" name="user_id" id="user_id" value="{{$user_details->id}}">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" value="{{$user_details->name}}">
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="text" class="form-control" id="email" name="email" value="{{$user_details->email}}">
</div>
<div class="form-group">
<label for="courses_id">Courses</label>
#php
$all_courses = $user_details->courses_id;
#endphp
<select name="courses_id[]" multiple id="course" class="form-control nice-select wide">
#foreach($courses as $data)
#if($all_courses)
<option #if(in_array($data->id,$all_courses)) selected #endif value="{{$data->id}}">{{$data->title}}</option>
#else
<option value="{{$data->id}}">{{$data->title}}</option>
#endif
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary mt-4 pr-4 pl-4">{{__('Update User')}}</button>
</form>
<script>
$(document).ready(function() {
if($('.nice-select').length > 0){
$('.nice-select').niceSelect();
}
$(document).on('change','select[name="courses_id[]"]',function (e) {
e.preventDefault();
var selectedId = $(this).val();
$.ajax({
url : "{{route('admin.user.course.by.slug')}}",
type: "POST",
data: {
_token : "{{csrf_token()}}",
id: selectedId
},
success:function (data) {
$('#course').html('');
$.each(data,function (index,value) {
$('#course').append('<option '+selected+' value="'+value.id+'">'+value.title+'</option>');
$('.nice-select').niceSelect('update');
});
}
});
});
} );
</script>
My controller:
namespace App\Http\Controllers;
use App\Courses;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
class UserController extends Controller
{
public function edit($id)
{
$user_details = User::find($id);
$courses = Courses::where(['status'=> 'publish'])->get();
return view('backend.user.edit-user')->with([ 'user_details' => $user_details, 'courses' => $courses]);
}
public function user_update(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:191',
'email' => 'required|string|max:191',
'courses_id' => 'nullable',
],[
'name.required' => __('Name is required'),
'email.required' => __('Email is required'),
]);
User::find($request->user_id)->update([
'name' => $request->name,
'email' => $request->email,
'courses_id' => serialize($request->courses_id),
]);
return redirect()->back()->with(['msg' => __('User Profile Updated Successfully..'), 'type' => 'success']);
}
public function course_by_slug(Request $request){
$all_courses = Courses::where(['status' => 'publish'])->get();
return response()->json($all_courses);
}
}
My route:
Route::prefix(user')->middleware(['adminPermissionCheck:Users Manage'])->group(function () {
Route::get('/edit/{id}', 'UserController#edit')->name('admin.user.edit');
Route::post('/update', 'UserController#user_update')->name('admin.user.update');
Route::post('/course-by-slug', 'UserController#course_by_slug')->name('admin.user.course.by.slug');
});

Upload image file with specified name using laravel

I want to store the image file with the id as a name .
So I tried the following code :
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'casting_photo' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($validator->passes()) {
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_photo' =>$request->casting_photo];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
}
But it gives me the 500 (Internal Server Error)
EDIT
if ($validator->passes()) {
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
'casting_photo'=> $input['casting_photo'] ];
Casting::create($data);
return response()->json(["status" => "success", "message" => "Success! post created."]);
}
return response()->json(["status" => "failed", "message" => "Alert! post not created"]);
I tried that and the same error occurs.
EDIT2
$fileName = $request->get('id') . '.' . $request->file('casting_photo')->extension();
$request->file('casting_photo')->storeAs('castingimages', $fileName);
But in databse I finf the image stored with just the extension like .png
EDIT3
<form id="castingform" method="post" action="castings" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="id" />
<div class="form-group col-md-6">
<label for="casting_name">Nom</label>
<input type="text" class="form-control" id="casting_name" name="casting_name" placeholder="Nom" >
<span class="text-danger">{{ $errors->first('casting_name') }}</span>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">Upload</span>
</div>
<div class="custom-file">
<input type="file" name="casting_photo" class="custom-file-input" id="casting_photo">
<div class="input-group-prepend">
<span class="text-danger">{{ $errors->first('casting_photo') }}</span>
</div>
<label class="custom-file-label" for="casting_photo">Choose file</label>
</div>
</div>
<button type="submit" id="createBtn" class="btn btn-success">Sign in</button>
</form>
You are accessing unknown id from request
$input['casting_photo'] = $request->Casting()->id .'.'.$request->casting_photo->extension();
it should be
$request->casting_photo->storeAs(public_path('castingimages'),$request->id.'.'.$request->casting_photo->extension() );
Updated
$request->casting_photo->storeAs(public_path('castingimages'),$request->Casting()->id.'.'.$request->casting_photo->extension() );
$data = ['casting_name' => $request->casting_name,
'casting_cin' => $request->casting_cin,
'casting_email' => $request->casting_email,
'casting_phone' => $request->casting_phone,
'casting_age' => $request->casting_age,
'casting_sexe' => $request->casting_sexe,
'casting_city' => $request->casting_city,
'casting_address' => $request->casting_address,
$casting=Casting::create($data);
$casting->casting_photo=$casting->id.'.'.$request->casting_photo->extension() );
$casting->save();

Laravel - Some fields save null to the database in my Laravel Project

I derived some data from jQuery in Laravel-5.8:
Model Class:
class HrLeaveRequest extends Model
{
protected $table = 'hr_leave_requests';
protected $primaryKey = 'id';
protected $fillable = [
'id',
'company_id',
'employee_id',
'reason',
'leave_type_id',
'commencement_date',
'resumption_date',
'authorized_days',
'available_days',
'leave_status',
'no_of_days',
'relief_officer_id',
'contact_person_fullname',
'contact_person_phone',
'contact_person_address',
'created_by',
'created_at',
'updated_by',
'updated_at',
'is_active'
];
protected $dates = [];
protected $casts = [];
public function reliefofficer()
{
return $this->belongsTo('App\Models\Hr\HrEmployee','relief_officer_id');
}
public function leavetype()
{
return $this->belongsTo('App\Models\Hr\HrLeaveType','leave_type_id');
}
}
Controller
public function store(StoreLeaveRequestRequest $request)
{
$leaverequest = HrLeaveRequest::create([
'leave_type_id' => $request->leave_type_id,
'employee_id' => $userEmployee,
'commencement_date' => $commencementDate,
'resumption_date' => $resumptionDate,
'authorized_days' => $request->authorized_days,
'available_days' => $request->available_days,
'no_of_days' => $days,
'reason' => $request->reason,
'relief_officer_id' => $request->relief_officer_id,
'contact_person_fullname' => $request->contact_person_fullname,
'contact_person_phone' => $request->contact_person_phone,
'contact_person_address' => $request->contact_person_address,
'company_id' => Auth::user()->company_id,
'created_by' => Auth::user()->id,
'created_at' => date("Y-m-d H:i:s"),
'is_active' => 1,
]);
Session::flash('success', 'Leave Request is created successfully');
return redirect()->route('service.leave_requests.index');
}
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#leave_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.leavecounts.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
$('#authorized_leave_days').val(data.authorizedleavedays);
$('#available_leave_daysx').val(data.availableleavedays);
let sumAvailableDays = parseInt(data.authorizedleavedays) - parseInt(data.availableleavedays);
$("#available_leave_days").val(sumAvailableDays);
},
error:function(){
}
});
});
});
</script>
I derived 'authorized_days' and 'available_days' from the jQuery above and loaded the result into:
view
<form action="{{route('service.leave_requests.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="col-sm-4">
<div class="form-group">
<label>Leave Type:<span style="color:red;">*</span></label>
<select id="leave_type" class="form-control select2bs4" data-placeholder="Choose Leave Type" tabindex="1" name="leave_type_id" style="width: 100%;">
<option value="">Select Leave Type</option>
#if($leavetypes->count() > 0)
#foreach($leavetypes as $leavetype)
<option value="{{$leavetype->id}}">{{$leavetype->leave_type_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<input type="hidden" id="available_leave_daysx" class="form-control" value="0" >
<div class="col-sm-4">
<div class="form-group">
<label>Commencement Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="commencement_date" value="{{old('commencement_date')}}" min="{{Carbon\Carbon::now()->addDay()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Resumption Date:<span style="color:red;">*</span></label>
<input type="date" class="form-control" placeholder="dd/mm/yyyy" name="resumption_date" value="{{old('resumption_date')}}" min="{{Carbon\Carbon::now()->addDay()->format('Y-m-d')}}" max="{{Carbon\Carbon::now()->lastOfYear()->format('Y-m-d')}}">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Relief Officer:<span style="color:red;">*</span></label>
<select class="form-control select2bs4" data-placeholder="Choose Relief Officer" tabindex="1" name="relief_officer_id" style="width: 100%;">
<option value="">Select Relief Officer</option>
#if($reliefofficers->count() > 0)
#foreach($reliefofficers as $reliefofficer)
<option value="{{$reliefofficer->id}}">{{$reliefofficer->employee_code}} - {{$reliefofficer->first_name}} {{$reliefofficer->last_name}}</option>
#endforeach
#endif
</select>
</div>
</div>
<div class="col-sm-12">
<div class="form-group">
<label>Reason</label>
<textarea rows="2" name="reason" class="form-control" placeholder="Enter Reason here" value="{{old('reason')}}"></textarea>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Contact Person Name:<span style="color:red;">*</span></label>
<input type="text" name="contact_person_fullname" placeholder="Enter contact person name here" class="form-control" value="{{old('contact_person_fullname')}}">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Contact Person Phone:<span style="color:red;">*</span></label>
<input type="number" name="contact_person_phone" placeholder="e.g. 23455996633" class="form-control" value="{{old('contact_person_phone')}}" pattern="[0-9]{13}" style="width: 100%;" maxlength="14">
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Authorized Leave Days:</label>
<input type="number" id="authorized_leave_days" class="form-control authorized_days" name="authorized_days" value="{{old('authorized_days')}}" style="width: 100%;" disabled>
</div>
</div>
<div class="col-sm-4">
<div class="form-group">
<label>Available Leave Days:</label>
<input type="number" id="available_leave_days" class="form-control available_days" name="available_days" value="{{old('available_days')}}" style="width: 100%;" disabled>
</div>
</div>
<div class="card-footer">
<button type="submit" id="submit_create" class="btn btn-primary">{{ trans('global.save') }}</button>
'service.leave_requests.index')}}'" class="btn btn-default">Cancel
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#leave_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.leavecounts.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
$('#authorized_leave_days').val(data.authorizedleavedays);
$('#available_leave_daysx').val(data.availableleavedays);
let sumAvailableDays = parseInt(data.authorizedleavedays) - parseInt(data.availableleavedays);
$("#available_leave_days").val(sumAvailableDays);
},
error:function(){
}
});
});
});
</script>
And I see the data there clearly on my screen, but when I saved it I found null in each of the fields.
Then I did:
dd($leaverequest);
and I have this:
dd($leaverequest):
#attributes: array:17 [▼
"leave_type_id" => "1"
"employee_id" => 2
"commencement_date" => Carbon\Carbon #1586559600 {#804 ▶}
"resumption_date" => Carbon\Carbon #1587769200 {#790 ▶}
"authorized_days" => null
"available_days" => null
"no_of_days" => 11
"relief_officer_id" => "10"
"contact_person_fullname" => "assasasaddddd"
"contact_person_phone" => "08099448844"
"contact_person_address" => "xxzxzxzxz ddds"
"company_id" => 1
"created_by" => 2
"created_at" => "2020-04-10 22:10:41"
"is_active" => 1
"id" => 9
]
You can see:
"authorized_days" => null
"available_days" => null
How do I resolve this?
Thank you

Why am getting method not allowed error when saving the data in Laravel?

In my application, I am getting the error method not allowed when trying to save the data. I am posting my codes here, please someone look into this and help me.
HolidayAdd.vue
<template>
<layout>
<form #submit.prevent="handleSubmit">
<div class="input-group">
<div class="input-group-prepend">
<span for="name" class="input-group-text">First Name and Last Name </span>
</div>
<input type="text" class="form-control" name="firstname" placeholder="Enter your First Name" v-model="holiday.fname" id="fname">
<input type="text" class="form-control" name="lastname" placeholder="Enter your Last Name" v-model="holiday.lname" id="lname">
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Start Date </span>
</div>
<input type="date" class="form-control" name="startdate" v-model="holiday.sdate" id="sdate">
</div>
<br>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">End Date</span>
</div>
<input type="date" class="form-control" name="enddate" v-model="holiday.edate" id="edate">
</div>
<br>
<button type="submit" class="btn btn-info">Apply</button>
</form>
</layout>
</template>
<script>
import Layout from './../../Shared/Layout'
export default {
components: {
Layout
},
data() {
return {
holiday: {
fname: '',
lname: '',
sdate: '',
edate: ''
}
}
},
methods: {
async handleSubmit() {
let response = await this.$inertia.post('/holiday/store', this.holiday)
}
}
}
</script>
HolidayController.php
public function store(Request $request)
{
$holiday = $request->validate([
'firstname' => 'required',
'lastname' => 'required',
'startdate' => 'required',
'enddate' => 'required'
]);
Holiday::create($holiday);
return redirect()->route('holiday.index')->with('success', 'Record Inserted Successfully');
}
web.php
Route::resource('holiday', 'HolidayController');
As far as I know, there is no error, then why I am getting a 405 error here?
In your Vue code your should use POST request to the '/holiday' instead of the '/holiday/store'.
Defining resource route is equivalent to:
Route::get('/holiday', 'HolidayController#index');
Route::get('/holiday/create', 'HolidayController#create');
Route::post('/holiday', 'HolidayController#store');
Route::get('/holiday/{holiday}', 'HolidayController#show');
Route::get('/holiday/{holiday}/edit', 'HolidayController#edit');
Route::put('/holiday/{holiday}', 'HolidayController#update');
Route::patch('/holiday/{holiday}', 'HolidayController#update');
Route::delete('/holiday/{holiday}', 'HolidayController#destroy');
https://laravel.com/docs/5.8/controllers#resource-controllers
Your url '/holiday/store' dose not much Route::resource('holiday', 'HolidayController');
Fix
await this.$inertia.post('holiday', this.holiday)
To check routes and its corresponding URIs
Run the following command
php artisan route:list

Why i am getting 'No Access-Control-Allow-Origin'

I am getting this error "Access to XMLHttpRequest at 'http://localhost/api/auth/register' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."
<template>
<div class="container mt-2">
<form autocomplete="off" #submit.prevent="register" method="post">
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.email }">
<label for="email">E-mail</label>
<input type="email" id="email" class="form-control bg-light border-0 small" placeholder="user#example.com" v-model="email">
<span class="help-block" v-if="has_error && errors.email">{{ errors.email }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password">Password</label>
<input type="password" id="password" class="form-control bg-light border-0 small" v-model="password">
<span class="help-block" v-if="has_error && errors.password">{{ errors.password }}</span>
</div>
<div class="form-group" v-bind:class="{ 'has-error': has_error && errors.password }">
<label for="password_confirmation">Conform Password</label>
<input type="password" id="password_confirmation" class="form-control bg-light border-0 small" v-model="password_confirmation">
</div>
<div class="alert alert-danger" v-if="has_error && !success">
<p v-if="error == 'registration_validation_error'">Validation error</p>
<p v-else>Please fill all the fields to get registered</p>
</div>
<input type="hidden" name="_token" :value="csrf">
<div class="text-center pb-3">
<button type="submit" class="btn btn-success btn-sm" style="background-color:#00A7F5;border:none;">Register</button>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {
email: '',
password: '',
password_confirmation: '',
csrf: document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
has_error: false,
error: '',
errors: {},
success: false
}
},
methods: {
register() {
var app = this
this.$auth.register({
data: {
email: app.email,
password: app.password,
password_confirmation: app.password_confirmation
},
success: function () {
app.success = true
},
error: function (res) {
app.has_error = true
app.error = res.response.error
app.errors = res.response.errors || {}
}
})
}
}
}
</script>
if fails, response from controller
$a = Validator::make($request->all(), [
'email' => 'required|email|unique:users',
'password' => 'required|min:6|confirmed',
]);
if ($a->fails())
{
return response()->json([
'status' => 'error',
'errors' => $a->errors()
], 422);
}
if everything ok then
return response()->json(['status' => 'success'], 200);
Please let me know whats wrong with this and is there any better way to handle error. Please share link then, i am not able to handle error correctly.
All helps are appreciated.
CORS policy checks strictly on domain plus port. So make both the same will be the solution.
You need to add CORS Service Provider to your project, like this: https://github.com/barryvdh/laravel-cors

Resources