Passing form values with RESTful routing in Laravel 4 - php

I have setup nested RESTful resource routes like so:
Route::group(array('prefix'=>'opening-hours'), function(){
Route::resource('library', 'LibraryController');
Route::resource('library.interval', 'LibraryIntervalController');
});
I have a blade form which has a select dropdown with options populated from the db, like this:
{{ Form::open(array('route' => 'opening-hours.library.show', 'method' => 'GET')) }}
<legend>Select a library to edit</legend>
<div class="form-group">
<label for="">Please select a library to modify its opening hours:</label>
<select class="form-control" name="id" required>
#foreach ($library_options as $id => $name)
<option value="{{ $id }}">{{ $name }}</option>
#endforeach
</select>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
{{ Form::close() }}
The form submits to the named route:
opening-hours.library.show
The routing itself works but I have a couple of questions about the logistics (I'm a little confused about how to use the routing):
I can get the form to submit to the correct route if I make it a
'GET' request (GET/HEAD opening-hours/library/{library} =>
opening-hours.library.show), as the corresponding POST route does not
exist
how do I pass the user-selected $id to the controller show($id)
method?
when I submit the form, it goes to the URI
"../opening-hours/library/%7Blibrary%7D?id=3". So if the user selects
the library with id=3, how do I make the URI "../opening-hours/library/3"?
Here is my Library controller show method:
/**
* Display the specifed library.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
return "This is a library with id: " . $id . "!";
}
When I submit the form, the following is displayed:
This is a library with id: {library}!
Of course, I'd want it to display:
This is a library with id: 3!
I'm obviously not understanding something critical about how REST or Laravel or both work here. Any pointers would be very much appreciated, I've spent a day knocking about with this!
Thanks a lot

Try using
$id = Input::get('id');
Documentation
I would also recommend using the provided helpers for forms:
echo Form::select('size', array('L' => 'Large', 'S' => 'Small'));
Documentation

Writing out the problem seemed to help me come up with the solution. It seemed silly to use a form to send a 'GET' request, so I thought (bing!) why not just construct the URIs as anchor tag href attributes. So instead of using a form, I did:
#foreach( $library_options as $id => $name )
<a class="btn btn-primary" href="{{ URL::to('opening-hours/library/' . $id) }}">Edit {{ $name }}</a>
#endforeach
That solved the issue of dodgy URIs and also the id was directly available from the RESTful controller method like so:
public function show($id)
{
return "This is a library with id: " . $id . "!";
}

Related

i'm having trouble with adding new replies using laravel8

Before question , This is my code
Show.blade.php
#foreach ($comments as $comment)
#if ($comment->post_id == $post->id)
.....
<form action="{{ route('createreply', ['rid' => $comment->id]) }}" method="POST">
#csrf
<input type="text" class="form-control" name="replyContent" id="replyContent" style="color:white" />
<button type=" submit" style=" color :lavender " class="btn btn-secondary">comment</button>
</form>
....
#endif
#endforeach
(( comment is original comment, and i made reply for answer of comment ))
web.php (route)
Route::post('/replycreate', [CommentController::class, 'createReply'])->name('createreply');
my controller (comment)
public function createReply(Request $request, $rid)
{
$reply = new Reply();
$reply->replyContent = $request->replyContent;
$reply->user_name = Auth::user()->name;
$reply->comment_id = $rid;
dd($reply);
$reply->save();
return redirect()->back();
}
I have problem with making re-reply,
and my code returns error and it says
Too few arguments to function App\Http\Controllers\CommentController::createReply(), 1 passed in C:\Users\ALSACE\post-app\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 54 and exactly 2 expected
I tought i had used two argument , but this kind of error occurs.
so i tought using dd($reply),
dd() can't even complete.
you can guess $rid is empty .. but in the same Show.blade.php , I had used $comment with no problem so i think i can not be problem.
plz help with newbe Laravel student!!
Your createReply method expect 2 arguments, BUT you don't have variable in your route.
You must change the route to:
Route::post('/replycreate/{rid}', [CommentController::class, 'createReply'])->name('createreply');
You forgot to add the id to the route itself. If you're going to require it in the function parameters, then it needs to be added on the route URL.
Route::post('/replycreate/{rid}', [CommentController::class, 'createReply'])->name('createreply');

Laravel 6 - Update function in controller ran but the model is not passed to the controller

I want to update a record from the background_check_batches table. What was done is listing all the records and each has a status property (column) that can be changed. Clicking on the status value will prompt a popup modal to update the value. Since there are multiple records sharing one model, the form's action is changed using js. The issue here is when submitting the form, requested data is received but the BackgroundCheckBatch model id is not. I have previously done this kind of task which is identical but it just doesn't work for some reason. Below are my codes.
web.php
Route::put('/admin/dashboard/background-request/{backgroundrequest}', 'BackgroundCheckBatchController#update')->name('update');
status.blade.php ()
{!! Form::open(['action' => ['BackgroundCheckBatchController#update', -1], 'method' => 'POST', 'id' => 'adminBackgroundCheckStatusModalForm']) !!}
#csrf
#method("PUT")
<div class="modal__content">
<select class="table_custom_select" id="Status" name="status">
<option class="table_custom_select_pending" value="Pending">Pending</option>
<option class="table_custom_select_progress" value="In Progress">In Progress</option>
<option class="table_custom_select_complete" value="Completed">Completed</option>
</select>
</div>
<div class="modal__footer">
<button type="submit" class="button button_size_m button_theme_primary">Proceed</button>
</div>
{!! Form::close() !!}
BackgroundcheckBatchController
public function update(Request $request, BackgroundCheckBatch $backgroundCheckBatch) {
return $backgroundCheckBatch;
}
return $backgroundCheckBatch; outputted and empty array, []
I expect it to return the BackgroundCheckBatch of the provided id in the URL
If I return $request;, it will output like so:
{
_token: "Ax789Dr4VXFVE1vpjtKhEWdBjdCZqARDaNQnk7K8",
_method: "PUT",
status: "Completed"
}
Do inform me if I'm not providing enough detail
If you want to use route model binding the name of your parameter in the update function should match the route parameter:
public function update(Request $request, BackgroundCheckBatch $backgroundrequest) {
return $backgroundrequest;
}
You're using implicit binding, but it doesn't work because your route parameter doesn't match argument name of your controller's method,
Change your route's parameter to snake_case of $backgroundCheckBatch (type-hinted argument name of controller's method):
Route::put('/admin/dashboard/background-request/{background_check_batch}', 'BackgroundCheckBatchController#update')->name('update');

How can I get id from url with Request $request? (Laravel 5.3)

My link href on the view is like this :
<a href="{{ route('message.inbox.detail.id', ['id' => $message->id]) }}" class="btn btn-default">
<span class="fa fa-eye"></span> {{ trans('button.view') }}
</a>
My routes is like this :
Route::get('message/inbox/detail/id/{id}', ['as'=>'message.inbox.detail.id','uses'=>'MessageController#detail']);
When clicked, the url display like this :
http://myshop.dev/message/inbox/detail/id/58cadfba607a1d2ac4000254
I want get id with Request $request
On the controller, I try like this :
public function detail(Request $request)
{
dd($request->input('id'));
}
The result : null
How can I solve it?
You can get it like this
$request->route('id')
Inside request class you can access it this way
$this->route('id')
I usually use it when I'm validating field to make sure it's unique, and I need to exclude model by ID when I'm doing update
This is because you're passing the id parameter through url, you should send it using a form like this
{!! Form::open(['route'=>' route('message.inbox.detail.id', 'method'=> 'POST']) !!}
<input type="hidden" name="id" value="{{ $message->id }}" />
{!! Form::submit({{ trans('button.view') }}, ['class'=>'btn btn-default']) !!}
{!! Form::close() !!}
and now you can access via request in your controller
public function detail(Request $request)
{
dd($request->input('id'));
}
For people who are looking for answers using newer versions of laravel, you can get the route id using the following:
Example route with model binding
Route::put('/post/{post}, [PostController::class, 'update]);
$this->route('id') will not work in this case due to model binding.
instead you can do this:
// using in controller
request()->route('post.id);
or
// using in form request
$this->route('post.id');
Get the id via this:
public function detail($id)
{
dd($id);
}

Laravel Passing Variable from Forms

I am brand new to Laravel, and following a super basic tutorial.
However the tutorial did not come with an edit record section, which I am attempting to extend myself.
Route:
Route::controller('admin/products', 'ProductsController');
Controller:
class ProductsController extends BaseController
{
public function getUpdate($id)
{
$product = Product::find($id);
if ($product) {
$product->title = Input::get('title');
$product->save();
return Redirect::to('admin/products/index')->with('message', 'Product Updated');
}
return Redirect::to('admin/products/index')->with('message', 'Invalid Product');
}
..ECT...
I realise the controller is requesting an ID to use, but I cannot figure out how to pass it a product ID when the form is posted/get.
Form:
{{Form::open(array("url"=>"admin/products/update",'method' => 'get', 'files'=>true))}}
<ul>
<li>
{{ Form::label('title', 'Title:') }}
{{ Form::text('title') }}
{{ Form::hidden('id', $product->id) }}
..ECT...
{{ Form::close() }}
my initial idea was to pass the product id within the form URL like:
{{Form::open(array("url"=>"admin/products/update/{{product->id}}", 'files'=>true))}}
But no luck with that either.
The error I get is:
Missing argument 1 for ProductsController::postUpdate()
Interestingly if I type directly into the URL:
http://localhost/laravel/public/admin/products/update/3
It works and the item with id 3 is altered fine.
So can anyone help and inform me how to pass the id with a form?
Thanks very much
The first Problem here ist the following:
{{Form::open(array("url"=>"admin/products/update/{{product->id}}", 'files'=>true))}}
the {{product->id}} is wrong in two ways:
it should be {{$product->id}}
BUT it wouldn't work anyway because the inner {{..}} inside of the {{Form::...}} won't be recognized since it is inside a string and therefore part of the string itself.
You either have to write it this way:
{{Form::open(array("url"=>"admin/products/update/".$product->id, 'files'=>true))}}
or you give your route a name in your routes.php file and do it this way:
{{Form::open(array('route' => array('route.name', $product->id, 'files'=>true)))}}
I prefer the second way.
You also might want to look into Form Model Bingin

Laravel form action

I'm having a hard time setting up simple links/actions.
In my index view, I have this little form that I want to launch the getTest action in the ProjectsController when I click on the button:
{{ Form::open(array('action' => array('ProjectsController#getTest', $project->id))) }}
<button type="submit"><i class="icon-arrow-up"></i></button>
{{ Form::close() }}
This is the getTest function :
public function getTest(){
echo "test";
return 'test';
}
But this keeps getting me a "Array_combine(): Both parameters should have an equal number of elements" error.
I tried making this work with a route. with this form open instead :
{{ Form::open(['method' => 'GET', 'route' => ['test_route', $project->id]]) }}
And this route :
Route::get('projects/test', array('as' => 'test_route', 'uses' =>'ProjectsController#getTest'));
But I still have the same error.
I can't find any good doc on routing/sending to actions that don't give me this problem. I don't see what
Your route doesn't need parameter, so I think this code is sufficient:
{{ Form::open(['method' => 'GET', 'route' => 'test_route']) }}
I believe the problem is you are adding parameters to the action, but you are not managing those parameters in your routes, nor is your getTest() function accepting any parameters. Another problem is you are setting your route as a GET route, but your form is going to be using POST.
It would be much easier instead on your form to use Form::hidden('id', $project->id); And then in your getTest() function, you could get the variable using $id = Input::get('id');. You'd also be able to use your route name in your form as well. Form::open(array('route'=> 'test_route', method=> 'get'));

Categories