How to pluck name from related model in select box - laravel

I am trying to show the name of the company but it is a related Model
A company has Stocks
A Stock belongs to a Company
I have tried this:
$userStocks = \Auth::user()->stocks->pluck('type', 'id')->toArray();
{!! Form::select('name', $userStocks, null, ['class' => 'form-control', 'placeholder' => 'Pick Your Stock']) !!}
But I don't know how can I get the name of the company which owns that stock?

Load the data and create an array for the Form::select() manually by using the map() helper. Something like:
$stocks = Stock::where('user_id', auth()->user()->id)
->with('company')
->get()
->map(function($i) {
return [$i->id => $i->type.' - '.$i->company->name];
});

Related

Laravel - Iterating pivot data (Property does not exist on this collection instance)

I have a many-to-many relationship between Order and Product
Product.php
public function orders()
{
return $this->belongsToMany(Order::class)
->withTimestamps()
->withPivot('qty');
}
Order.php
public function products()
{
return $this->belongsToMany(Product::class)
->withTimestamps()
->withPivot('qty');
}
Now whenever I try to utilize an iteration in a view (in this case I am just trying to show the form which iterates through all available Products, I always receive the error...
Property [products] does not exist on this collection instance.
create.blade.php
#foreach ($products->orders as $product)
# Order inputs are here
{{ Form::text('qty', $product->pivot->qty, [
'type' => 'tel',
'min' => 0,
'max' => 20,
'step' => 1,
'placeholder' => '0',
'class' => 'meal'
]) }}
#endforeach
I have also attempted #foreach ($products->orders as $product) and both approaches give me that same error.
I have attempted many different ways in my Controller to fix this error, here is my last attempt:
OrderControlller.php
public function create()
{
$user = Auth::user();
$products = Product::get();
$orders = $user->orders;
return view('orders.create', compact('products', 'orders', 'user'));
}
UPDATE
#alan's answer is correct, I am sure, however...
I am still getting "Property [pivot] does not exist on this collection instance" whenever I try to run an iteration.
The concept of an iteration inside of an iteration in this instance is confusing for me.
I cannot visualize how Laravel is handling the pivot connection. In tinker when I load up just the Product table, there is no qty column. (This makes sense because that is on the pivot table). This also explains this new error.
Should I be doing something in the vein of this? :
changed create.blade.php
#foreach ($products as $product)
{{ Form::text('qty', $product->orders->pivot->qty }}
OrderController.php
$user = Auth::user();
$orders = $user->orders;
$products= []; #pass products to view as an array
$p = $orders->products; #this relationship brings in pivot data?
foreach ($p as $orders) {
#would I then somehow pass just this qty here?
}
Problem is I am always getting a "Property does not exist" error, be it with 'products', 'orders', or 'pivot'.
This should work. You were trying to access the orders property on the $products variable, which is a Laravel Collection (get method on model returns a collection). So instead of doing that you just iterate through the products and access the pivot table from the individual product model.
#foreach ($products as $product)
# Order inputs are here
{{ Form::text('qty', $product->orders->pivot->qty, [
'type' => 'tel',
'min' => 0,
'max' => 20,
'step' => 1,
'placeholder' => '0',
'class' => 'meal'
]) }}
#endforeach
Update:
Actually that makes sense. A record on the pivot table defines an association between an order and a product. So for you to access a record in the pivot table you must access the product or order from its relationship. This is what I would do.
OrderController.php
$user = Auth::user();
$user->load("orders.products"); // eager load relationship to avoid N+1 problem
$orders = $user->orders;
return view('orders.create', compact('orders', 'user'));
create.blade.php
#foreach ($orders as $order)
#foreach ($order->products as $product)
{{ Form::text('qty', $product->pivot->qty, [
'type' => 'tel',
'min' => 0,
'max' => 20,
'step' => 1,
'placeholder' => '0',
'class' => 'meal'
]) }}
#endforeach
#endforeach
Some resources:
Eager loading
Many to Many relations

Pass user id through select box list laravel

I want to pass the selected user id to controller from select box.How can I achieve it?
{!! route('approve', ['id' => $user->id]) !!}
In select box,
{{ Form::select('Actions', [
'approve' => 'Approve',
'decline' => 'Decline']
) }}
My resulto to be like this,
First of all you'll need an input for selecting users. For example I got a list of users with their username and id here :
$users= \App\Users::pluck('username','id');
after sending it to the view, you can use an input for selecting user :
{!! Form::select('user_id', $users,'0', ['class' => 'form-control']) !!}
That's it. Now you can select the user and get data as $_POST['user_id'] or $_GET['user_id'] in the action. gl.

Laravel - HasMany CRUD - Update

I need some help, please,
I have two tables: carriers and sell
Carrier CRUD is working. Sell CRUD is also working, except Update method.
In order to update, i need carrierId and sell id, right?
This is my CarrierSellController:
And this is my carriers/sell/edit.blade.php
The model binding is working:
Form action has /edit at the end of the url. It's oke?
If i hit submit button, i get this error:
Try this one
{!! Form::model($sell,['url'=>url('carriers/'.$sell->carrier->id.'/sell/'.$sell->id),'method'=>'patch']) !!}
and in the Sell model add
public function carrier()
{
return $this->belongsTo(Carrier::class);
}
make sure the method is PUT
add this to your form
{{ method_field('put') }}
Why don't you if you want to be absolutely sure just try declaring the route yourself like:
Route::put('carriers/{carrierId}/sell/{id}', [ 'as' => 'carriers.sell.update', 'uses' => 'CarrierSellController#update' ]);
And then in your view have this:
{!! Form::model($sell, ['method' => 'PUT', 'route' => ['carriers.sell.update', 'carrierId' => $sell->carrier->id, 'id' => $sell->id]) !!}

Laravel having trouble sending decimals

I have a blade template form that takes a price
{!!Form::open(array('method'=>'POST','route'=>array('order.store'))) !!}
<div class="form-group">
{!! Form::label('price', 'Price:', ['class' => 'control-label']) !!}
{!! Form::number('price', null, ['class' => 'form-control']) !!}
</div>
{!! Form::submit('Submit Order', ['class' => 'btn btn-primary']) !!}
{!! Form::close() !!}
The controller takes price and send it to email:
class OrderController extends Controller
{
public function store()
{
$data=Input::all();
//Validation rules
$rules = array (
'price' => 'required|regex:/[\d]{2}.[\d]{2}/',
);
$validator = Validator::make ($data, $rules);
//If everything is correct than run passes.
if ($validator -> passes()){
//Send email using Laravel send function
Mail::send('emails.order_received', $data, function($msg) use ($data)
{
//email 'From' field: Get users email add and name
$msg->from($data['email'] , $data['owner']);
//email 'To' field: change this to emails that you want to be notified.
$msg->to('on#dx.com', 'Rn')->subject('New Order');
});
return Redirect::route('order.index')->with('flash_notice', 'Thank you');
}
else
{
//return contact form with errors
return Redirect::route('order.index')->withErrors($validator)->with('flash_error', 'This is not how one shops');
}
}
}
The table is passed to a email template.
<?php
//get the first name
$item = Input::get('item');
$manufacturer = Input::get ('manufacturer');
$price = Input::get('price');
$quantity = Input::get ('quantity');
$product_code = Input::get ('product_code');
$owner = Input::get ('owner');
$email = Input::get("email");
$created_at = Input::get("date");
?>
When ever I try to add a price i.e. (3.65) the blade form continues to return an error message for an integer. My migration takes price as a decimal(2,2) I can't understand why my form is throwing errors. Any help would be much appreciated.
P.S. Other than the regex rule I have tried float and decimal. Now if I try entering 2 instead of 02.00 with the regex rule it throws an error based on the regex. However if I try adhering to the regex rule it wants an integer (error says between X and Y).
Thanks
M
First, you'll definitely want to use the numeric rule for your validation.
Secondly, you are using the HTML5 input field number which by default only accepts integers, not floats.
If you want it to also accept floats and therefore not trigger the browser built in validation change your code to the following:
{!! Form::number('price', null, ['class' => 'form-control', 'step' => 'any']) !!}
Or, of course, you could just use an text input and do the inline validation yourself.

Update / post database colum in Laravel

I have a general question.
I have a search form in larvel which returns results form the database.
in these i have an input field to enter a price if price is == 0
what my problem is when i enter price and submit it returns to the search page without my previous search results i.e it doesn't refresh the same page with results and the newly updated field etc.
form in view
{{ Form::open(['action' => 'price_input'])->with($gyms) }}
{{ Form::text('enter_price', null, ['class' => 'form-control', 'size' => '50', 'id' => 'enter_price', 'autocomplete' => 'on', 'runat' => 'server', 'required' => 'required', 'placeholder' => 'enter price!', 'style' => 'margin-bottom: 0px!important;']) }}
{{ Form::submit('Search', ['class' => 'btn btn- primary', 'style' => 'margin-left: 10px;']) }}
{{ Form::close() }}
route
Route::post('/', [ //not used yet
'as' => 'price_input',
'uses' => 'PagesController#priceUpdate'
]);
Model
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
return Redirect::back()->withInput();
}
Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gym);
}
not bothering with model as that works fine.
any ideas guys?
Thanks for your answer,
i have changed my controller to this
public function priceUpdate($gyms)
{
if (Input::has('enter_price'))
{
$price = Input::get('enter_price');
Gym::updatePrice($price);
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
}
but when i run it i get
Missing argument 1 for PagesController::priceUpdate()
with the $gyms being passed into the method.
if i take out the $gyms that goes away but not sure if its still being passed with session or not, sorry im a novice.
orignally i had a search box which when run returns
return View::make('pages.home')->with($data);
what is the difference between that and
return View::make('pages.home')->with($data);
when i do the above line it returns to the search page with no search options from before update the form, any ideas?
Currently, you are just retrieving an existing session and doing nothing with it. You need to do:
$gyms = Session::get('gyms');
return Redirect::to('pages.home') ->with('gyms', $gyms);
Or
return Redirect::to('pages.home')->with('gyms', Session::get('gyms'));
Then you can access the gyms in the view with $gyms.
Alternatively, you could access Session::get('gyms') in the view as well.
Also, not sure if it's just the way you pasted it here, but you have an unnecessary space before the ->with. Just wanted to make sure that's not part of the issue, too!

Resources