Laravel - route("resource.destroy") calls "resource.show" - laravel

This is the web.php
Route::group(['middleware' => 'auth'],
function () {
Route::get('letters/getRows', 'LetterController#getRows')->name('letters.getRows');
Route::get('letters/{letter}/A4', 'LetterController#A4')->name('letters.A4');
Route::get('letters/{letter}/A5', 'LetterController#A5')->name('letters.A5');
Route::resource('letters', 'LetterController');
}
);
I created a link as follow
"<a class='mx-2 h5' href='".route('letters.destroy', $entity->id)."'><i class='icon-remove-circle'></i></a>".
where the $entity->id is the id of the letter. The problem is, it links to show method not the destroy method. What can I do?
Using a form like this
{{ Form::open(array('route' => array('letters.destroy', $entity->id), 'method' => 'delete')) }}
<button type="submit" >Delete Account</button>
{{ Form::close() }}
may solve the problem but I want to use a tag not a form.
update
In the php artisan route:list, the url of destroy and show are the same
thanks

When you use the Route::resource method it will create, among others, a route to DESTROY a resource like this: /letters/:id/ and another route to EDIT the resource: /letters/:id, and one more to SHOW /letters/:id
They all look the same. However, the difference is in the HTTP method/verb used to reach each route.
If you look to the output if php artisan route:list, you will find the list of HTTP methods used. Something like:
GET|HEAD | letters/{letter} | letters.show
PUT|PATCH | letters/{letter} | letters.update
DELETE | letters/{letter} | letters.destroy
Therefore, to show a letter, you use a GET method, to edit a letter, use PUT method, and to destroy/delete, you use a DELETE method.
When you use an a tag, the browser will use the GET method, thus will reach the letters.show route. Html forms, can use POST or GET. Finally to use the DELETE http method, you need a form with hidden input named _method and the value="delete inside the form. Check the docs for more details.
There is also a note about this in LaravelCollective package documentations
Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form.
Finally, if you must use an anchor tag <a>, you could use javascript to listen to the click event and submit a form with DELETE method.
Update to add an example:
You can find an example of using an anchor tag to submit the form, in the default app layout in the framework here
And this is a modified version to submit a delete request:
<a class="dropdown-item" href="#"
onclick="event.preventDefault();
document.getElementById('destroy-form').submit();">
{{ __('DELETE') }}
</a>
<form id="destroy-form" action="{{ route('letters.destroy', $entity) }}" method="POST" style="display: none;">
#method('DELETE')
#csrf
</form>

You cant. If you want to make a DELETE request you need to spoof it via a form (method POST, _method DELETE) or use Javascript.
Hyperlinks will cause new requests which will be GET requests. That is just how the web works.

Related

getting errors The POST method

I have a problem with my edit page. When I submit I get this error:
Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException
The GET method is not supported for this route. Supported methods:
POST
.
I have no clue where it comes from as I am pretty new to Laravel.
web.php
Route::post('/admin/add_reseller','ResellerController#addReseller');
Controller.php
public function addReseller(){
return view ('admin.resellers.add_reseller');
}
add_reseller.blade.php
<form class="form-horizontal" method="post" action="" name="addreseller" id="addreseller">
{{ csrf_field() }}
Tip:
First of all, I would use named routes, that means you add ->name('someName') to your routes. This makes the use of routes way easier and if you decide that your url doens't fit you don't need to change it everywhere you used the route.
https://laravel.com/docs/7.x/routing#named-routes
e.g. Route::post('/admin/add_reseller',
'ResellerController#addReseller')->name('admin.reseller');
Problem:
What I see is, that you lack the value for the action attribute in your <form>. The action is needed, so that the right route is chosen, if the form gets submitted.
Solution:
I guess you just have to add action="{{route('admin.reseller')}}" for the attribute, so that the request goes the right route.
<form class="form-horizontal" method="post" action="" name="addreseller" id="addreseller">
Your action in the form is empty, you need to add the corresponding route there.
I'd suggest you to use named routes.
https://laravel.com/docs/7.x/routing#named-routes
In web.php
Route::post('/admin/add_reseller','ResellerController#addReseller')->name('admin.add.reseller');
and then in your blade file you could refer to the route using the route() function by passing the name of the route as an argument
<form class="form-horizontal" method="post" action="{{route('admin.add.reseller')}}" name="addreseller" id="addreseller">

laravel POST request not rendering

Below is the auth part of my routes.
I just added the Tags part (where I can add another tag to the DB).
the tag creation works but the creation of a new post doesn't work now (worked before).
When I "submit" a post, it doesn't redirect or submits anything and it refreshes me back to the post create form with empty fields like nothing was rendered.
I tried to play with the positions of the routing, I made the post creation work but than the same happened to the tag creation where the page was "submiting" but actually there was no submit and it didn't redirect afterwards.
Auth::routes();
Route::get('/posts', 'PostsController#index')->name('posts.index');
Route::middleware('can:isAdmin')->group(function () {
Route::get('/posts/create', 'PostsController#create')->name('posts.create');
Route::get('/posts/{post}/edit', 'PostsController#edit')->name('post.edit');
Route::put('/posts/{post}', 'PostsController#update');
Route::post('/posts', 'PostsController#store');
Route::get('/tags/create', 'TagsController#create')->name('tags.create');
Route::post('/posts', 'TagsController#store');
});
Route::get('/posts/{post}', 'PostsController#show')->name('posts.show');
thanks in advance.
At first, in given configuration you have two routes for same method / URI combination, so one of them would be unreachable:
// here the first
Route::post('/posts', 'PostsController#store');
Route::get('/tags/create', 'TagsController#create')->name('tags.create');
Route::post('/posts', 'TagsController#store'); // <-- here the second
Looks like your post form submit goes to the tags, than validation fails and it redirect you back to post create page. Do you display validation errors?
here is example - https://laravel.com/docs/5.8/validation#quick-displaying-the-validation-errors
<!-- /resources/views/post/create.blade.php -->
<h1>Create Post</h1>
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<!-- Create Post Form -->
If it refresh your page so probably it works but if it do not save your request to databse it means that your request not validate respect to table.
Use validation for understand the errors.

can I use route() to make a DELETE request in laravel

I'm using laravel and trying to delete something. Is it possible to specify the DELETE method on laravel's route()??
e.g
route('dashboard-delete-user', ['id' => $use->id, 'method'=> 'delete'])
or something like that??
EDIT:
What I meant was could I specify that in a link or a button in my blade template. Similar to this:
href="{{ route('dashboard-delete-user') }}
Yes, you can do this:
Route::delete($uri, $callback);
https://laravel.com/docs/master/routing#basic-routing
Update
If for some reason you want to use route only (without a controller), you can use closure, something like:
Route::get('delete-user/{id}', function ($id) {
App\User::destroy($id);
return 'User '.$id.' deleted';
});
No or at least I haven't figure out how to.
The only way for this to work out of the box would be to build a form to handle it. At the very minimum, you would need...
<form action="{{ route('dashboard-delete-user') }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<button type="submit" value="submit">Submit</button>
</form>
Or you can just create the get route which you are trying to link to and have it handle the logic. It doesn't need to be a route which only respondes to delete requests to delete a resource.
Yes you can, using a URL helper. https://laravel.com/docs/5.2/helpers#urls
There are several options to choose from.

Posting form in Laravel 4.1 and blade template

I'm having trouble posting forms using Laravel 4.1 with the blade template engine. The problem seems to be that the full URL including http:// is being included in the form action attribute. If I hard code the form open html manually and use a relative url, it works OK, however, when it has the full url, I am getting an exception.
routes.php
Route::any("/", 'HomeController#showWelcome');
HomeController.php
public function showWelcome()
{
echo($_SERVER['REQUEST_METHOD']);
return View::make('form');
}
Form opening tag in form.blade.php
{{ Form::open(["url" => "/","method" => "post","autocomplete" => "off"]) }}
{{ Form::label("username", "Username") }}
{{ Form::text("username", Input::old("username"), ["placeholder" => "john.smith"]) }}
{{ Form::label("password", "Password") }}
{{ Form::password("password", ["placeholder" => ""]) }}
{{ Form::submit("login") }}
{{ Form::close() }}
So if I go to my home dir / in the browser, I see the form that I have created. If I fill in the form details and click submit, I am simply taken to the same page - the request method is still GET as shown by echo($_SERVER['REQUEST_METHOD']);
I notice that the full
http://localhost/subdir/public/
url is used in the form markup. If I hardcode a form open tag in such as
<form action="/subdir/public/" method="post">
it works fine and $_SERVER['REQUEST_METHOD'] shows as post.
What am I doing wrong here?
You have created the route for the post?
example:
{{Form::open(["url"=>"/", "autocomplete"=>"off"])}} //No need to later add POST method
in Route.php
Route::post('/', 'YouController#postLogin');
you have not set up a route to handle the POST. You can do that in a couple of ways.
As pointed out above:
Route::post('/', 'HomeController#processLogin');
note that if you stick with your existing Route::any that the `Route::post needs to be before it as Laravel processes them in order (I believe).
You could also handle it in the Controller method showWelcome using:
if (Input::server("REQUEST_METHOD") == "POST") {
... stuff
}
I prefer the seperate routes method. I tend to avoid Route::any and in my login pages use a Route::get and a Route::post to handle the showing and processing of the form respectively.

How does Laravel handle PUT requests from browsers?

I know browsers only support POST and GET requests, and Laravel supports PUT requests using the following code:
<?= Form::open('/path/', 'PUT'); ?>
... form stuff ...
<?= Form::close(); ?>
This produces the following HTML
<form method="POST" action="http://example.com/home/" accept-charset="UTF-8">
<input type="hidden" name="_method" value="PUT" />
... form stuff ...
</form>
How does the framework handle this? Does it capture the POST request before deciding which route to send the request off to? Does it use ajax to send an actual PUT to the framework?
It inserts a hidden field, and that field mentions it is a PUT or DELETE request
See here:
echo Form::open('user/profile', 'PUT');
results in:
<input type="hidden" name="_method" value="PUT">
Then it looks for _method when routing in the request.php core file (look for 'spoofing' in the code) - and if it detects it - will use that value to route to the correct restful controller.
It is still using "POST" to achieve this. There is no ajax used.
Laravel uses the symfony Http Foundation which checks for this _method variable and changes the request to either PUT or DELETE based on its contents. Yes, this happens before routing takes place.
You can also use an array within your form open like so:
{{ Form::open( array('route' => array('equipment.update', $item->id ),
'role' => 'form',
'method' => 'put')) }}
Simply change the method to what you want.
While a late answer, I feel it is important to add this for anyone else who finds this and can't get their API to work.
When using Laravel's resource routes like this:
Route::resource('myRoute','MyController');
It will expect a PUT in order to call the update() method. For this to work normally (outside of a form submission), you need to make sure you pass the ContentType as x-www-form-urlencoded. This is default for forms, but making requests with cURL or using a tool like Postman will not work unless you set this.
PUT usually refers to update request.
When you open a form inside laravel blade template using,
{{ Form::open('/path/', 'PUT') }}
It would create a hidden field inside the form as follows,
<input type="hidden" name="_method" value="PUT" />
In order for you to process the PUT request inside your controller, you would need to create a method with a put prefix,
for example, putMethodName()
so if you specify,
{{ Form::open('controller/methodName/', 'PUT') }}
inside Form:open. Then you would need to create a controller method as follows,
class Controller extends BaseController {
public function putMethodName()
{
// put - usual update code logic goes here
}
}

Resources