Method not allowed exception while updating a record - laravel

Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpExceptionNomessage
I'm getting this error while trying to update a record in the database. Don't know what's the problem. This question might be a duplicate but I've checked all and couldn't find the answer. Please Help me with this.
Controller Update Method:
public function updateEvent(Request $request, $id=''){
$name = $request->name;
$startdate = date_create($request->start_date);
$start_date = $startdate;
$time = $request->start_time;
$start_time = $time;//date("G:i", strtotime($time));
$endDate = date_create($request->end_date);
$end_date =$endDate;
$time_e = $request->end_time;
$end_time = $time_e;//date("G:i", strtotime($time_e));
$location = $request->location;
$description = $request->description;
$calendar_type = $request->calendar_type;
$timezone = $request->timezone;
if ($request->has('isFullDay')) {
$isFullDay = 1;
}else{
$isFullDay = 0;
}
DB::table('events')->where('id', $id)->update(
array(
'name' => $name,
'start_date' => $start_date,
'end_date' => $end_date,
'start_time' => $start_time,
'end_time' => $end_time,
'isFullDay' =>$isFullDay,
'description' => $description,
'calendar_type' => $calendar_type,
'timezone' => $timezone,
'location' => $location,
));
// Event Created and saved to the database
//now we will fetch this events id and store its reminder(if set) to the event_reminder table.
if(!empty($id))
{
if (!empty($request->reminder_type && $request->reminder_number && $request->reminder_duration)) {
DB::table('event_reminders')->where('id', $id)->update([
'event_id' => $id,
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
}
else{
DB::table('event_reminders')->insert([
'type' => $request->reminder_type,
'number'=> $request->reminder_number,
'duration' => $request->reminder_duration
]);
}
return redirect()->back();
}
Route:
Route::post('/event/update/{id}', 'EventTasksController#updateEvent');
Form attributes :
<form action="/event/update/{{$event->id}}" method="POST">
{{ method_field('PATCH')}}
i'm calling the same update function inside my calendar page and it working fine there. Don't know why it doesn't work here.

Check the routeing method.
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
patch should be the method called on route facade.

Change your route to patch:
Route::patch('/event/update/{id}', 'EventTasksController#updateEvent');
For your comment:
You can send the method to the ajax call by something like data-method attribute on the element you click on,take the method and use it in your ajax call. see this question/answer for help. How to get the data-id attribute?

Related

add multiple langue using Astrotomic / laravel-translatable package and laravel

i am new in laravel and use Astrotomic / laravel-translatable package for translation
i have problem when i want to add two langue at same time.
i have name_en,name_ar,discription_an,disriptionar as inputs fields.
i get this error Creating default object from empty value
so how can I solve my problem
this is link of package https://github.com/Astrotomic/laravel-translatable
// start add data
public function store(CategoryRequest $request)
{
// prepare data
$validatedData = array(
'url' => $request->url,
'slug' => $request->slug,
'status' => $request->status,
'last_updated_by' => auth('admin')->user()->id,
'created_by' => auth('admin')->user()->id,
'created' => time(),
);
$translated = array(
'name_en' => $request->name_en,
'name_ar' => $request->name_ar,
'description_en' => $request->description_en,
'description_ar' => $request->description_ar,
);
//start define categoru is sub or main
$request ->sub ==1 ? $validatedData['parent_id'] = $request ->category_id: $validatedData['parent_id']=null;
// start update data
DB::beginTransaction();
$add = Category::create($validatedData);
$id = $add->id;
// strat update category report
$categoryReport = CategoryReport::create(
['status' =>$validatedData['status'],
'category_id' =>$id,
'created_by' =>$validatedData['created_by']
,'last_updated_by' =>$validatedData['last_updated_by']]);
$add->translate('ar')->name = $translated['name_ar'];
$add->translate('en')->name = $translated['name_en'];
$add->translate('ar')->description = $translated['description_ar'];
$add->translate('en')->description =$translated['description_en'];
$add ->save();
DB::commit();
return redirect()->back()->with('success','تم اضافه البيانات بنجاح');
}

in laravel if condition not working in controller

i am trying to use if condition in controller ( IF IMAGE NOT UPLOADED it go to ELSE condition Or else go to IF ) but it was not working , it just redirecting registration from page when submitting a form
code
public function Enrollment(Request $request)
{
$this->validate($request, [
'name' => 'required|string|max:255',
'father_name' => 'required|string|max:225',
'address' => 'required|string|max:255',
'card_id' => 'required|string|max:255',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if ($request->image != '')
{
$input['name'] = strtoupper ($request['name']);
$input['father_name'] = strtoupper ($request['father_name']);
$input['address'] = strtoupper ($request['address']);
$input['card_id'] = strtoupper ($request['card_id']);
$input['image'] = time().'.'.$request->image->getClientOriginalExtension();
$folder1 = public_path('IMAGE/');
$path1 = $folder1 . $input['image']; // path 1
$request->image->move($folder1, $input['image']); // image saved in first folder
$path2 = public_path('IMAGE/BACKUP_IMAGE/') . $input['image']; // path 2
\File::copy($path1, $path2);
}else{
$input['name'] = strtoupper ($request['name']);
$input['father_name'] = strtoupper ($request['father_name']);
$input['address'] = strtoupper ($request['address']);
$input['card_id'] = strtoupper ($request['card_id']);
}
Card::create($input);
return back()->with('success','Enrolled Successfully.');
}
try this
if($request->hasfile('user_image'))
Nice that you use laravel. At first I will give you some hints to improve your code snippet.
You've written
it just redirecting registration from page when submitting a form
that's correct, because if you submit the form without an image, the validation will say "false".
You can't check an required in this way:
if ($request->image != '') {
because it's required.
Actually your code skips the validation at all, it would be better if you use the following:
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'father_name' => 'required|string|max:225',
'address' => 'required|string|max:255',
'card_id' => 'required|string|max:255',
'image' => 'required|image|mimes:jpeg,png,jpg',
]);
if ($validator->fails()) {
Session::flash('error', $validator->messages()->first());
return redirect()->back()->withInput();
}
If you dump your dd($validator); you will see all opertunities to validate the $request. Your errors you will find here: $validator->errors().
If something went wrong you should redirect back with the
->withInput()
so all data will stay in the form. Also possible with some explanation for the user ->withErrors():
// message information for the user
$messages = $validator->errors();
$messages->add('Your explanation');
// redirect
return redirect()->route('index')->withErrors($messages)->withInput();
Actually I am unsure why you save all $request in $input.
You can check https://laravel.com/docs/5.8/validation#using-rule-objects that for find an great solution for the strtoupper() usement.
Helpful links:
https://laravel.com/docs/5.8/validation
https://laravel.com/docs/5.8/session#flash-data

POST, Response and assertJson in phpunit testing

I have following test function to check the update data is correct or not.
It has no problem in updating.
My question is how to check the given parameters are correct after updated.
for example
if response.id == 1 and response.name = 'Mr.Smith'
assertcode = OK
else
assertcode = NG
public function user_update_info(){
$this->post('login',['email' => config('my-app.test_user'),
'password' => config('my-app.test_pass')]);
$response = $this->post('/update_info',[
'id' => 1,
'name' => 'Mr.Smith',
'post_code' => '142-4756',
'prefectural_code' => '15',
'address' => 'Merchat St.',]);
$response->assertStatus(200);
}
Assume your update_info route update User model.
Try below after your code,
$user = User::find(1);
static::assertTrue($user->id == 1 && $user->name = 'Mr.Smith');
To check if the response returns a json data you expect, you can use assertJson() method of the response object like so:
$response->assertJson([
'id' => 1,
'name' => 'Mr.Smith'
]);

How to pass array in POST API?

I'm trying to post booking content with array of passengers but it always return invalid argument supplied for foreach(). What seems to be the problem ?
public function postBooking(Request $request)
{
$user = JWTAuth::parseToken()->authenticate();
$booking = Booking::create([
'service_name' => $request->get('service_name'),
'service_package' => $request->get('service_package'),
'travel_date' => $request->get('travel_date'),
'travel_day' => $request->get('travel_day'),
'travel_time' => $request->get('travel_time'),
'remark' => $request->get('remark'),
'booking_name' => $request->get('booking_name'),
'mobile_number' => $request->get('mobile_number'),
'email' => $request->get('email'),
'nationality' => $request->get('nationality'),
'user_id' => $user->user_id,
]);
$passengers = $request['passengers'];
if(is_array($passengers))
{
foreach($passengers as $passenger)
{
$passenger = Passenger::create([
'passenger_name' => $passenger['passenger_name'],
'ic_passport' => $passenger['ic_passport'],
'booking_id' => $booking->booking_id
]);
}
}
$response = (object)[];
$response->booking = $booking->makeHidden('users');
$response->passengers = $passengers;
return response()->json(['data'=>$response, 'status'=>'ok']);
}
var_dump the $passengers, in my opinion ,the way u get the data from $request is wrong, u show use var_dump()or dd() to see the structure of $request and mostly u can solve the problem.

Laravel 4 - Return the id of the current insert

I have the following query
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
return $results;
}
How would i return the id of the row just inserted?
Cheers,
Instead of doing a raw query, why not create a model...
Call it Conversation, or whatever...
And then you can just do....
$result = Conversation::create(array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now ))->id;
Which will return an id...
Or if you're using Laravel 4, you can use the insertGetId method...In Laravel 3 its insert_get_id() I believe
$results = DB::table('pm_conversations')->insertGetId(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
This method requires that the id of the table be auto-incrementing, so watch out for that...
The last method, is that you can just return the last inserted mysql object....
Like so...
$result = DB::connection('mysql')->pdo->lastInsertId();
So if you choose that last road...
It'll go...
public static function createConversation( $toUserId )
{
$now = date('Y-m-d H:i:s');
$currentId = Auth::user()->id;
$results = DB::table('pm_conversations')->insert(
array( 'user_one' => $currentId, 'user_two' => $toUserId, 'ip' => Request::getClientIp(), 'time' => $now )
);
$theid= DB::connection('mysql')->pdo->lastInsertId();
return $theid;
}
I would personally choose the first method of creating an actual model. That way you can actually have objects of the item in question.
Then instead of creating a model and just save()....you calll YourModel::create() and that will return the id of the latest model creation
You can use DB::getPdo()->lastInsertId().
Using Eloquent you can do:
$new = Conversation();
$new->currentId = $currentId;
$new->toUserId = $toUserId;
$new->ip = Request::getClientIp();
$new->time = $now;
$new->save();
$the_id = $new->id; //the id of created row
The way I made it work was I ran an insert statement, then I returned the inserted row ID (This is from a self-learning project to for invoicing):
WorkOrder::create(array(
'cust_id' => $c_id,
'date' => Input::get('date'),
'invoice' => Input::get('invoice'),
'qty' => Input::get('qty'),
'description' => Input::get('description'),
'unit_price' => Input::get('unit_price'),
'line_total' => Input::get('line_total'),
'notes' => Input::get('notes'),
'total' => Input::get('total')
));
$w_id = WorkOrder::where('cust_id', '=', $c_id)->pluck('w_order_id');
return $w_id;

Resources