MethodNotAllowedHttpException in laravel-5.6 - php

I am trying to submit the form with method 'POSt' but getting MethodNotAllowedHttpException I know some possible reason for getting this error and also searched on the internet for a possible solution. My project's all other forms are working fine except this one. I am not finding the reason why I am getting this common error. Would someone help me please to find out the solution?
form
<form action="{{ url('admin/checkout') }}" method="POST">
#csrf
<div class="row">
<div class="col-sm-6 offset-sm-3">
<label class="m-t-20">Now time</label>
<div class="input-group">
<input name="outtime" class="form-control" id="single-input" value="" placeholder="Now" required>
<span class="input-group-btn">
<button type="submit" id="check-minutes" class="btn waves-effect waves-light btn-warning">Check Out</button>
</span>
#if ($errors->has('outtime'))
<small class="error">{{ $errors->first('outtime') }}</small>
#endif
</div>
</div>
</div>
<br>
<table id="flow-table" class="display nowrap mytable" cellspacing="0" width="100%">
<thead>
<tr>
<th style="width: 15px;">#</th>
<th class="check">
<div class="checkbox">
<label>
<input type="checkbox" id="flowcheckall" />
<i class="input-helper"></i>
<span><strong> All</strong></span>
</label>
</div>
</th>
<th class="text-left">Name</th>
<th>Cord No</th>
<th>Section</th>
<th>Designation</th>
</tr>
</thead>
<tbody>
#forelse($employees as $employee)
<tr class="text-center">
<td>{{ $loop->index + 1 }}</td>
<td style="max-width: 30px;">
<div class="checkbox text-center">
<label>
<input type="checkbox" name="employee_id[]" class="check" id="checkall" value="{{ $employee->employee_id }}" />
<i class="input-helper"></i>
</label>
</div>
</td>
<td class="text-left">{{ $employee->name }}</td>
<td>{{ $employee->card_no }}</td>
<td>{{ ucwords($employee->section) }}</td>
<td>{{ ucwords($employee->designation) }}</td>
</tr>
#empty
#endforelse
</tbody>
</table>
</form>
web.php
#Admin Routes
Route::get('admin', 'Admin\LoginController#showLoginForm')->name('admin.login');
Route::post('admin', 'Admin\LoginController#login');
Route::post('admin-password/email', 'Admin\ForgotPasswordController#sendResetLinkEmail')->name('admin.password.email');
Route::get('admin-password/reset', 'Admin\ForgotPasswordController#showLinkRequestForm')->name('admin.password.request');
Route::post('admin-password/reset', 'Admin\ResetPasswordController#reset');
Route::get('admin-password/reset/{token}', 'Admin\ResetPasswordController#showResetForm')->name('admin.password.reset');
Route::group(['prefix' => 'admin', 'middleware' => ['auth:admin'], 'as' => 'admin.'], function () {
# Dashboard / Index
Route::get('home', array('as' => 'home','uses' => 'Admin\AdminController#index'));
Route::get('change-password', array('as' => 'change-password','uses' => 'Admin\AdminController#changePassword'));
Route::put('change-password', array('as' => 'change-password','uses' => 'Admin\AdminController#updatePassword'));
// HR (Section)
Route::resource('section', 'Admin\HR\SectionController');
// HR (Designation)
Route::resource('designation', 'Admin\HR\DesignationController');
// HR (Salary Grade)
Route::resource('salary-grade', 'Admin\HR\SalaryGradeController');
// HR (Employee)
Route::resource('employees', 'Admin\HR\EmployeeController');
//HR (Employee cv download)
Route::get('cv-download/{id}', 'Admin\HR\EmployeeController#cvDownload');
// HR (Attendance)
Route::resource('attendances', 'Admin\HR\AttendanceController');
Route::post('attendances/searched-employees', 'Admin\HR\AttendanceController#searchedEmployees');
Route::get('today-checked-in', array('as' => 'today-checked-in', 'uses' => 'Admin\HR\AttendanceController#checkedIn'));
Route::post('checkout', 'Admin\HR\AttendanceController#checkout');
//HR (Leave Type)
Route::resource('leave-types', 'Admin\HR\LeaveTypeController');
//HR (Leave Application)
Route::resource('leave-application', 'Admin\HR\LeaveApplicationController');
Route::post('leave-application/searched-employees', 'Admin\HR\LeaveApplicationController#searchedEmployees');
Route::get('leave-application/{id}/create', 'Admin\HR\LeaveApplicationController#create');
Route::get('leave-application-download/{id}', 'Admin\HR\LeaveApplicationController#applicationDownload');
//HR (Holidays)
Route::resource('holidays', 'Admin\HR\HolidayController');
//HR (Promotions)
Route::resource('promotions', 'Admin\HR\PromotionController');
Route::get('promotions/{id}/create', 'Admin\HR\PromotionController#create');
Route::post('promotions/searched-employees', 'Admin\HR\PromotionController#searchedEmployees');
Route::get('promotions/update/{id}', 'Admin\HR\PromotionController#');
//HR (Payroll Provident Fund)
Route::resource('provident-fund', 'Admin\HR\ProvidentFundController');
Route::post('provident-fund/searched-employees', 'Admin\HR\ProvidentFundController#searchedEmployees');
Route::get('provident-fund/{id}/create', 'Admin\HR\ProvidentFundController#create');
//HR (Payroll Advance Salary)
Route::resource('advance-salary', 'Admin\HR\AdvanceSalaryController');
Route::post('advance-salary/searched-employees', 'Admin\HR\AdvanceSalaryController#searchedEmployees');
Route::get('advance-salary/{id}/create', 'Admin\HR\AdvanceSalaryController#create');
//HR (Payroll-Salary)
Route::group(['prefix' => 'salary', 'as' => 'salary.'], function () {
//make salary
Route::get('make-salary', array('as' => 'make-salary', 'uses' => 'Admin\HR\SalaryController#makeSalaryIndex'));
Route::post('make-salary-employees-list', array('as' => 'make-salary-employees-list', 'uses' => 'Admin\HR\SalaryController#getMakeSalaryEmployeeList'));
Route::post('make-salary-save/{id}', array('as' => 'make-salary-save', 'uses' => 'Admin\HR\SalaryController#makeSalarySave'));
//make payment
Route::get('make-payment', array('as' => 'make-payment', 'uses' => 'Admin\HR\SalaryController#makePaymentSearch'));
Route::post('make-payment-employees-list', array('as' => 'make-payment-employees-list', 'uses' => 'Admin\HR\SalaryController#getMakePaymentEmployeeList'));
Route::get('employee/{id}', array('as' => 'employee', 'uses' => 'Admin\HR\SalaryController#makeEmployeeSalary'));
Route::put('change-payment-status/{id}', array('as' => 'change-payment-status', 'uses' => 'Admin\HR\SalaryController#changePaymentStatus'));
//generate payslip
Route::get('payslip', array('as' => 'payslip', 'uses' => 'Admin\HR\SalaryController#generatePayslip'));
Route::post('payslip-search', array('as' => 'payslip-search', 'uses' => 'Admin\HR\SalaryController#payslipSearch'));
});
/*Accounts Part*/
//Accounts (Groups)
Route::resource('groups', 'Admin\Accounts\GroupController');
//Accounts (Groups)
Route::resource('companies', 'Admin\Accounts\CompanyController');
//Accounts (Customers)
Route::resource('customers', 'Admin\Accounts\CustomerController');
//Accounts (Suppliers)
Route::resource('suppliers', 'Admin\Accounts\SupplierController');
});
AttendanceController.php
/**
*
*checkout
**/
public function checkout(Request $request)
{
return $request->all();
}

try this
Route::post('checkout', 'Admin\HR\AttendanceController#checkout')->name('checkout');
<form action="{{ route('admin.checkout') }}" method="POST">

Create a route in web.php file
Route::get('/', 'LoginController#index');
In Controller add
public function index(){
$postHeader = Request::header(); // HEADER Data
$postData = Request::all();
if(!empty($postData)){
echo'<pre>';print_r($postData); die;
}
}
Do not forget to add crf token in your View
<form name="" action="login" method="POST">
{{ csrf_field() }}

Related

Form refuses to add first entry to cart and remove first entry from cart in Laravel

After redownloading my laravel project to my new pc from github, I got a new bug that didn't have before. The first entry of my shopping cart and of my products page can not go throught the assigned route given, but the rest of the entries work perfectly fine. I couldn't really find anything that resembled my problem in other questions.
This is the error message:
I have tried to substitute the Route::post with Route::match(['get', 'post'], which solved the error, but had as a result that I couldn't add the first entry to the cart.
These are my routes before and after exchanging:
Route::get('/login', [LoginController::class, 'index'])->name('login');
Route::post('/login/authenticate', [LoginController::class, 'authenticate'])->name('auth');
Route::get('/home', [PageController::class, 'home'])->name('home')->middleware('checklogin');
Route::get('/products', [PageController::class, 'products'])->name('product')->middleware('checklogin');
Route::get('/logout', [LoginController::class, 'logout'])->name('logout');
Route::post('/products/addproduct', [OrderController::class, 'addToCart'])->name('addtocart')->middleware('checklogin');
Route::post('/products/removeproduct', [OrderController::class, 'removeFromCart'])->name('removefromcart')->middleware('checklogin');
Route::get('/order', [PageController::class, 'order'])->name('order')->middleware('checklogin');
Route::post('/order/buy', [OrderController::class, 'payment'])->name('pay')->middleware('checklogin');
Route::get('/orderhistory', function(){return view('orderHistory');})->name('orderhistory')->middleware('checklogin');
Route::get('/products/details/{product}', [ProductDetailController::class, 'getProductPage'])->name('productdetail')->middleware('checklogin');
Route::get('/login', [LoginController::class, 'index'])->name('login');
Route::match(['get', 'post'], '/login/authenticate', [LoginController::class, 'authenticate'])->name('auth');
Route::get('/home', [PageController::class, 'home'])->name('home')->middleware('checklogin');
Route::match(['get', 'post'], '/products', [PageController::class, 'products'])->name('product')->middleware('checklogin');
Route::get('/logout', [LoginController::class, 'logout'])->name('logout');
Route::match(['get', 'post'], '/products/addproduct', [OrderController::class, 'addToCart'])->name('addtocart')->middleware('checklogin');
Route::match(['get', 'post'], '/products/removeproduct', [OrderController::class, 'removeFromCart'])->name('removefromcart')->middleware('checklogin');
Route::match(['get', 'post'], '/order', [PageController::class, 'order'])->name('order')->middleware('checklogin');
Route::match(['get', 'post'], '/order/buy', [OrderController::class, 'payment'])->name('pay')->middleware('checklogin');
Route::get('/orderhistory', function(){return view('orderHistory');})->name('orderhistory')->middleware('checklogin');
Route::get('/products/details/{product}', [ProductDetailController::class, 'getProductPage'])->name('productdetail')->middleware('checklogin');
This is the form I use to send the data to the route.
<div class="card-deck row">
#foreach (ProductController::getProduct() as $product)
#if($product->quantity > 0)
<div class="col-md-4 col-sm-12 my-3">
<div class="card h-100 mx-2" style="width: 18rem;margin-bottom: -1em">
<form action="{{ route('addtocart') }}" method="post">
#csrf
<a href="products/details/{{$product->id}}" class="" style="text-decoration: none; color: inherit;">
<div class="card-body d-flex flex-column">
<input type="hidden" name="productId" value="{{$product->id}}">
<h5 class="card-title" name="product">{{$product->name}}</h5>
<p class="card-text" name="description">{{$product->description}}</p>
</div>
</a>
<ul class="list-group list-group-flush">
<li class="list-group-item">
#if(count($product->categories) < 1)
No relevant categories found.
#else
#foreach ($product->categories as $category)
{{$category->name}}
#endforeach
#endif
</li>
</ul>
<div class="card-footer mt-auto">
<div class="input-group mb-3">
<input class="form-control" aria-describedby="basic-addon1" type="number" name="quantity" value="1" min="1" max="{{$product->quantity}}">
<div class="input-group-append">
<input class="btn btn-outline-secondary" type="submit" value="Buy">
</div>
</div>
</div>
</form>
</div>
</div>
#endif
#endforeach
</div>
I have also no idea if this has anything to do with the function i use to add to or remove from the cart.
This is the function used to add the product to the cart and remove from the cart:
public function addToCart(Request $request){
$orderInfo = $this->getOrderInfo();
if($orderInfo === null){
$orderInfo = Order::create([
'customer_id' => Auth::user()->id,
'order_status' => 0
]);
}
if(Product::find($request->post('productId'))->quantity >= $request->post('quantity')){
if($orderInfo->products->contains($request->post('productId')) === true){
$orderInfo->products()->increment('order_quantity', $request->post('quantity'));
}else{
$orderInfo->products()->attach($request->post('productId'), ['order_quantity' => $request->post('quantity')]);
}
Product::where('id', $request->post('productId'))->decrement('quantity', $request->post('quantity'));
return redirect(route('product'));
}else{
return "Product not in Stock";
}
}
public function removeFromCart(Request $request){
$orderInfo = $this->getOrderInfo();
$orderQuantity = 0;
foreach($orderInfo->products as $order){
$orderQuantity = $order->pivot->order_quantity;
}
$orderInfo->products()->detach($request->post('delete'));
Product::where('id', $request->post('delete'))->increment('quantity', $orderQuantity);
return redirect(route('order'));
}
After leaving this problem for what it is for a while, I came back to it to find out that the error code I had no longer appears and that everything works fine and as it should. I don't know what the problem was, nor do I know how it fixed itself.
EDIT
The error was caused by an unclosed <form> tag in the navbar of the project. After closing it off it resolved any route related error messages.

How to call controller's update function

I am trying to use controller's update function on my dashboard.blade.php page, but when I press on "Save" it switches to show.blade.php page instead of updating.
My dashboard.blade.php page:
#if(count($posts) > 0 )
<table class="table table-striped">
<tr>
<th>Title</th>
<th>Body</th>
<th>Employee Number</th>
<th>Edit</th>
<th>Save</th>
</tr>
#foreach($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td><input type='text' name='body'class='form-control' value='{{$post->body}}'></td>
<td>{{$post->employee_no}}</td>
<td><a href="{{ action("PostsController#update", $post->id) }}" >Save</a></td>
<td>Edit</td>
</tr>
#endforeach
</table>
#else
<p>You Have No Posts</p>
#endif
My update function on PostsController.php page:
public function update(Request $request, $id)
{
$this->validate($request,[
//'title' => 'required',
'body' => 'required'
]);
//Update Post
$post = Post::find($id);
//$post->title = $request->input('title');
$post->body = $request->input('body');
$post->save();
return redirect('/posts')->with('success','Post Updated');
}
I read that "action" will go to the first route that matches the pattern, but I do not know how to solve this problem.
My web.php page:
Route::get('/', 'PagesController#index');
Route::get('/about', 'PagesController#about');
Route::get('/services', 'PagesController#services');
Route::resource('posts','PostsController');
Auth::routes();
Route::get('/dashboard', 'DashboardController#index');
How can I call the update function correctly from dashboard.blade.php page?
To update data you have to use form with put method.
and route will be like this,
Route::put('dashboard/update/{id}',[
'uses' => 'DashboardController#update',
'as' => 'dashboard.update'
]);
For more Laravel Routing
Hope it helps :)
You can solve this by using form submit with hidden PUT method.
<form action="{{ url('customers') }}/{{$data['customer']->id}}" method="POST">
<input type="hidden" name="_method" value="PUT">
#csrf
</form>
How about having a simple form for each row in the table :
#if(count($posts) > 0 )
<table class="table table-striped">
<tr>
<th>Title</th>
<th>Body</th>
<th>Employee Number</th>
<th>Edit</th>
<th>Save</th>
</tr>
#foreach($posts as $post)
<tr>
<td>{{$post->title}}</td>
<td>{{$post->employee_no}}</td>
<td>
<!-- Form for each row -->
<form action="{{ route("posts.update", [ 'post' => $post->id ]) }}" method="POST">
#method('PUT')
#csrf
<input type='text' name='body'class='form-control' value='{{$post->body}}'></td>
<button type="submit">Save</button>
</form>
<!-- Form for each row -->
<td>Edit</td>
</tr>
#endforeach
</table>
#else
<p>You Have No Posts</p>
#endif

How to incremented in table on button click laravel

I have Home.blade.php in which if I click vote button it should increment the count in candidate table.
home.blade.php
#foreach ($file as $show)
<div class="col-md-3" style="margin-bottom: 20px;">
<div class="card">
<img src="{{$show->image}}" style="width:100%">
<div class="card-body">
<h5 class="title">President</h5>
<p class="card-text">Name : {{$show->name}}</p>
<button>VOTE</button>
</div>
</div>
</div>
#endforeach
homecontroller
public function Count(){
DB::table('candidate')->increment('count');
return view('/home')->with('success', 'voted');
}
Route
Route::get('/home','Homecontroller#Count');
Please help me to increment the count, if not this method is there any other method to do the same.
Yes, there is a better way.
Add this to Your web.php
Route::put('/votesUp/{vote}', 'HomeController#upVote')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'HomeController#downVote')->name('votes.downVote');
in your view list thats is index.blade.php add this two buttons
FORM BUILDER WAY
#foreach($candidates as $item)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{!! $item->name !!}</td>
<td>{!! Form::model($item, ['method' => 'PUT', 'route' => ['votes.upVote', $item->id ] ,'enctype'=>'multipart/form-data' ]) !!}
{!! Form::submit( 'Up Vote', ['class' => '', 'name' => 'submitbutton', 'value' => 'upvote'])!!}
{!! Form::close() !!}</td>
<td>{!! Form::model($item, ['method' => 'PUT', 'route' => ['votes.downVote', $item->id ] ,'enctype'=>'multipart/form-data' ]) !!}
{!! Form::submit( 'Down Vote', ['class' => '', 'name' => 'submitbutton', 'value' => 'upvote'])!!}
{!! Form::close() !!}</td>
</tr>
#endforeach
HTML WAY
#foreach($candidates as $item)
<tr>
<td>{{ $loop->iteration }}</td>
<td>{!! $item->name !!}</td>
<td>
<form method="post" action="{{ route('votes.upVote', $item->id) }}">
#method('PUT')
#csrf
<input class="" name="submitbutton" value="Up Vote" type="submit">
</form>
<form method="post" action="{{ route('votes.downVote', $item->id) }}">
#method('PUT')
#csrf
<input class="" name="submitbutton" value="Down Vote" type="submit">
</form>
</td>
</tr>
#endforeach
I am Considering Your model as Candidate so add this to HomeController
ELOQUENT way
public function upVote(Request $request, $id)
{
Candidate::find($id)->increment('votes_count', 1);
return redirect()->back();
}
public function downVote(Request $request, $id)
{
Candidate::find($id)->decrement('votes_count', 1);
return redirect()->back();
}
DB Facade Way
public function upVote(Request $request, $id)
{
\DB::table('candidates')->where('id','=',1)->increment('votes_count', 1);
return redirect()->back();
}
public function downVote(Request $request, $id)
{
\DB::table('candidates')->where('id','=',1)->decrement('votes_count', 1);
return redirect()->back();
}
Explained:
When You click on the upvote button filed votes_count in candidates table will be
incremented by 1
When You click on the downvote button filed votes_count in candidates table will be decremented by 1
EDIT FOR undefined variable candidate
Find this line
#foreach($candidates as $item)
And Replace with
#foreach ($file as $item)
FIX FOR
Class App\Http\Controllers\HomeController does not exist
From
Route::put('/votesUp/{vote}', 'HomeController#upVote')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'HomeController#downVote')->name('votes.downVote');
TO
Route::put('/votesUp/{vote}', 'Homecontroller#upVote')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'Homecontroller#downVote')->name('votes.downVote');
Your Controller Class
Homecontroller
but i have wrongly written as
HomeController
Make sure your column count is integer type in migration
And:
You are writing it in wrong way
<button>VOTE</button>
change it to
<button>VOTE</button>
The vote button should be like this:
<button>VOTE</button>
With the functionalities like Upvote and Downvote as answered nicely by #manojkiran-a above, I would also add throttling. Now a days it is easy to create a bot which will send upvote requests even when you are using csrf token.
I would add :
'middleware' => 'throttle:5'
Which will allow only 5 requests per minute per IP address. Not entirely preventing it but making it little harder.
Route::put('/votesUp/{vote}', 'Homecontroller#upVote')->middleware('throttle:5')->name('votes.upVote');
Route::put('/votesDown/{vote}', 'Homecontroller#downVote')->middleware('throttle:5')->name('votes.downVote');

Adding Data to the multiple column in laravel 5.7

Hi I am working on a project and I need to do some addition while working on a table.
like I have to fill the three fields and change the status to 2 using checkbox Array. I tried it all but with no luck. Kindly look into it and Let me know the changes I can Do.
My Model CustomerLoad.php is
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CustomerLoad extends Model
{
protected $fillable = [
'driver_id',
'vehicle_id',
'company_id',
'customer_id',
'package_type',
'from',
'to',
'in_mile',
'weight',
'height',
'width',
'length',
'rate',
'duration_text',
'ticket_number',
'status_id'
];
public function status()
{
return $this->belongsTo('App\Status');
}
}
My Controller for creating the page is Like this
public function create()
{
$csloads = CustomerLoad::paginate(4);
$driver = Driver::pluck('name', 'id')->all();
$vehicle = Vehicle::pluck('vin', 'id')->all();
$company = Company::pluck('name', 'id')->all();
return view('customerload.create', compact('csloads', 'driver', 'vehicle', 'company'));
}
for storing it
public function updatecsloads(Request $request)
{
if(isset($request->update_all) && !empty($request->checkBoxArray)){
$csloads = CustomerLoad::findOrFail($request->checkBoxArray);
foreach($csloads as $csload){
$input = $request->all();
dd($input);
// $csload->update($input);
}
// return redirect()->back();
// } else {
// return redirect()->back();
}
}
My View is like
<div class="card">
<div class="card-header card-header-rose card-header-text">
<div class="card-ttle">
<h4 class="card-text">Allocate Loads</h4>
</div>
</div>
<div class="card-body">
{!! Form::model(['method' => 'PATCH', 'action' => ['CustomerLoadsController#updatecsloads']]) !!}
<div class='form-group'>
{!! Form::select('checkBoxArray', ['' => 'Allocate'], null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>''])!!}
</div>
<div class='form-group'>
{!! Form::submit('Allocate Loads', ['class'=>'btn btn-rose pull-right']) !!}
</div>
#if(count($csloads) > 0)
<div class="table-responsive">
<table class="table">
<thead>
<tr>
<th>ID</th>
<th><input type="checkbox" id="options"></th>
<th>Driver Name</th>
<th>Company Name</th>
<th>Vehicle Vin Number</th>
<th>Origin</th>
<th>Destination</th>
<th>Package Type</th>
<th>Dimensions</th>
<th>Weight</th>
</tr>
</thead>
<tbody>
#foreach($csloads as $csload)
#if($csload->status_id == 1)
<tr>
<td>{‌{$csload->id}}</td>
<td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]" value="{‌{$csload->status ? $csload->status->id == 2 : $csload->status->id == 1}}"></td>
<td>{!! Form::select('driver_id', ['' => 'Choose Driver Name'] + $driver, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{!! Form::select('company_id', ['' => 'Choose Company Name'] + $company, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{!! Form::select('vehicle_id', ['' => 'Choose Vehicle Vin Number'] + $vehicle, null, ['class' => 'selectpicker form-control', 'data-style'=>'btn btn-link', 'id'=>'exampleFormControlSelect1'])!!}</td>
<td>{‌{$csload->from}}</td>
<td>{‌{$csload->to}}</td>
<td>{‌{$csload->package_type}}</td>
<td>{‌{$csload->length}}x{‌{$csload->width}}x{‌{$csload->height}}</td>
<td>{‌{$csload->weight}}</td>
</tr>
#endif
#endforeach
</tbody>
</table>
</div>
#else
<h1 class="text-center">No Loads Found</h1>
#endif
{!! Form::close() !!}
</div>
</div>
</div>
I am struck in the project kindly answer the question as soon as you can I shall be really obliged.
Thanks in advance
From Munish Rana
Love your Work
change 'method' => 'PATCH' to 'POST'
and add {{ method_field('PATCH') }} to form field like this
<form method="POST" action="your url" >
{{csrf_field()}}
{{ method_field('PATCH') }}
</form>

Laravel 5.4 change user role

I trying make changing role in my panel admin. But when i made it my form dont sending post request. Now only working showing user role. I cant fix it becouse when i click button to switch i dont get any error and role is not changing.
I use HttpRequester when i use url /admin/change its showing this error:
MethodNotAllowedHttpException in RouteCollection.php line 233
There is my code:
View:
#extends('layouts.app')
#section('content')
<h2>Panel Admina</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Imię</th>
<th>Nazwisko </th>
<th>E-mail </th>
<th>Nr.tele </th>
<th>Użytkownik </th>
<th>Moderator </th>
<th>Admin </th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<form action="{{route('change')}}" method="post">
{{ csrf_field() }}
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->lastname }}</td>
<td>{{ $user->email }}<input type="hidden" name="email" value="{{ $user->email }}"></td>
<td>{{ $user->phonenumber }}</td>
<td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"/></td>
<td><input type="checkbox" {{ $user->hasRole('Moderator') ? 'checked' : '' }} name="role_moderator"/></td>
<td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"/></td>
<td><input type="submit" class="btn btn-default btn-sm" value="Przydziel rolę"></td>
</form>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
Controller:
public function change(Request $request)
{
$user = User::where('email', $request['email'])->first();
$user->roles()->detach();
if ($request['role_user']) {
$user->roles()->attach(Role::where('name', 'User')->first());
}
if ($request['role_moderator']) {
$user->roles()->attach(Role::where('name', 'Moderator')->first());
}
if ($request['role_admin']) {
$user->roles()->attach(Role::where('name', 'Admin')->first());
}
return redirect()->back();
}
Routing:
Route::get('/admin', [
'uses' => 'AdminController#index',
'middleware' => 'roles',
'roles' => ['Admin']
]);
Route::post('/admin/change', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
I really dont know how i can resolve my problem.
try to pass the user id to your route and your form action and instead of post make it put for example:
<form action="{{route('change', $user->id)}}" method="post">
and in your route:
Route::put('/admin/change/{id}', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
and in your controller:
public function change(Request $request, $id)

Categories