Two forms on same view in Laravel 4 - php

I've tried number of solutions from other posts but still can't get it work.
I have two forms on the page(view)
{{ Form::open(array('action' => 'AdminController#shopMode')) }}
....// form fields
<button type="submit" class="btn btn-primary">Change</button>
{{ Form::close() }}
<hr/>
{{ Form::open(array('action' => 'AdminController#preferencesSubmit')) }}
....// second form fields
<button type="submit" class="btn btn-primary">Save Changes</button>
{{ Form::close() }}
Then in routes I have
Route::post('/admin/preferences', ['uses' => 'AdminController#preferencesSubmit', 'before' => 'csrf|admin']);
Route::post('/admin/preferences', ['uses' => 'AdminController#shopMode', 'before' => 'csrf|admin']);
When I hit submit button nothing change in database. Just page is refreshed and I got success message from FIRST form even if I submit second one.
Is it because url's in routes are same for both posts?
Update: First form input field:
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" <?php if ($settings['preferences_shop_mode'] == 0){ ?> checked="checked" value="1"<?php }else{ ?> value="0" <?php } ?>>
Here I check if preference is =0 to set value to 1 otherwise value = 0. In source I see that value is =1 which is correct because in database I have 0
<input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked="checked" value="1">
This is the controller
public function shopMode() {
$preferences = Preferences::where('preferences_id', 1)->first();
if (!$preferences) {
App::abort(404);
}
Input::merge(array_map('trim', Input::all()));
$preferences->preferences_shop_mode = Input::get('onoffswitch');
$preferences->save();
return Redirect::to('/admin/preferences')->with('message', 'Shop mode changed successfully.');
}
Any idea why isn't updated in database?

Routes are read in cascade. Since both routes have the same path, the first takes priority (an entry was found, so no further route lookup is needed).
You should split them with just different paths, for example:
Route::post('/admin/preferences/general', ['uses' => 'AdminController#preferencesSubmit', 'before' => 'csrf|admin']);
Route::post('/admin/preferences/shop', ['uses' => 'AdminController#shopMode', 'before' => 'csrf|admin']);

Related

$request->get() not getting the form value when updating data in laravel 5.4

I am trying to update just one column from'business_account' table. I tried something like bellow, When trying to get the form value to my 'packPurchasedMembers' controller function I am getting null value. What should be the right code to getting expected result.
Route::group(['prefix' => 'super', 'middleware' => 'super', 'as' => 'super.'], function () {
Route::post('verify-account', array('as' => 'verify-account', 'uses' => 'packPurchasedMembers#postVerifyAccount'));});
My Controller-
public function postVerifyAccount(Request $request){
$uid = $request->get('userid');
$verfiy = $request->get('verification');
DB::table('business_account')
->where('user_id', $uid)
->update(['verified' => $verfiy]);}
My Form -
<div class="pull-left">
<h4>Verify Account</h4>
#foreach ($verification as $verify)
<form action="{{ url('super/verify-account') }}" method="POST">
{{ csrf_field() }}
<input type="hidden" name="userid" value="<?php echo $uid; ?>" />
<input type="radio" id="reinv1" name="verification" value="0"
<?php if ($verify->verified == '0') echo 'checked' ?> >
<label for="reinv1"> Not Verified</label>
<input type="radio" id="reinv2" name="verification" value="1"
<?php if ($verify->verified == '1') echo 'checked' ?> >
<label for="reinv2"> Verified</label>
<button type="submit" class="btn btn-success" value="Submit">Submit</button>
</form>
#endforeach
</div>
Please use the following function to retrieve input value
public function postVerifyAccount(Request $request){
$uid = $request->input('userid');
$verfiy = $request->input('verification');
DB::table('business_account')
->where('user_id', $uid)
->update(['verified' => $verfiy]);
}
Just in case if anyone lands up to this question. I would like to address the solution for the above question.
So the problem was he had not used the proper HTTP request. Instead of using POST request he was using GET request.
In routes/web.php
The request method is changed from GET -> POST.
Hope it may help someone.

Laravel 5.3 Database Update From Button Click

So I'm building an app to monitor tasks / jobs. Each job has a status and the default is "1". If it has been finished, the user will click a button, which will change the status to "2", meaning it's done. However, I haven't been successful so far and I will be needing your help.
So far, this is what I have done
The button link:
<p>
{{ link_to('job/detail/' . $job->id, 'Finish Task', ['class' => 'btn btn-primary btn-lg']) }}
</p>
The controller:
public function finish($id)
{
$job = Job::findOrFail($id);
$job->update(['status' => '2']);
}
And finally, my route, which I have the biggest doubt. Because I might have two conflicting routes
Route::get('job/detail/{job}', 'JobController#show');
Route::put('job/detail/{job}', 'JobController#finish');
I didn't use any form, and I wanted to do the update right from the button click. Is that possible?
Thanks for the answers
If you would like to make it more secure you should use PUT method as you did:
Route::put('job/detail/{job}/finished', 'JobController#finish');
/*********/
public function finish(Request $request,Job $job){
$this->validate($request,[
'status'=>'required|in:2'
]);
$job->update(['status'=>$request->only('status')]);
}
/*********/
<form action="/job/detail/{{$job->id}}/finished" method="POST">
{{csrf_field()}}
<input type="hidden" name="_method" value="PUT"></input>
<input type="hidden" name="status" value="2"></input>
<button type="submit" class="btn btn-primary">Change Staus</button>
</form>
Without using form:
Route::get('job/detail/{job}/finished', 'JobController#finish');
/*********/
public function finish(Job $job){
$job->update(['status'=>2);
}
/*********/
Change Status
As you can see I've added finished at the end of the link because it may has conflict with your other get route.
Try this, try to change the url a bit and this would work. Try and tell
Route::get('job/detail/{job}/action', 'JobController#finish');
public function finish($id)
{
Job::find($id)->update(['status' => '2']);
}
<p>
{{ link_to('job/detail/' . $job->id. '/action', 'Finish Task', ['class' => 'btn btn-primary btn-lg']) }}
</p>

Adding input query to route value for search function Laravel Scout

Trying to set up basic search functionality for products. I am having trouble sorting the route parameter variable and passing the query string to the search function.
Route::get('/search/{query?}', 'ProductController#searchable');
This works and returns a query when I input the query manually.
Controller
public function searchable($query)
{
// search database, with result, list on page, with links to products,
$products = Product::search($query)->get();
return view('search.index', compact('products'));
}
However, I would like it to come from the URL /search?test.
My form shows:
{{ Form::open(array('action' => 'ProductController#searchable', 'method' => 'get', 'files' => 'false')) }}
<input type="search" name="search" placeholder="type keyword(s) here" />
<button type="submit" class="btn btn-primary">Search</button>
{{ Form::close() }}`
I am new to Laravel and need a little help. I am using Laravel Scout and TNTSearch.
You don't need to user {wildcard} for searching. We have Request for that
Route::get('search', 'ProductController#searchable');
Pass the url instead.
{{ Form::open(array('url' => 'search', 'method' => 'GET', 'files' => 'false')) }}
<input type="search" name="search" placeholder="type keyword(s) here" />
<button type="submit" class="btn btn-primary">Search</button>
{{ Form::close() }}
In Controller simple fetch $request->search
public function searchable(Request $request)
{
// search database, with result, list on page, with links to products,
$products = Product::search($request->search)->get();
return view('search.index', compact('products'));
}

Second independant form inside another form in laravel

I'm trying to make something that I'm not sure if is possible and how exactly can happen.
What I want is to have one table which is in form and one addition form inside. The depending of which button I hit to perform different actions in controller. Here is what I have so far
my blade
{{ Form::open(array('url' => 'admin/inv')) }}
{{ Form::open(array('url' => 'admin/inv/multiPC')) }}
<table class="table table-bordered">
<tbody>
<tr>
<td><input type="checkbox" name="delete[]" value="{{ $product->product_id }}"> </td>
<td><strong>${{ $product->price }}</strong><input type="number" name='price[]' class="form-control"/></td>
</tr>
</tbody>
</table>
<button type="submit" href="{{ URL::to('/admin/del') }}?_token={{ csrf_token() }}">Delete</button>
<button type="submit" href="{{ URL::to('/admin/multiPC') }}?_token={{ csrf_token() }}">Update Price</button>
{{ Form::close() }}
{{ Form::close() }}
Those are both functions
public function pDelete() {
$delete = Input::only('delete')['delete'];
$pDel = Product::whereIn('product_id', $delete)->delete();
return Redirect::to('/admin/inv')->with('message', 'Product(s) deleted.');
}
public function priceUpdate() {
$pchanges->price = Input::only('price')['price'];
$pChange = Product::whereIn('product_id', $pchanges);
$pChange->save();
return Redirect::to('/admin/inv')->with('message', 'Product(s) price changed.');
}
And route
Route::post('/admin/inv', ['uses' => 'AdminController#pDelete', 'before' => 'csrf|admin']);
Route::post ('/admin/inv/multiPC', ['uses' => 'AdminController#priceUpdate', 'before' => 'csrf|admin'])
What happen is when I check product and hit Delete button product is deleted. But when I input price in the input field for price and hit Update Price page only refreshed and price isn't changed.
Is there a way to accomplish this without using JS?
try this type of approach
<form method="POST" class="form-horizontal" action="myapplication/personal">
<input type="number" name='price[]' class="form-control"/>
<input type="checkbox" name="delete[]" value="{{ $product->product_id }}">
<button type="submit" name="step[0]" value="Delete">Delete</button>
<button type="submit" name="step[1]" value="Update">Update Price</button>
</form>
from your controller check the value of step and do as you like
public function formProcess() {
$action = request::get('step'); // i forgot laravel 4 syntex. used laravel 5 instead here :D
if($action == 'Delete')
{
// do delete operation
}
else
{
//do update operation
}
}
hope this helps

PHP Laravel - how to test if a checkbox is checked, if the value is a variable?

I'm a noob in Laravel, so please bear with me.
I'm continuing work on a friend's webpage that displays a list of items (with a checkbox beside each item). There are plenty of ways to interact with said items, such as "Delete", "Update", and the one I'm working on, "Download". There's a delete button per row/item/checkbox, so that a user can easily delete just one item. There's also a mass delete option, where the user can check multiple rows, check a "Delete" checkbox, and click on "Update". The webpage stores data on mongodb.
Supposedly, a user checks the box, clicks on Download, and a file is created and downloaded for the user.
But I'm not getting to that part yet. For now I'm having trouble even checking if the checkboxes are checked.
Here's my code:
Download Button:
<div class="col-md-1 col-md-offset-1">
{{ Form::open( array(
'url' => 'contents/download',
'role' => 'form',
'method' => 'POST',
'class' => 'form-inline'
)
) }}
<div class="form-inline" role="form">
<div class="form-group">
<input type="submit" class="btn btn-success" name="download" id="download" value="Download Selected">
</div>
</div>
{{ Form::close() }}
</div>
Here's the rows of checkboxes/items. Notice that the value of the checkbox is a variable - it corresponds to the ID of the item in the database.
#foreach($children as $child)
#if($mother->id == $child->mother_id)
<tr>
<td class="text-center">
{{--*/ $child->id /*--}}
<input type="checkbox" class="child" value="{{ $child->id }}" onclick=isSelected(this)>
</td>
<td>
<span class="glyphicon glyphicon-file"></span>
{{ ucwords($child->child) }}
</td>
<td class="text-center">
Coder
</td>
<td class="text-center">
{{ $child->updated_at }}
</td>
<td class="text-center">
{{ Form::open(array(
'url' => 'contents/delete',
'role' => 'form',
'method' => 'POST',
'class' => 'form-inline'
)
) }}
<input type="hidden" value="{{ $child->id }}" name="id">
<input type="submit" class="btn btn-danger btn-xs" name="deleteChild" value="Delete" onclick="return confirmDelete();" />
{{ Form::close() }}
</td>
</tr>
#endif
#endforeach
Controller Code:
public function postDownload()
{
$input = Input::all();
if(Input::has("child"))
{
echo $input["child"];
// Begin download
}
else
{
echo "none";
// Error - No Item selected
}
}
My understanding of Laravel is basic at best. Where did I go wrong? Or perhaps there's another approach to this?
First of all, in HTML you should give your checkboxes a name, perhaps something like items.
When you submit the form, Laravel get those data. And now if retrieve input by using Input::get('items'),
$itemIds = Input::get('items');
you will get an array whose elements are those checkboxes that were checked. This array is basically an indexed array, the structure could be like this
array(
[0] => '1', // item 1 ID
[1] => '5', // item 5 ID
[2] => '33' // item 33 ID
)
Finally, you are ready to process $itemIds however you want.
By the way, if no boxes were checked in your UI, you cannot get an array by calling Input::get('items'). Therefore, it might be better to check whether this field exists first by calling Input::has('items').
In your HTML , name the checkboxes dynamically after your item IDs.
Example , item1 , item2 etc.
Then check for selected items like this in your controller
$items = Item::all();
foreach($items as $item)
{
if($request->has('item'.$item->id)){
// item has been ticked
}
else{
// item was not ticked
}
}

Categories