I have three tables delivery-request_item, items and a pivot table delivery-request_item. In my create.blade.php, I have button, which will add one of the items with its corresponding quantity selected by the user.
My solution was to put the item and quantity to the Session. Now my problem is that I can only create one record, if I decided to add another item, the previous item gets overridden.
create.blade.php
{{Form::open(array('method'=>'POST','url'=>'delivery-requests'))}}
{{Form::text('requested_by', Auth::user()->email)}}
<div>
{{Form::label('Shows Items from table')}}
{{Form::select('item_id', $items)}}
{{Form::label('Quantity')}}
{{Form::text('item_quantity')}}
{{Form::submit('add item',array('name'=>'addItem'))}}
{{Form::submit('remove item', array('name' => 'removeItem'))}}
</div>
<hr>
<div>
<table>
<theader>
<tr>
<td>ITEM NAME</td>
<td>QUANTITY</td>
</tr>
</theader>
<!-- loop through all added items and display here -->
#if(Session::has('item_id'))
<h1>{{ Session::get('item_id') }}</h1>
#endif
#if(Session::has('item_quantity'))
<h1>{{ Session::get('item_quantity')}}</h1>
#endif
</table>
</div>
{{Form::submit('submit', array('name' => 'submit'))}}
{{Form::close()}}
DeliveryRequestsController#Store
if(Input::has('addItem'))
{
Session::flash('item_id', Input::get('item_id'));
Session::flash('item_quantity', Input::get('item_quantity'));
$data = Session::all();
$item = Item::lists('item_name','id');
return View::make('test')->with('data',$data)->with('items',$item);
}
Two things.
You need to make the session an array, otherwise you'll always overwrite.
You need to not use flash() as this data will be removed as soon as another request is made, that's what flash data is, data that persists until the next request.
Try this:
if(Input::has('addItem')) {
if(Session::has('items')) {
Session::push('items', [
'id' => Input::get('item_id'),
'qty' => Input::get('item_quantity')
]);
} else {
Session::put('items', [
'id' => Input::get('item_id'),
'qty' => Input::get('item_quantity')
]);
}
}
Session::push() works with arrays stored in a session, and then obviously Session::put() is used if it doesn't exist.
Remember that this data will be persist, and will need to be cleared upon certain instances, like once you've finished with it.
For more information about sessions, read this: http://laravel.com/docs/session
Related
In my app i have a Payers table which hasMany relationship with Spouses in the Model. I want to be able to add several Spouses to a client in situation where they have more than one spouse while saving their details.
For that purpose I created a Livewire component Spouses with code below.This code allows me to add new form group for each Spouse the Payer has.
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Spouses extends Component
{
public $spouses = [];
public function increments()
{
$this->spouses[] =count($this->spouses)+1;
}
public function remove($index){
unset($this->spouses[$index]);
}
public function render()
{
return view('livewire.spouses');
}
}
The form is on the component page (spouses.blade.php) with the following codes
<div>
<div>
<span wire:click ="increments" class="btn btn-defaults fa fa-plus padding:2 py-1 cursor:pointer text-success"> Click to Add Spouse(s)</span>
</div>
#foreach($spouses as $spouse)
<div class="col-md-10 d-flex">
{!! Form::text('spouse_name', '',array(
'class' => 'form-control col-3',
'id' => 'spouse_name',
'placeholder' => 'Spouse name',
)) !!}
{!! Form::text('spouse_dob', '',array(
'class' => 'form-control col-3',
'id' => 'spouse_dob',
'placeholder' => 'Spouse Age',
)) !!}
{!! Form::text('spouse_emplbiz_add', '',array(
'class' => 'form-control col-3',
'id' => 'spouse_emplbiz_add',
'placeholder' => 'Work Address',
)) !!}
{!! Form::text('spose_income', '',array(
'class' => 'form-control col-3',
'id' => 'spose_income',
'placeholder' => 'Gross Income',
)) !!}
<span class="btn btn-defalt fa fa-times text-danger padding:2"
wire:click="remove({{$loop->index}})"></span>
</div>
#endforeach
</div>
</div>
And finally i imported it to my Payers creation page using the #livewire('spouses').
However after filling the form and adding like three Spouses for each client Only one row is added into the Spouses database.
I will appreciate a careful analysis of my codes to tell me how to ensure that all the spuses record save as the Payers details is saving
My PayerController store method code is shown below
public function store(CreatePayerRequest $request)
{
$input = $request->all();
$payer = $this->payerRepository->create($input);
{
$spouses = new Spouse();
$input = $request->all();
foreach($spouses as $spouse){
$spouses->user_id = Auth::user()->id;
$spouses->payer_id = 1;
$spouses->spouse_occupation='NA';
$spouses->spouse_name = $input['spouse_name'];
$spouses->spouse_dob = $input['spouse_dob'];
$spouses->spouse_emplbiz_add = $input['spouse_emplbiz_add'];
$spouses->spose_income = $input['spose_income'];
$spouses->save();
}
Flash::error('Taxpayers record not saved');
return redirect(route('payers.index'));
Note that i tried moving the line
$spouses = new Spouse();
into the foreach loop but it gave me Undefined variable: spouses
Your foreach loop inside the php script is looping over $spouses, but this variable only holds 1 freshly created Spouse.
Your code is hard to read, since inside your foreach loop you are again using $spouses but with a different meaning.
Your foreach loop should loop over the spouses that come in from your form, so it should loop over for example $request->input('spouce_name') or something.
But this requires array data to come in and I think your form data is not coming in correctly, since inside your blade you create a foreach loop, but you create multiple form elements with the same name. Your form will then only use the last value. If you change the input names to array values, it should work, so change spouce_name to spouce_name[]
I am listing many rows in a table and I AM trying to edit them with a drop down menu that exists in each row. The code below is fine but it will store only the last (S_Rank) value (which is the column I want to change) what would be the best way to get each row input. I know the issue that the form is not an array, what would be the way to make it an array
My view
{!! Form::open(['action' => 'AbstractsController#UpdateRank' , 'method' => 'post' ]) !!}
<table id="myTable" class ="table table-striped">
<thead>
<td><h4>Student Name</h4></td>
<td><h4>Student Rank</h4></td>
</thead>
#foreach($applications as $application)
<tbody>
<tr>
<td><h5>{{$application->Student_Name}}</h5></td>
<td><h5>
{{Form::select('Ranking' ,$ranks, ['class' => 'form-control', 'placeholder' =>$application->S_Rank] )}}
{{Form::hidden('Student_ids[]', $application->S_ID)}}
</h5></td>
</tr>
#endforeach
</tbody>
</table>
{{Form::Submit('Save New Ranking',['class' => 'btn btn-primary'])}}
{!! Form::close() !!}
My controller
foreach(request('Student_ids') as $S_ID){
$application = Application::where('S_ID' , $S_ID)->get();
$application->S_Rank = $request-> input('Ranking');
$application->save();}
I am trying to update each row with the inputted value from each dropdown menu
I think you already answer yourselve. I think what you need is to change your $ranks var to $ranks[] because you are actually only taking the last value they chose in your select, that way, you are storing your ranks in a one dimenssion array that should correspont with your Student_ids[] hidden array
If you want to update the ranking per application, you'll need to know which ranking value goes to which application. Assuming S_ID is a unique identifier for Application, you could do something like this in your view:
<h5>
{{Form::select('Ranking[' . $application->S_ID . ']' ,$ranks, ['class' => 'form-control', 'placeholder' =>$application->S_Rank] )}}
</h5>
Then in your controller:
foreach(request('Ranking') as $S_ID => $rank){
$application = Application::where('S_ID' , $S_ID)->first();
$application->S_Rank = $rank;
$application->save();}
I asked this question before but there was no response on it. So apologies. I'm asking it again
I have foreach loop here and I'm passing values from database in view to controller via GET route function. At first I click and send key from database to controller, then correct key is passed. By clicking second time on <a> tag previous key(value) is passed. I do not want to do this. I want to pass current key(value) from database. I spend 2 days in resolving this issue but failed. Do anyone know how can I resolve this issue?
Here is my code:
shopReq.blade.php:
#foreach($products as $key => $value)
<div href="{{route('special',$value->toCity)}}" id="tayyab"class="recent-container" data-toggle="modal" data-target="#shopping-request-modal">
<h1>I'm opening modal and sending value to Controller.<h1>
</div>
#endforeach
#include('modal')
web.php:
Route::get('special/{id}', [
'uses' => 'UserController#shopReq1',
'as' => 'special'
]);
UserController.php:
public function shopReq1($id){
echo $id;
$products = DB::table('shippingitems')->get();
return view('modal',compact('products'));
}
#foreach($products as $key => $value)
<div href="{{route('special',[ 'id' => $value->toCity ])}}" id="tayyab"class="recent-container" data-toggle="modal" data-target="#shopping-request-modal">
<h1>I'm opening modal and sending value to Controller.<h1>
</div>
#endforeach
I've got a problem in Laravel. I have passed my whole table to my view like this from my controller:
$usersTable = DB::table('users')->get();
return view('users')->with('users', $usersTable);
In a foreach loop I can perfectly get each of the values like this in my view:
#foreach($users as $user => $value)
<div class="projectBox">
<br><span class="projectBoxName">{{ $value->name }}</span>
#php
echo Form::image('/images/edit.png', "",['class' => "editUserBtn", 'userId' => $value->id]);
#endphp
<br><span class="projectBoxSmallText projectBoxEmail">{{ $value->email }}</span>
<br><span class="projectBoxSmallText projectBoxId">ID: {{ $value->id }}</span>
<br><span class="projectBoxSmallText projectBoxProjects">Currently no projects</span>
</div>
#endforeach
But I also need to access these values outside my foreach loop, how can I do that?
echo Form::text('email', "$users->$value->email", array('placeholder' => "Email"));
Ain't working...
This gives my the whole object in this form
[{"id":"1","name":"Administrator","email":"admin#mail.com","password":"$2y$10$Re3Ahf.SwU5vj4UvtU5Dy.jxaZMsUNC2WhuJMwsNy9gu6TST4PuRG","remember_token":null}]
How to get only the email? I also tried using indexes, but those weren't working.
Thanks!
Edit:
Full situation:
I have a list of users with their extra information (mail, tel,...). In those user-boxes there is a button which says 'edit user' when I click that a modal opens giving the current mail and tel. So I can't say in my controller WHO's mailaddress to return because I only know that at the moment the user clicks a client-side button.
Images: http://imgur.com/a/krDrY
(Edit button is that small circle with three dots).
To access a collection without using loop, you should use collection methods:
$users = User::get();
$users->where('name', 'John Smith')->first()->email
This will not create any additional queries since you've already eager loaded data.
If you want to load just one user, use first() instead of get():
$users = User::first();
If you'll use get() and then [0] or first() like some guys recommend here, you'll load all users data into the memory for each request which will overload your server.
Also, using indexes to access data (like $users[4]['email']) is a bad practice. Avoid it if possible.
You need to add as first element by adding [0]
echo Form::text('email', $users[0]->email, array('placeholder' => "Email"));
I suggest use ->first() instead of ->get() to get single object. And remove loop and use anywhere you want.
You are using a collection of users to get the first user's email, you do
$users->first()->email;
Looks like it's coming in as JSON. Try json_decode($data) and $data->email to get that attribute.
I am just wondering if i could ask a fairly simple question about radio buttons and Laravel as the googlebox isnt co-operating. My code is thus:
{{ Form::open(array('url'=>'users/create', 'method' => 'post')) }}
<tbody>
<label><span> </span>{{ Form::submit('Approve/Decline')}}</label>
#foreach($users as $user)
<tr>
<td>{{{$user->firstname}}}</a></td>
<td>{{{$user->secondname}}}</a></td>
<td>{{{$user->address}}}</a></td>
<td>{{{$user->city}}}</a></td>
<td>{{{$user->phone}}}</a></td>
<td>{{{$user->id}}}</td>
<td>{{{$user->username}}}</a></td>
<td>{{{$user->email}}}</tds>
<td>{{{$user->type}}}</a></td>
<td>{{Form::radio('Membership[]', 'approve')}}</a></td>
<td>{{Form::radio('Membership[]', 'decline')}}</a></td>
</tr>
#endforeach
</tbody>
{{ Form::close() }}
A simple form with my two text boxes at the end there. This turns on fine in the browser but once i check one radio button the others deselect which would be fine in this order:
O O
but since its in a loop, there are many rows of O O and i can only choose one out of all of the different rows. I would imagine I would need to group each two together somehow dynamically but I'm unsure. All aid appreciated.
Probably you'll need to set a different name for each of your checkboxes/radio buttons:
<td>{{Form::radio("Membership[".$user->id."]", 'approve')}}</a></td>
<td>{{Form::radio("Membership[".$user->id."]", 'decline')}}</a></td>
To get your values in your controller you just have to:
dd( Input::get('Membership')[$user->id] );
In return you should get
approve
or
decline
Note that for this to work this way I removed the quotes from
"Membership[".$user->id."]"
Here are two routes I used to test it:
The form:
Route::any('test', function() {
return Form::open(array('url' => 'radio', 'method' => 'post')) .
Form::radio("Membership[1]", 'approve') .
Form::radio("Membership[1]", 'decline') .
Form::submit('send') .
Form::close();
});
The result:
Route::any('radio', function() {
dd( Input::get('Membership')[1] );
});