Laravel: Getting the Value of a Field In a Table - php

What I'm trying to do is get the available credits from the users table and 'credits' field and get the price of the current item in the foreach loop which is the 'normalprice' field in the 'items' table.
When a user fills in the amount he wants to put toward the 'normalprice' of an item, i want to subtract from the number in his 'credits' field, and create a new variable for 'This is the price of the item after you've put credits toward it' and display it.
The users table and items table are on a many-to-many relationship, and i've been able to display a user item by doing
$user->item
What i've done is bellow is wrong, because 'normalprice' in '$item->normalprice;' is not a property. I'm trying to find out how I can make $itemprice equal the value of 'normalprice' in the current #foreach ($user->items as $item)
Controller:
public function allocateCredit(){
$validator = Validator::make(Input::all(),
array(
'puttoward' => 'Integer',
));
$user = Auth::user();
$items = Item::all();
$userItems = Auth::user()->items;
$itemprice = $item->normalprice;
$available = $user->credits;
$goodtogo = ($available > $itemprice) ? TRUE : FALSE;
if($goodtogo === true){
$howmuch = Input::get('puttoward');
$newavailable = $howmuch - $available;
$itembalance = $itemprice - $howmuch;
$user->credits = $newavailable;
}
if($user->save()){
return Redirect::route('account')->with('global', 'Success.');
}
}
View:
#foreach ($user->items as $item)
<div class="sep">
<div class="nameIt">
{{ $item->name }}
<form action="{{ URL::route('allocate-credits-post') }}" method="post" role="form">
<div class="form-group">
<label for="exampleInputPassword1">Allocate credits</label>
<input type="intiger" class="form-control" name="puttoward" placeholder="$0.00">
</div>
<button type="submit" class="btn btn-default">Submit</button>
{{ Form::token() }}
</form>

Since you're using a form submission to call your Controller, why don't you populate the $item->normalprice into the form as hidden type like:
<input type="hidden" name="NormalPrice" value="{{$item->normalprice}}">
Then access the value in your controller with Input::get('NormalPrice')
or if that is not desired for security reason, then you can populate the $item->id instead and find out the price for that ID in your controller.

Related

Laravel: How to get ID from Papers Table to Store in Bookmarks Table

I can't get the PaperID to store into my Bookmarks DB
here is my controller for the bookmark store function
public function store(Request $request)
{
$request->validate([
'BookmarkName' => 'required',
]);
$paper = DB::table('papers')
->where('PaperID', '=', $request->paper_id)
->value('PaperID');
$bm = new Bookmarks();
$bm->BookmarkName=$request->BookmarkName;
$bm->paper_id = $paper;
$bm->save();
return redirect()->back()->with('success','Bookmark Added');
}
here is the form to call the function
<form class="bookmarkInput" action="{{ route('Bookmarks')}} " method="POST" >
#csrf
<div class="group">
<input class="inputInfo" type="text" name="BookmarkName" required>
<span class="highlight"></span>
<span class="bar"></span>
<label class="infoLabel">Bookmark Name</label>
</div>
<br>
<br>
<button class="redBtn" type="submit">Add</button>
</form>
here is the route for it
Route::post('/Bookmarked', [App\Http\Controllers\BookmarkController::class, 'store'])->name('Bookmarks');
I do not know why it isn't getting the ID calling papers DB seems good but it doesn't want to get the current ID of the paper I want to bookmark
You are not passing paper_id from form.
That's why your ->where('PaperID', '=', $request->paper_id)
don't have value of paper_id.
you can pass paper_id from form by using hidden input field.
<input type="hidden" name="paper_id" value = {{ $paper_id }}>
Remember to pass paper_id variable containg paper_id value to the blade having form.
Also add ->first() before ->value('PaperID').

Laravel search only exact match

Newbie to PHP/Laravel here.
Expected behavior
I want to use a form action to get data from database by inserting the id, something like the couriers tracking id. Until now it is working, but i want to show the results only if that id exist on the database
Code
Controller
public function search(Request $request)
{
$request->validate([
'query' => 'required|min:10|max:10',
]);
$query = $request->input('id');
$orders = Order::where('id','LIKE',"%$query%")->get();
$name = $request->input('id', '$id');
return view('order-details', compact('orders'));
order.blade
<form action="{{ route('order-details') }}" method="GET" class="order-form">
<div class="row">
<div class="col-lg-12">
<input type="text" placeholder="Track Order ID" name="query" id="query" value="{{ request()->input('query') }}">
</div>
<div class="col-lg-12">
<button type="submit">Submit Now</button>
</div>
</div>
</form>
#if(count($errors) > 0)
<ul>
#foreach ($errors->all() as $error)
<li>{{$error}}</li>
#endforeach
</ul>
#endif
route
Route::get('order', 'OrderController#index')->name('order');
Route::get('order-detail', 'OrderController#search')->name('order-details');
I think your problem is you are using a like condition, like is notoriusly flakey on numbers.
$query = $request->input('id') ?? -1;
Order::where('id', $query)->get();
Where on only id, will only returns rows where id exists.
You are using a wrong query.
$orders = Order::where('id','LIKE',"%$query%")->get();
The like operator will get anything like that query and not only.
You just need to remove the like operator to get only orders that match the exact id.
$orders = Order::where('id',$query)->get();
You can also add the exists rule:
The field under validation must exist on a given database table.
$request->validate([
'query' => 'exists:orders,id',
]);

How to resolve PHP Laravel Sql Insert error?

When I press the buy button I get this error
QueryException in Connection.php line 729:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'qty' cannot be null (SQL: insert into orders (user_id, product_id, qty, updated_at, created_at) values (3, 1, , 2018-10-06 20:44:27, 2018-10-06 20:44:27))
first of all, I'm a beginner so I'm still learning and I do not know if some of this is correct, all I want is when I press the buy button it will display the form and I will type the quantity then submit and my quantity will increase and the products inventory will decrease and if I deleted my order, The products will increase again (I did this and I think it will work) and the user can update his quantity and if someone ordered something the seller cannot delete it, only update his inventory as same as the buy button way and the form, and if the users ordered all products it will display (out of stock) with a dead link button, I am training, It is not homework and I do not know how to write all functions..
this is the Buy button
<li><span>Buy</span></li>
which should pop up the next form when I press it,
this is my form code for the buy button
<form method="POST" action="/add_order/{{ $product['id'] }}" class="klaviyo_subscription_form" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="g" value="LIST_ID">
<div class="klaviyo_fieldset">
<p class="klaviyo_header">Please define quantity you need, then order it.</p>
</div>
<div class="klaviyo_fieldset">
<div class="klaviyo_field_group{{ $errors->has('qty') ? ' has-error' : '' }}">
<label for="k_id_modal_$email" style="display: block; text-align:center">Quantity</label>
<input type="number" id="k_id_modal_$email" name="qty" style="display: block; margin:auto">
#if ($errors->has('qty'))
<span class="help-block">
<strong>{{ $errors->first('qty') }}</strong>
</span>
#endif
</div>
</div>
<div class="klaviyo_fine_print"></div>
<div class="klaviyo_form_actions">
<button type="submit" class="klaviyo_submit_button">
<span>Order Now</span>
</button>
</div>
<div class="klaviyo_below_submit" ></div>
</form>
OrderController
public function store(Request $request, $id)
{
$product = Product::find($id);
$order = new Order();
$order->user_id = Auth::user()->id;
$order->product_id = $id;
$order->qty = $request->get('qty');
$product->inv = $product->inv - $order->qty;
$order->save();
$product->save();
return redirect('/');
}
thanks for reading :D
Request is object and not array! You need to use method to get request value. Check updated code
public function store(Request $request, $id)
{
$product = Product::find($id);
$order = new Order();
$order->user_id = Auth::user()->id;
$order->product_id = $id;
$order->qty = $request->get('qty');
$product->inv = $product->inv - $order->qty;
$order->save();
$product->save();
return redirect('/');
}
This will work if logic for passing "qty" to request is correct. You can do dump of request and die inside store function, to make sure about this fact.
Your Problem is you sending the data with the POST method.
But you access the data from the GET method.
OrderController
$order->qty = $request->get('qty'); // this is where you are wrong.
Change this either,
$order->qty = $request->post('qty');
or,
$order->qty = $request->qty // this is the preferred approach.
In your database table filed "qty" set default value null or as default 0.
and write
$order->qty = $request->qty;
it will work fine

How to display in the view edit-add.blade.php only some tables in Voyager?

It's my first time using blade and I'm a little confused with this. I need to show a form like what it comes with the default edit-add view in Voyager, but I need to display some inputs based on roles. I am filtering by the current user that is logged in and that is working fine, but I need to hide/display some inputs of the form based on that.
How can I accomplish this in the blade view?
Here is how Voyager take the data in the blade view:
#php
$dataTypeRows = $dataType->{(isset($dataTypeContent->id) ? 'editRows' :'addRows' )};
#endphp
#foreach($dataTypeRows as $row)
<!-- GET THE DISPLAY OPTIONS -->
#php
$options = json_decode($row->details);
$display_options = isset($options->display) ? $options->display : NULL;
#endphp
#if ($options && isset($options->formfields_custom))
#include('voyager::formfields.custom.' . $options->formfields_custom)
#else
<div class="form-group #if($row->type == 'hidden') hidden #endif #if(isset($display_options->width)){{ 'col-md-' . $display_options->width }}#else{{ '' }}#endif" #if(isset($display_options->id)){{ "id=$display_options->id" }}#endif>
{{ $row->slugify }}
<label for="name">{{ $row->display_name }}</label>
#include('voyager::multilingual.input-hidden-bread-edit-add')
#if($row->type == 'relationship')
#include('voyager::formfields.relationship')
#else
{!! app('voyager')->formField($row, $dataType, $dataTypeContent) !!}
#endif
#foreach (app('voyager')->afterFormFields($row, $dataType, $dataTypeContent) as $after)
{!! $after->handle($row, $dataType, $dataTypeContent) !!}
#endforeach
</div>
#endif
#endforeach
If my table 'example' contains: id, name, address and phone. How do I display in this view form only inputs for name and address?
Thanks in advance.
You should try this:
public function edit(Request $request, $id)
{
$user = Example::find($id);
return view(‘viewname’,compact(‘user’));
}
edit-add.blade.php
<input type = “text” name=”name” value=”#if(isset($user->name)){{ old('name', $user->name) }}#else{{old('name')}}#endif”>
<input type = “text” name=”name” value=”#if(isset($user->address)){{ old('address', $user->address) }}#else{{old('address')}}#endif”>
i cant understand what do you mean but
for showing a value in input in a view first you should send the value to view for example in controller you have :
public function test()
{
.....
return view('myView',compact('user'));
}
then in your view :
<input type="text" value"{{$user->address}}">
<input type="text" value"{{$user->first_name}}">
You can edit it from ADMIN interface without using any code
Just go to the settings menu and click BREAD

Yii check if the record already exsists in database table

I've got 2 models (producten and voorraad), and one controller (producten).
So i've build a form inside the producten CRUD (create/update).
This is a custom form:
<div class="form-group">
<span class='btn btn-default addOption'>Optie toevoegen</span>
</div>
<div class='opties'>
</div>
<div class="form-group">
Verkrijgbaar als backorder?
<select name="backorder">
<option value="1">Ja</option>
<option value="0">Nee</option>
</select>
</div>
This is very easy. If you press on the button addOption, it will add a few form inputs.
Now when the form is being saved (here the trouble begins), it will always add the data from the form to the database. But i don't want that. I want the data to be checked first, if it already exsists, if so, it has to be replaced and not added again.
Is there a yii function for that, or how do I do this?
ProductenController piece:
foreach($_POST as $key => $value){
if(substr($key, 0,5) == 'maat_'){
$index_expl = explode('_',$key);
$index = $index_expl['1'];
$aantal = $_POST['aantal_'.$index];
$maten = explode(',',$value);
foreach($maten as $maat_key => $maat){
$kleuren = explode(',',$_POST['kleur_'.$index]);
foreach($kleuren as $kleur_key => $kleur){
$voorraad = new Voorraad();
$voorraad->product_id = $model->id;
$voorraad->maat = $maat;
$voorraad->kleur = $kleur;
$voorraad->aantal = $aantal;
$voorraad->backorder = (int)$_POST['backorder'];
$voorraad->save();
}
}
}
}
Replace the following :
$voorraad = new Voorraad();
with :
$voorraad = Voorraad::model()->findByPk($model->id); // assuming id is primary key, you can also use `findByAttributes`
if($voorraad == null) $voorraad = new Voorraad();
$voorraad->save(); is also used for updating the record.
just put a hidden input field in your form:
<div class="form-group hidden">
<input name="id" value="<?php echo YOURID;?>"/>
</div>
check if id exist in your server with empty(),if not just add;if exist then update.

Categories