Second independant form inside another form in laravel - php

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

Related

why this function don't pass the coupon data to view in PHP Laravel?

I have created an online store, but there is a problem that when I enter the discount code in, the condition is executed correctly and returns a message of success of the operation, but no data for the entered discount code is returned.
the check function
public function coupon_check()
{
$coupon = Coupon::where('code', request()->post('code'))->first();
if (isset($coupon) || !empty($coupon)) {
toast('Successfully !!!', 'success');
return redirect()->back()->with(['coupon'=>$coupon]);
} else {
toast('Not Found !!!', 'error');
return redirect()->back();
}
}
in here
<tr>
<td style="color: white">{{__('discount')}}</td>
<td style="color: white">#if($coupon){{$coupon->discount_value }}
#endif </td>
</tr>
when executing this form
<form action="{{ route('coupons.check') }}" method="POST">
#csrf
<input type="text" name="code" class="form-control text-center" placeholder="
{{ __('cupon code') }}">
<button name="confirm_code" class="btn btn-success col-md">{{ __('Confirm')
}}</button>
</form>
When you use with, you create a session, and to access that session, you should use session helper. So change your if statement like this:
#if(session('coupon')){{session('coupon')->discount_value }}

Laravel destroy function always delete the record with lowest id

im new to laravel. So im trying to delete a record from database from my index page. But it only delete the record with the lowest primary key value, my id field.
Here's my controller code for destroy function:
public function destroy(Province $province)
{
//
$findProvince = DB::table('provinces')->where('id', $province->id)->delete();
if($findProvince){
return redirect()->route('provinces.index')->with('success', 'Province deleted successfully');
}
return back()->with('error', 'Province could not be deleted');
//var_dump($province->id);
}
Here's my view code:
#extends('layouts.app')
#section('content')
<div class="col-md-8 offset-md-2">
<br/>
<div>
Add New Province
</div>
<br/>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Image</th>
<th scope="col">Operations</th>
</tr>
</thead>
<tbody>
#foreach($provinces as $province)
<tr>
<th scope="row">{{ $province->id }}</th>
<td>{{ $province->name }}</td>
<td><img src="../{{ $province->imgPath }}" width="200px"/></td>
<td>
Edit |
<a
class="btn btn-danger"
href="#"
onclick="
var result = confirm('Are you sure you wish to delete this province?');
if( result ){
event.preventDefault();
document.getElementById('delete-form').submit();
}
">Delete
</a>
<form id="delete-form" action="{{route('provinces.destroy', $province->id)}}" method="POST" style="display: none;">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
I tried using var_dump on the $province->id but it only output the lowest 'id' value.
id's are unique. You will get this unexpected behavior if you use the same id in a loop. Either use unique id's or put your buttons inside the form (I suggest this).
<td>
<form class="delete-form" action="{{ route('provinces.destroy', $province->id) }}" method="POST">
<input type="hidden" name="_method" value="delete">
{{ csrf_field() }}
Edit |
<a class="btn btn-danger">Delete</a>
</form>
</td>
And then use this Javascript in a seperate file for confirmation:
(function(){
let forms = document.querySelectorAll('form.delete-form');
[].forEach.call(forms, function(form){
form.onsubmit = function(e) {
if ( ! confirm('Are you sure you wish to delete this province?'))
return e.preventDefault();
}
});
})();
If you still want to use your approach, add the id of $province to the id attribute of your form. This will make your form unique so you get access it with an id.
<form id="delete-form-{{ $province->id }}" ...>
And then your Javascript:
if( result ){
event.preventDefault();
document.getElementById('delete-form-{{ $province->id }}').submit();
}
Thanks everyone for your help. And sorry that it took me long to reply. I've been really busy with other schools. So i managed to track down the problem with my code. It's with my view. All the created delete form has the same id. So if i just added the record id to the form. It works just fine.

Laravel CRUD destroy method not working. Cannot pass data from the view to the controller in order to delete the data

Destroy method not working
I am trying to delete an image from my database but I am receiving the following error:
Undefined variable: portfolio (View: C:\MyProjects\bubblehouseProject\resources\views\admin\portfolio\addPortfolio.blade.php)
I believe there is something wrong with the logic I am trying to implement in my Laravel application. I am using Eloquent ORM.
Controller:
public function Destroy($id) {
$portfolio = new Portfolio();
$portfolio::find($id);
$portfolio->delete();
return redirect('addPortfolio')->with('delete', 'The image has been successfully deleted!');
}
Route:
Route::get('addPortfolio/{id}', 'AddPortfolioController#Destroy');
View:
<form action="{{ route('addPortfolioController.Destroy', $portfolio->id) }}">
<input type="submit" value="Delete" class="btn btn-danger btn-block" onclick="return confirm('Are you sure to delete?')">
<input type="hidden" value="{{ csrf_token() }}" name="_token">
{{ method_field('DELETE') }}
</form>
I am not entirely sure that this is the right way to delete data from the database.
Route
Route::delete('addPortfolio/{id}', 'AddPortfolioController#Destroy')->name('portfolio.destroy');
View
<form action="{{ route('portfolio.destroy', $portfolio->id) }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<input type="submit" value="Delete" class="btn btn-danger btn-block" onclick="return confirm('Are you sure to delete?')">
</form>
Controller
public function destroy($id)
{
if(Portfolio::destroy($id)) {
return redirect('addPortfolio')->with('success', 'The image has been successfully deleted!');
} else {
return redirect('addPortfolio')->with('error', 'Please try again!');
}
}

Add method 'put' to a url in laravel 4.2

I'm trying to change the status of a database record with just a button click so far I have this:
view
<td>
<a class="btn btn-small btn-warning" href="{{ URL::to('brands/'.$value->BrandID.'/archive') }}">Archive </a>
</td>
controller
public function archive($id)
{
$rules= array ('BrandName' =>'required | max:20',);
$validator = Validator::make(Input::all(), $rules);
if($validator->fails())
{
return Redirect::to('brands.view')
->withErrors($validator);
} else {
DB::table('tbl_brands')->where('BrandID' , $id)
->update(
array
(
'Status' => 'Archived'
));
Session::flash('message','Successfully Archived!');
return Redirect::to('brandsview');
}
}
and the route
Route::put('brands/{id}/archive', array('as' => 'Brandarch', 'uses'=>'BrandsController#archive'));
and my error what method exception. I scrolled down a bit and saw that in the errors, the http request is 'get' which I know should be 'put' any ideas on how to properly execute this?
You will need to change your hyperlink to a submit form in a form with hidden field with name _method, only this way you can control HTTP method used.
For example:
<form action="{{ URL::to('brands/'.$value->BrandID.'/archive') }}" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="submit" value="Archive">
</form>

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