Laravel - Method Not Allowed HTTP Exception (RouteCollection.php line 218) - php

I'm currently new on Laravel and trying to develop my first project. I have this MethodNotAllowedHttpException in RouteCollection.php line 218 error during my development for inserting data into database. I have searched both Google & Stackoverflow for solutions but non are related to my current problem and some of them way too complex for this simple problem (I think so...).
I have my form in my checklist page:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-12">
<div class="text-left">
<input type="hidden" name="schmFK" value="{{$id}}">
<div class="col-sm-6">
<h4>
<label>Section</label>
<select class="selectpicker form-control" data-live-search="true" name="sctionPK">
<option selected>Select the Section</option>
#foreach ($sction as $key=>$slct1)
<option value="{{$slct1->ssctionPK}}">{{strtoupper($slct1->ssctionName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-2">
<button type="button" data-toggle="modal" data-target=".bs-example-modal-lg" class="btn btn-primary btn-sm" style="margin-top:33px; padding-top:7px; padding-bottom:7px;">Add Section</button>
</div>
<div class="col-sm-4">
<h4>
<label>Severity</label>
<select class="selectpicker form-control" name="svrityPK">
<option selected>Select the Severity</option>
#foreach ($svrity as $key=>$slct2)
<option value="{{$slct2->severityPK}}">{{strtoupper($slct2->severityName)}}</option>
#endforeach
</select>
</h4>
</div>
<div class="col-sm-12">
<h4>
<label>Question</label>
<input class="form-control" type="text" placeholder="Question" name="question">
</h4>
</div>
<div class="col-sm-6">
#include('widgets.button', array('class'=>'primary btnaddstd', 'size'=>'lg', 'type'=>'submit', 'value'=>'Add Checklist'))
</div>
</div>
</div>
</div>
</form>
Then I have this route for inserting data from the form into database:-
Route::post('/addchecklist', function (Request $request){
// Create instance to store record
$scheme = new App\checklists;
$scheme->schmFK = $request->schmFK;
$scheme->schSectionFK = $request->sctionPK;
$scheme->severityFK = $request->svrityPK;
$scheme->clQuestion = $request->question;
$scheme->save(); // save the input
// Sort all records descending to retrieve the newest added record
$input = App\checklists::orderBy('cklistPK','desc')->first();
// Set search field variable default value of null
$src = isset($src) ? $src : null;
// Get Checklist reference from cklists_stddetails with the designated ID
$chkstd = App\Cklists_stddetail::where('cklistFK', $input->cklistPK)
->join('stddetails', 'stdDtlFK', '=', 'stddetails.sdtlPK')
->get();
// Get the newest stored record
$chcklst = App\checklists::where('cklistPK', $input->cklistPK)->firstOrFail();
// Get all data from table 'stddetails'
$stddetail = App\stddetails::all();
// Get all data from table 'standards'
$stndrd = App\standard::all();
// Get all data from table 'sections'
$sction = App\Section::all();
// Redirect to 'addref.blade' page with the newest added record
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
My scenario is this, I have a form for user to input data in it. Then when the data is saved, they will be redirected to the page of that data to do something there. The data is successfully saved in the database but the redirection to the designated page (addref.blade) with the newest record ID return error:-
But the URL goes where I wanted it to go (means the URL is right):-
As you can see, the usual solution from the net that I found are:-
Make sure both method from routes and the form is the same, and mine it is:-
method="POST"
Route::post
Make sure the URL routes can recognize the form's action URL, and mine it is:-
<form action="{{url('addchecklist')}}" method="POST">
Route::post('/addchecklist', function (Request $request)
Include CSRF token field in the form, and mine it have been included:-
<form action="{{url('addchecklist')}}" method="POST">
{{ csrf_field() }}
I have tried those simple solution provided on the net and nothing is helpful enough. I'm still wondering what else I have missed and hoped that anyone here can assist on solving my issue.

I think the error is that you have a redirect which you have not registered in your routes or web.php file.
Sample redirect:
Route::post('/addchecklist', function (Request $request){
//some post process here...
return redirect('addref/'.$input->cklistPK)
->with('src', $src)
->with('chkstd', $chkstd)
->with('id',$input->cklistPK)
->with('schmid', $request->schmFK)
->with('chcklst', $chcklst)
->with('stddetail', $stddetail)
->with('stndrd', $stndrd)
->with('sction', $sction);
});
Route::get('addref/{id}', function(Request $request){
//show the blade.php with data
});

Can you please write :
url('/addchecklist')
instead of :
url('addchecklist')
and then print_r('in');
and die; and check what you get.
Route::post('/addchecklist', function (Request $request){
print_r('in');
die;
});

Related

How to solve the problem of getting unusual id in laravel

Here is my routes
Route::get('add-members/{id}','MemberController#create');
Route::post('save-member/{id}','MemberController#store');
This is my code to show the create form
public function create($id)
{
$team=Team::find($id);
$users = User::doesntHave('teams')->whereHas('roles', function($role) {
$role->where('name', 'member');
})->get();
return view('members.create',compact('users','team'));
}
An this is my code to store it
public function store(Request $request,$id)
{
$team=Team::find($id);
dd($request->id);
$team->users()->attach($request->id);
return redirect('home');
}
and this is my blade file
#extends('layouts.app')
#section('content')
<form action="{{url('save-member',$team->id)}}" method="post" accept-charset="utf-8">
#csrf
<div class="form-group row">
<label for="name" class="col-md-4 col-form-label text-md-right">{{ __('Select Member/s') }}</label>
<div class="col-md-6">
#foreach($users as $key => $user)
<input type="checkbox" name="id[]" value="{{$user->id}}">{{$user->email}}<br>
#endforeach
#error('member_id')
<span class="invalid-feedback" role="alert"><strong><font
color="red">{{ $message }}</font></strong></span>
#enderror
</div>
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
#endsection
Now when i select none of the user and just click save button it will save the the user id as 1. After i am doing dd($request->id) it will show me the output 1. But in my form there is no users left or my form is empty.So where from 1 is coming. you can see this picture for clearify.
Please help me to solve this problems
You should be more specific with what data you are requesting from the Request:
$request->id; // could be an input named 'id' or a route parameter named 'id'
$request->input('id'); // is an input
$request->route('id'); // is a route parameter
You are running into a situation where you have a route parameter named id and potentially an input named id. Using the dynamic property of the Request, $request->id, will return the input id if it is there, if not it falls back to returning a route parameter named id.
Here is an article from the past that shows the issue with not being specific about what you are trying to get from the Request object:
asklagbox - blog - watch out for request

laravel update without passing ID

I am working on a ticket log where tickets get edited multiple times before they are 'done'.
I have an overview where you see all the tickets, on top of the page are 6 buttons. All buttons open a popup with a form. The first button is a create function which makes the ticket and fills in the first information. All other fields are now NULL. The second buttons is the first edit button.
Upon opening it opens an form where the user scans a barcode to fill in the first field; Ticket Number. this ticket number is unique for every Ticket. Next thing to fill in is your credentials, which come from a dropdown.
Due to the fact that all the edit forms work by Ticket_number (which is scanned from a QR code) I made it so all forms are on the same page. Therefor I am not able to do something like : action="{{ route('countries.update',$country->id) }} as I don't know the ID at this moment.
Here is the code behind everything(and you can see what I tried there too):
web.php:
// TICKET LOG ROUTES
Route::post('ticket/start-picking', 'TicketController#startpicking')->name('tickets.startpicking');
Route::resource('tickets', 'TicketController');
form for edit:
<div id="modal-start-picking" class="modal">
<form method="POST" id="modal-start-picking-form" action="{{ route('tickets.startpicking') }}">
#csrf
<input type="text" value="modal-start-picking" name="type" hidden>
<div class="modal-content">
<h4>Start Picking</h4>
<p>Scan Ticket Number here</p>
<div class="input-field">
<label for="start">Ticket Number</label>
<input type="text" name="ticket_number" id="start" autofocus>
</div>
<div class="input-field">
<select id="picker" name="picker">
<option value="" disabled selected>Choose a Picker</option>
#foreach($employees as $employee)
<option {{(old('picker') == $employee->initials ) ? 'selected' : ''}} value="{{ $employee->initials }}">{{ $employee->initials }}</option>
#endforeach
</select>
</div>
</div>
<div class="modal-footer">
<input class="btn-flat" type="submit" value="Start Picking">
</div>
</form>
</div>
Function in TicketController:
public function startpicking(Request $request, Ticket $ticket)
{
$request->validate([
'picker' => 'required',
]);
$ticket->update(array_merge($request->all(), ['picker_start_time' => Carbon::now()]));
return redirect()->route('tickets.index')->with('toast', 'Ticket updated successfully');
}
If any more info is required I Will gladly update my post.
I found out how it's done.
$request->validate([
'picker' => 'required',
]);
Ticket::where('ticket_number', $posted_ticket_number)->update([
'picker' => $request->picker,
'picker_start_time' => Carbon::now(),
]);
You just have to use ::where('column', 'variable').
The variable was pulled from my form (The Ticket number in my case. As this was an unique identifier.) and the column is self explanatory.

how to update database using laravel controller? MethodNotAllowedHttpException No message error message

I'm trying to update my database using a form on my
edit.blade.php page as shown below. The edit part works correctly as the fields are filled in in the form as expected, however when i try to save, an error message of
Symfony \ Component \ HttpKernel \ Exception \ MethodNotAllowedHttpException
No message
is displayed. I have tried so many ways on how to fix it and I'm not sure where I'm going wrong. Hopefully it's something simple to fix?
edit.blade.php
#extends('layouts.app')
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<form method="post" action="{{ action('PostsController#update', $id) }}">
{{ csrf_field() }}
<input type="hidden" name="_method" value="PATCH" />
<h1>Edit Item</h1>
<div class="form-group">
<label for="item">Item:</label>
<input type="text" id="item" name="item" value="{{$post->item}}" class="form-control" required>
</div>
<div class="form-group">
<label for="weight">Weight (g):</label>
<input type="number" id="weight" value="{{$post->weight}}" name="weight" class="form-control">
</div>
<div class="form-group">
<label for="noofservings">No of Servings:</label>
<input type="number" id="noofservings" value="{{$post->noofservings}}" name="noofservings" class="form-control">
</div>
<div class="form-group">
<label for="calories">Calories (kcal):</label>
<input type="number" id="calories" name="calories" value="{{$post->calories}}" class="form-control">
</div>
<div class="form-group">
<label for="fat">Fat (g):</label>
<input type="number" id="fat" name="fat" value="{{$post->fat}}" class="form-control">
</div>
<button type="submit" class="btn btn-primary">Save</button>
</form>
</div>
</div>
</div>
#endsection
PostsController.php
<?php
public function update(Request $request, $id)
{
$this->validate('$request', [
'item' => 'required'
]);
$post = Post::find($id);
$post->item = $request->input('item');
$post->weight = $request->input('weight');
$post->noofservings = $request->input('noofservings');
$post->calories = $request->input('calories');
$post->fat = $request->input('fat');
$post->save();
return redirect('/foodlog');
}
web.php
<?php
Route::get('edit/{id}', 'PostsController#edit');
Route::put('/edit', 'PostsController#update');
Post.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $fillable = [
'id',
'user_id',
'item',
'weight',
'noofservings',
'calories',
'fat',
'created_at'
];
}
My website is a food log application and this function is so that they can edit their log.
Any help is greatly appreciated!
Based on Michael Czechowski I edited my answer to make this answer better, The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second problem is , the form method field is 'patch' and your route method is 'put'.
The difference between 'patch' and 'put' is:
put: gets the data and update the row and makes a new row in the database from the data that you want to update.
patch: just updates the row and it does not make a new row.
so if you want to just update the old row change the route method to patch.
or if you really want to put the data, just change the put method field in your form.
simply by : {{method_field('PUT')}}
Remember, the form's and the route's methods must be same. If the form's method is put, the route method must be put; and vice-versa.
The main problem is inside your routes:
Route::put('/edit/{id}', 'PostsController#update');
You have to add the id inside your route parameters either. Your update() function needs two parameters, first the form parameters from the formular and second the $id of the edited log entry.
The second one is inside your HTML template:
<input type="hidden" name="_method" value="PUT" />
To hit the right route you have to add the corresponding method to your route Route::put('/edit/{id}', 'PostsController#update');.
A possible last problem
<form method="post" action="{{ action('PostsController#update', $post->id) }}">
I am not sure how your template works, but $id is possible not set inside your template. Maybe try to specify the ID depending on your post. Just to make it sure the ID comes from the shown post.
Further suggestions
Best practice is to use the symfony built-in FormBuilder. This would make it easier to target those special requests like PUT, PATCH, OPTIONS, DELETE etc.

codeigniter get data by selection of dropdown

How to get data by selecting the drop-down in CodeIgniter.
Below is my code it does not work. The below code is not working properly when I selecting an option in the drop down and when I submit page appearing empty. when click please help me to get data. I am doing it in CodeIgniter. I want to get data from the database . I think the code is perfect am new to CodeIgniter the below code is not working properly the page appearing empty when click please help me to get data. I am doing it in CodeIgniter. I want to get data from the database . I think the code is perfect am new to CodeIgniter.
view:
<?php echo form_open('super_admin/believers_controller/view_believerr/' , array('class' => 'form-horizontal validatable', 'enctype' => 'multipart/form-data') ); ?>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> District Id</label>
<div class="col-sm-9">
<select name="report_type" >
<option >Select Id</option>
<option value="believers">Believers</option>
<option value="staff">staff</option>
<option value="staff">committe members</option>
</select>
</div>
</div>
<div class="clearfix form-actions">
<div class="col-md-offset-3 col-md-9">
<input type="submit" name="Submit" class="btn btn-info" >
controller:
<?php
function view_believerr()
{
$report_type = $this->input->get('report_type');
if($report_type=='believers'){
$this->load->model('believers/believers_model');
$page_data['h']=$this->believers_model->view_believer();
$page_data['page_name'] = 'believers/view_believer';
$this->load->view('index', $page_data);
}
}
?>
model:
<?php
function view_believer()
{
$query = $this->db->get('tbl_believers');
return $query;
}
?>
I want to get data from database . I think the code is perfect am new to codeigniter the below code is not working properly the page appearing empty when click please help me to get data. I am doing it in codeigniter. I want to get data from database . I think the code is perfect am new to codeignite
Use $this->input->post('report_type');

deleting loan row in database after returning book

I am making a loan system for books and I have a profile page that displays the loans you have taken out, underneath each one is a button that takes you to a form where you fill out the condition of the book, under that is another button that will send the data to a returns table in my database, I want to delete the loan in the loan table because if not then the loan keeps displaying in the profile page and the user can return the same book as many times as they want. any help would be greatly appreciated.
thanks.
profile.blade.php
<?php
use App\Requests;
use App\Loan;
$request = Requests::where('userid', auth()->user()->userid)->get();
?>
#extends('layouts.app')
#section('content')
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1>Profile: {{ Auth::user()->f_name }}</h1></div>
<div class="panel-body">
<div class="container">
<h3>Requests</h3>
#foreach ($request as $request)
<ul>
<h4>Title: {{$request->r_title}}</h4>
<h4>Author: {{$request->r_author}}</h4>
<h4>Year: {{$request->r_year}}</h4>
<h4>Condition: {{$request->r_condition}}</h4>
<br/>
</ul>
#endforeach
</div>
<div class="container">
<h3>Loans</h3>
#foreach ($loan as $loan)
<ul>
<h4>Title: {{$loan->title}}</h4>
<h4>Start Date: {{$loan->startdate}}</h4>
<h4>Due Date: {{$loan->duedate}}</h4>
<br/>
<form action="{{url('returnform/'.$loan->loanid)}}" method="GET">
<input type="submit" name="returnbtn" value="returnform">
</form>
</ul>
#endforeach
</div>
</div>
</div>
</div>
#endsection
returnform.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1>Return Book</h1></div>
<div class="panel-body">
<form action="{{url('returns')}}" method="POST">
{{ csrf_field() }}
<div>
<input type="hidden" name="lid" value="{{$loan->loanid}}" id="lid">
<input type="hidden" name="re_bookid" value="{{$loan->bookid}}" id="re_bookid">
<input type="hidden" name="re_title" value="{{$loan->title}}" id="re_title">
<input type="hidden" name="re_ddate" value="{{$loan->duedate}}" id="re_ddate">
</div>
<div>
<label for="title"><h4>Enter the books condition: </h4></label>
<select name ="re_condition" value="{{old('condition')}}">
<option value="mint">Mint</option>
<option value="good">Good</option>
<option value="fair">Fair</option>
<option value="poor">Poor</option>
</select>
</div>
<input type="submit" name="btn" value="returns">
</form>
</div>
</div>
</div>
#endsection
BookController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Book;
use App\Returns;
use App\Requests;
use App\Loan;
use Carbon\Carbon;
class BookController extends Controller
{
......
function returnform($loanid)
{
$loan = Loan::find($loanid);
return view('book/returnform',['loan' => $loan]);
}
function returns(Request $request, $loanid)
{
$return = new Returns();
$return->userid = auth()->user()->userid;
$return->f_name = auth()->user()->f_name;
$return->l_name = auth()->user()->l_name;
$return->bookid = $request->re_bookid;
$return->title=$request->re_title;
$return->condition=$request->re_condition;
$return->returndate= Carbon::now();
$return->duedate=$request->re_ddate;
$return->save();
return redirect('profile');
}
routes
....
Route::get('returnform/{loanid}', 'BookController#returnform');
Route::post('returns', 'BookController#returns');
To delete a row in a table use the following code
function deletereturns(Request $request, $loanid) {
$return = Return::find($loanid);
$return->delete();
// return to some place
}
Add a route and its done.
But i suggest you to create a new column in the table with boolean and set default false.
Each time a user tries to delete a loan just change false to true.
When you list the loan use a where conditions to exclude all the deleted ones.
This helps you to know who all deleted the loans, which may help in any way
The $loanid parameter won't work in your method since you don't pass any value to it. You are however setting the loan id in a hidden form field. So do this to delete the loan using the loan id.
Loan::destroy($request->lid);
You should also add some check when a user returns the book. Check if the loan with the loan id exists and perform a check to see if the logged in user and the loaned user match. Because with your code right now, any user can return a book loaned by any other user.

Categories