Laravel - Calculate minimum value from multiple fields in controller - laravel

I want to calculate the minimum value from a collection of form fields.
I have one-to-many relationship, where one shop can have many items ans that is working fine without any errors.
My form
<form action="{{ route('form_submit') }}" method="post">
#csrf
<h3>Item 1</h3>
<input type="text" name="item[]">
<input type="text" name="price[]">
//Like this I can add many fields
<input type="submit">
</form>
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//I tried
$price_group = collect($item->price)->where('shop_id', $shop->id);
$min_price = min($price_group);
$item->save();
}
Route
Route::post('/{id}', 'Controller#store')->name('form_submit');
But it does not calculate the minimum price. When I dd($min_price), its total blank. What am I missing here?

I think is just...
$items = Item::where('shop_id', $shop->id)->get();
$min = $items->min('price');
And take a look on eager loading for relations. It's much better.

I solved this by #Jonas's solution. And I make this my answer.
Controller
public function store(Request $request, $id){
$shop = Shop::findorfail($id);
$item = Item::where('shop_id', $shop->id)->get(); //working fine
$i=0;
$price = request('price')
foreach( $items as $item)
$item->price = request('price')[$i];
$i++;
//This works
$min_price = min(request('price'));
$item->save();
}

Related

Why am i getting all my products and not only one in my view?

In my detail-tickets view i want to show all the data of a loaded product with all its fields, but when i want to view the detail i get all my products and no only the one product that belongs to that ticket.
So the following is how im storing my tickets:
public function store(Request $request){
/*dd($request->all());*/
$ticket = new Ticket();
if($request->file('file')){
$file = $request->file('file');
$filename = time().'.'.$file->getClientOriginalName();
$request->file->move('storage/', $filename);
$ticket->file = $filename;
}
/*$ticket->cuenta_id = $request->cuenta_id;*/
$ticket->contact_id = $request->contact_id;
$ticket->statusTicket_id = $request->statusTicket_id;
$ticket->typeTicket_id = $request->typeTicket_id;
$ticket->idOwner = Auth::user()->id;
$ticket->product_id = $request->product_id;
$ticket->serial_number = $request->serial_number;
$ticket->accesories = $request->accesories;
$ticket->entry = Carbon::parse ( $request->entry)->toDateString();
$ticket->deliver = Carbon::parse ($request->deliver)->toDateString();
$ticket->save();
Session::flash('success');
return redirect()->route('tickets.view');
}
And this is my detail method:
public function detail($id){
$detailData = Ticket::find($id);
$detailData['contacts'] = Contact::all();
$detailData['products'] = Product::all();
$detailData['ptypes'] = Ptype::all();
$detailData['brands'] = Brand::all();
$detailData['models'] = ModelP::all();
return view('backend.ticket.detail-ticket', compact('detailData'));
}
So in my view im passing my product as the following:
#foreach($detailData['products'] as $product)
<div class="form-group col-md-3">
<label for="product_id">Producto</label>
<input type="text" name="product_id" value="{{$product->ptype->productType . ", " . $product->marca->brandName . " " . $product->modelo->modelName}}" class="form-control" readonly>
</div>
#endforeach
And this is an image of how it is bringing me data:
There should be only one product but instead i have all my product list.
Any idea what im doing wrong while passing the data to my view?
in this line:
$detailData['products'] = Product::all();
you are loading All products not only the wanted product ...
it should be:
$detailData['products'] = Product::find($detailData->product_id);

How to use session with id?

I have an order and I want to after save, get in session current id of order for next page reports.
use Session;
public function store(Request $request)
{
$order = new Order($request->all());
$order->user_id = auth()->user()->id;
$order->title = $request->title;
$order->body = $request->body;
$order->id = $request->session()->get('id');
$order->description = $request->description;
$order->save();
session(['order_id' => $order_id]);
return redirect()->route('reports.index')->with('order_id', $request->id);
}
In notes page has a input hidden for get session of article id.
<input type="hidden" class="form-control" value="{{ Session::get('order_id') }}" name="id" id="id">
But I see input hidden. It is blank . "".
I'm confused here
session(['order_id' => $order_id]);
return redirect()->route('reports.index')->with('order_id', $request->id);
when you're returning something with "->with()" it stores in session so why use session() ? and $order_id is not defined in your method.
and best way to put something in session is like this
Session::put('order_id');
I think if you do this
->with('order_id', $order->id); // You will get the current order id created

How to update a product in Laravel 5.8

I have a product that I want to edit. Please see the following code.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $request->file('image')->getClientOriginalName();
}
$product->update();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
product.blade.php
<form class="form-horizontal" action="{{ route('products.update', $product->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
.
.
.
Everything changes except the image. I tried it, but, I did not succeed. What's the solution? I want to update the image in the database.
OK, I go to database now, I changed in image to picture, then I go my project, and I tested this again.
But it did not event for me.
I changed
public function update(ProductRequest $request, Product $product)
To
public function update(Request $request, Product $product)
To update a model, you should retrieve it, set any attributes you wish to update, and then call the save method. See the updates section in the documentation.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $request->file('image')->getClientOriginalName();
}
$product->save();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
Update 1
Assuming you have debugged the above and $request->file('image')->getClientOriginalName() is returning the expected value, it's possible that you are using field whitelisting on your model and haven't added the image field to the whitelist. Make sure that image is in the $fillable array on your model.
class Product extends Model
{
protected $fillable = [
'user_id',
'title',
'body',
'price',
...
'image'
];
Update 2
If $request->file('image') is returning null then that would suggest your form is not submitting the files. Ensure your <form> element has the enctype="multipart/form-data" attribute included in the tag.
Update 3
If your already including the required enctype="multipart/form-data" tags in the <form> element then I would suggest doing the following.
Place dd($request->all()); at the top of your update(ProductRequest $request, Product $product) method. Post the form and check the output.
If the file is not included in the output, change from using ProductRequest $request to the default Request $request (Illuminate\Http\Request) and try it again. There could be something in your ProductRequest class that is causing a problem.
As a small critique, you could improve your code in the following ways.
・Use hasFile() instead of has().
・Use $product-image = $filename instead of $product->image = $request->file('image')->getClientOriginalName();.
public function update(ProductRequest $request, Product $product)
{
$product->user_id = auth()->user()->id;
$product->title = $request->title;
$product->body = $request->body;
$product->price = $request->price;
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/products'), $filename);
$product->image = $filename;
}
$product->save();
$product->categories()->sync($request->category);
return redirect()->route('products.index');
}
make sure your has
enctype="multipart/form-data"
property

Trying to get a variable pagination to show me 3 different types of paginations

Here is my Index:
<div class="page-sizer">
<a class="page numbers" href="{{$references->pagination(10)}}">10</a>
<a class="page numbers" href="{{$references->pagination(30)}}">30</a>
<a class="page numbers" href="{{$references->pagination(100)}}">100</a>
<button href="qweqwe.qweqwe" class="btn btn-info float-right>112e1e1e1e"></button>
</div>
My AdminreferenceController:
public function index()
{
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate(50);
return view('admin.reference.index', ['references' => $references]);
}
and my Lengthawarepaginator:
public function __construct($items, $total, $perPage, $currentPage = null, array $options = [])
{
foreach ($options as $key => $value) {
$this->{$key} = $value;
}
$this->total = $total;
$this->perPage = $perPage;
$this->lastPage = max((int) ceil($total / $perPage), 1);
$this->path = $this->path !== '/' ? rtrim($this->path, '/') : $this->path;
$this->currentPage = $this->setCurrentPage($currentPage, $this->pageName);
$this->items = $items instanceof Collection ? $items : Collection::make($items);
}
. i currently get the error Method Illuminate\Database\Eloquent\Collection::pagination does not exist.
I want to have 3 buttons that show 3 different kinds of paginations like in stackoverflow in the search bar at the bottom.
You are calling pagination in collection try like this
first you need to include the DB class before class deceleration
use Illuminate\Support\Facades\DB;
Then change the query like this
$references = DB::table('reference')->orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate(5o);
return view('admin.reference.index', ['references' => $references]);
In you view you need to access like this
{{ $references->links() }}
https://laravel.com/docs/5.7/pagination
i have currently changed the pagination completly. i wrote a url with
/x/y/perpage/10,
/x/y/perpage/30,
/x/y/perpage/100,
i made a new route for it
route::('/x/perpage/{count})'
and changed my AdminReferenceController to
public function index($perpage = false)
{
if(!$perpage) {
$perpage = 10;
}
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc')->paginate($perpage);
I couldn't get time to work this out. But I found you calling pagination() instead of paginate. See my suggetion
<div class="page-sizer">
<a class="page numbers" href="{{$references->paginate(10)}}">10</a>
<a class="page numbers" href="{{$references->paginate(30)}}">30</a>
<a class="page numbers" href="{{$references->paginate(100)}}">100</a>
<button href="qweqwe.qweqwe" class="btn btn-info float-right>112e1e1e1e"></button>
</div>
Here I removed the paginate from index() and returns collection.
public function index()
{
$references = Reference::orderBy('priority', 'desc')->orderBy('id', 'desc');
return view('admin.reference.index', ['references' => $references]);
}
Hope this helps you.

Cart update in laravel

have a form like this. This is an update form, i just need to update qty foreach product in cart.
But i have tried to explode each results and not work... it return object2array conversion error... its the first time that i get this error How i can save this in DB?
<form action="update">
#foreach($products as $product)
<input type="text" name="products[]">
<input type="text" name="qty[]">
#endforeach
<input type="submit" calss="btn btn-primary">
This is my controller:
Route::post('aggiorna', function() {
$quantita = Input::all();
$carrelli = \App\Models\Carrello::where('entry_by', \Session::get('uid'))->get();
$quantita = explode(',', $quantita);
$i = 0;
foreach($carrelli as $carrello) {
$carrello->quantita = $quantita[$i];
$i = $i++;
}
return Redirect::to('carrello');
});
Thanks in advance.
you do the iteration for each $carreli that exist on your database, however you never save the value.
Route::post('aggiorna', function() {
$quantita = Input::all();
$carrelli = \App\Models\Carrello::where('entry_by', \Session::get('uid'))->get();
$quantita = explode(',', $quantita);
$i = 0;
foreach($carrelli as $carrello) {
$carrello->quantita = $quantita[$i];
$i = $i++;
$carrelo->save();
}
return Redirect::to('carrello');
});
add the $carrelo->save(); after you update the value in order to save it on db.
Also careful when you use Input::all();. That means that your data array contains both products and quantities. I would suggest using the following code:
Route::post('aggiorna', function() {
$quantita = Input::get('qty');
$products = Input::get('products');
$carrelli = \App\Models\Carrello::where('entry_by', \Session::get('uid'))->get();
$quantita = explode(',', $quantita);
$products = explode(',', $products);
$i = 0;
foreach($carrelli as $carrello) {
$carrello->quantita = $quantita[$i];
$carrello->products = $products[$i];
$i = $i++;
$carrelo->save();
}
return Redirect::to('carrello');
});
However since i do not know what you are trying to achieve, I posted both solutions here.

Resources