How to pass a value in a form action in laravel - php

I have a view that list all objects in a database and for each object creates a form for saving to a different table. My problem is, that the value isn't being passed to my function.
Here is my blade.php file:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card">
<div class="card-header">{{ __('Items') }}</div>
<div class="card-body">
<div class="row">
#foreach($items as $item)
<div class="col-md-3 col-xs-12">
<div class="card">
<img src="..." class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{ $item->name }}</h5>
<p class="card-text">$ {{ $item->price }}</p>
#auth
<form method="post" action="{{ route('carts.store', $item) }}">
#csrf
#method('post')
<button type="submit" class="form-control btn">add to cart</button>
</form>
#endauth
<form method="post" action="{{ route('item.destroy', $item) }}">
#csrf
#method('delete')
<button type="submit" class="form-control btn btn-danger">delete</button>
</form>
</div>
</div>
</div>
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
and my function in the CartsController:
public function store(Item $item)
{
$cart = new Cart();
$cart->user_id = auth()->id();
$cart->item_id = $item->id;
$cart->save();
return redirect('/item');
}
When I click on add to cart I get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'item_id' cannot be null (SQL: insert into `carts` (`user_id`, `item_id`, `updated_at`, `created_at`) values (1, ?, 2020-08-24 07:35:44, 2020-08-24 07:35:44))
I've tried passing the id to the function directly but that also doesn't seem to work. I'm very confused as to why this is happening since I can use $item two rows earlier without a problem.

Provided that your route model binding is setup correctly, it won't actually matter whether you pass the id of an object or the object itself to the the route() function.
https://laravel.com/docs/7.x/routing#implicit-binding
When you run php artisan route:list, you should see something similar to this:
POST | cart/store/item/{item} | carts.store | App\Http\Controllers\CartController#store
Laravel automatically resolves Eloquent models defined in routes or controller actions whose type-hinted variable names match a route segment name.
So any of the following will actually work
{{ route('carts.store', $item) }}
OR
{{ route('carts.store', $item->id) }}
OR
{{ route('carts.store', ['item' => $item->id]) }}
Should all resolve to the same thing.
Addendum
So the route you are using doesn't have a route parameter for your item (i.e {item}), as such it won't know which Item object you are referencing.
You can either:
Amend your route to include this route parameter
OR
use the Request object to resolve the Item instead.
Blade
<form method="post" action="{{ route('carts.store') }}">
#csrf
#method('post')
<input type="hidden" name="item_id" value="{{ $item->id }}">
<button type="submit" class="form-control btn">add to cart</button>
</form>
Controller
public function store(Request $request)
{
$cart = new Cart();
$cart->user_id = auth()->id();
$cart->item_id = $request->item_id;
$cart->save();
return redirect('/item');
}

Related

How do i get a post id in laravel

i am new to Laravel so am trying to delete and edit some posts which is linked to a page where the update from is located but each time i update or delete, i get a 404 error or the page is not found(i think the problem is the url).
here is my code for the update
public function update(Request $request, $id) {
$car = Car::where('id', $id)
->update([
'name'=> $request->input('name'),
'founded'=> $request->input('founded'),
'description' => $request->input('description')
]);
return redirect('/cars'); }
this one is for delete/destroy
public function destroy($id)
{
$car = Car::find($id);
$car->delete();
return redirect('/cars');
}
i also have an edit.blade.php
#section('content')
<div class="m-auto w-4/8 py-24">
<div class="text-center">
<h1 class="text-5xl uppercase bold">
Update Car
</h1>
</div>
</div>
<div class="flex justify-center pt-20">
<form action="../cars/{{ $car->id }}" method="POST">
#csrf
#method('PUT')
<div class="block">
<input type="text" class="shadow-5xl mb-10 p-2 w-80 italic placeholder-gray-400" name="name"
value="{{ $car->name }}"><br>
<input type="number" class="shadow-5xl mb-10 p-2 w-80 italic placeholder-gray-400" name="founded"
value="{{ $car->founded }}"><br>
<input type="text" class="shadow-5xl mb-10 p-2 w-80 italic placeholder-gray-400" name="description"
value="{{ $car->description }}"><br>
<button type="submit" class="bg-teal-500 block shadow-5xl mb-10 p-2 w-80 uppercase font-bold text-white">
Update
</button>
</div>
</form>
</div>
#endsection
the last part contains the buttons for delete and edit
#foreach ($cars as $car )
<div class="m-auto">
<span class="uppercase text-teal-500 font-bold text-xs italic">
Founded : {{ $car->founded }}
</span>
<h2 class="text-gray-700 text-5xl">
{{ $car->name }}
</h2>
<p class="text-lg text-gray-700 py-6">
Description : {{ $car->description }}
</p>
<div class="float-right">
<a class=" pb-2 italic text-teal-500" href="cars/{{ $car->id }}/edit">
Edit →
</a>
<form action="../cars/{{ $car->id }}" method="POST">
#csrf
#method("delete")
<button type="submit" class="pb-2 italic text-red-500">
Delete →
</button>
</form>
</div><br><br>
<hr class="mt-4 mb-8">
</div>
#endforeach
here is my route
Route::resource('/cars', CarsController::class);
first check route with this command php artisan route:list
then you see list like this
DELETE cars/{car}
PUT|PATCH cars/{car}
the car name is important to automatically Laravel find entity base on Type hint Car $car, so in controller use this convention :
public function destroy(Car $car)
{
$car->delete();
return redirect('/cars');
}
public function update(Request $request, Car $car) { ... }
You should not generate url like this: action="../cars/{{ $car->id }}"
Instead use action="{{ route('cars.update', $car->id) }}"
You can see the available routes by running this command
php artisan route:list
So, Basically when you use resource you get predefined route list by Laravel with different methods.
Example your route is
Route::resource('/cars', CarsController::class);
Then laravel generate routes like this.
To check route list run php artisan route:list
Route::GET('/cars', [CarsController::class, 'index'])->name('cars.index');
Route::GET('/cars/create', [CarsController::class, 'create'])->name('cars.create');
Route::POST('/cars', [CarsController::class, 'store'])->name('cars.store');
Route::GET('/cars/{id}', [CarsController::class, 'show'])->name('cars.show');
Route::GET('/cars/{id}/edit', [CarsController::class, 'edit'])->name('cars.edit');
Route::PUT('/cars/{id}', [CarsController::class, 'update'])->name('cars.update');
Route::DELETE('/cars/{id}', [CarsController::class, 'destroy'])->name('cars.destroy');
Then you can use in form with defined methods.
Example to use
{{ route('cars.destroy', ['id' => $car->id]) }}
Source Laravel documentation: click to check more resource method on offical Laravel website.

Trying to get property 'img' of non-object using Gloudemans\Shoppingcart\ in Laravel

I am creating a Laravel e-commerce site and I am using the Gloudemans\Shoppingcart\ library. I am having an issue with the 'Add To Cart' button. I'll explain a bit more! I have a singleProduct.blade.php file and this calls the product info from a controller:
This is the function that passes the data from the DB to the view:
public function show($name)
{
$iamlush = iamlush::where('name', $name)->firstOrFail();
return view('singleProduct')->with('product', $iamlush);
}
This is the singleProduct file:
<div class="contentContainer">
<div class="rowContainer text-center">
<div class="productImgContainer">
<img src="{{ asset('img/iamlush/shop/'.$product->img) }}" class="productImg">
</div>
<div class="productInfoContainer">
<div class="text-center">
<div class="productLogoContainer">
<img src="{{ asset('img/logo/'.$product->productLogo) }}" class="logoContainer">
</div>
<h3>{{ $product->name }}</h3>
<h5>{{ $product->priceFormat() }}</h5>
</div>
<p class="descriptionContainer">
{{ $product->description }}
</p>
<div class="rowContainer">
<div class="iconContainer">
<img src="{{ asset('img/productPage/productInfo.png') }}" class="icons">
</div>
<div class="iconContainer">
<img src="{{ asset('img/productPage/paymentMethods.jpg') }}" class="icons">
</div>
</div>
<form action="{{ route('cart.store') }}" method="POST" class="formContainer">
#csrf
<input type="hidden" name="id" value="{{ $product->id }}">
<input type="hidden" name="name" value="{{ $product->name }}">
<input type="hidden" name="price" value="{{ $product->price }}">
<div class="BtnContainer">
<button type="submit" class="btnCart">Add To Cart</button>
</div>
</form>
</div>
</div>
</div>
The 'Add To Cart' sends a POST request to the 'cart.store' and this is the web.php:
Route::post('/cart', 'CartController#store')->name('cart.store');
This is the cart controller file:
public function store(Request $request)
{
Cart::add($request->id, $request->name, 1, $request->price)->associate('App\iamlush');
return redirect()->route('cart.index')->with('success_message', 'Item was added to your cart!');
}
The cart page as several Laravel sections. The first is the passing of the success message if the item is succesfully added:
#if (session()->has('success_message'))
<p class="itemAddedContainer">
{{ session()->get('success_message') }}
</p>
#endif
The second is the the actual cart function, it checks wether the count for the cart is above 0 i.e. there is items in the cart:
#if(\Gloudemans\Shoppingcart\Facades\Cart::count() > 0)
<p class="introTxt">Looks like you have {{ \Gloudemans\Shoppingcart\Facades\Cart::count() }} Let's see what you have in your bag...</p>
<div class="rowContainer">
<!-- holds labels for cart -->
<div class="labelContainer">
<p>Product Image</p>
</div>
<div class="labelContainer">
<p>Name</p>
</div>
<div class="labelContainer">
<p>Quantity</p>
</div>
<div class="labelContainer">
<p>Price</p>
</div>
</div>
After this section, before the #else and #endif for 'count() > 0', is the #foreach loop in the cart:
#foreach( \Gloudemans\Shoppingcart\Facades\Cart::content() as $item)
<div class="productRowContainer">
<!-- holds labels for cart -->
<div class="cartItemContainer">
<img src="{{ asset('img/iamlush/shop/'.$item->model->img) }}" style="width: 30%;">
</div>
<div class="cartItemContainer">
<div class="dataContainer">
<img src="{{ asset('img/logo/'.$item->model->productLogo) }}" class="productLogo">
<p>Mediterranean Dark</p>
</div>
</div>
<div class="cartItemContainer">
<div class="dataContainer">
<div class="quantityContainer">
<button class="quantityBtn">-</button>
</div>
<div class="quantityContainer">
<p>1</p>
</div>
<div class="quantityContainer">
<button class="quantityBtn">+</button>
</div>
</div>
</div>
<div class="cartItemContainer">
<div class="dataContainer">
<p>{{ $item->model->presentprice() }}</p>
</div>
</div>
</div>
#endforeach
#else
<h3>You dont have anything</h3>
#endif
This section takes the content of the cart as $item and is then used to fill the data. I am following this youtube tutorial:
Laravel E-Commerce - Shopping Cart - Part 2 ( https://www.youtube.com/watch?v=Jzi6aLKVw-A&list=PLEhEHUEU3x5oPTli631ZX9cxl6cU_sDaR&index=4&t=430s )
At 13.00 minutes is when he makes it dynamic and when I first tried it, it worked for me but then it stopped working out of the blue and I can't understand why and it was giving me this error:
Trying to get property 'img' of non-object
First, try to debug your query result
dd($iamlush)
if there is null, check your database? have you any records by that name
there may be two reason
you doesn't have any record for this condition
you have a mistake in your model

laravel having problem with show method of laravel

i have a property model and i want to get the property show method and do some operation on it so i am on the show method right now consider the link below :
http://localhost:8000/properties/1
now from this link i submit a form to the route below :
Route::post('/properties/startreserve','PropertyController#startreserve');
and this is the controller of my startreserve and here i want to get the property that i had in last page which means property number 1 in this example exacly like show method :
public function startreserve(Request $request,Property $property){
.
.
.
return view('users.properties.reserve')
->with('property',$property);
}
now when i pass $property its empty but i want to do it as the show method !!!
ok now for example i want to pass the id 1 property and make the link look like this :
http://localhost:8000/properties/startreserve/1
and here is my view code :
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed"
action="/properties/startreserve" method="post">
{{ csrf_field() }}
#if ($errors->any())
<div class="panel panel-flat bg-danger">
<div class="panel-heading">
<h5 class="panel-title"></h5>
<div class="heading-elements">
<ul class="icons-list">
<li><a data-action="close"></a></li>
</ul>
</div>
</div>
<div class="panel-body">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
</div>
#endif
<div class="row">
#foreach($pdate as $index => $pdates)
<div id="checkboxes" class="col-lg-2 text-center">
<input type="checkbox" name="d[{{$index}}]"value="{{verta($pdates->date)->format('Y/m/d')}}-{{$pdates->price}}" id="d{{$index}}"/>
<label class="whatever mt-3" for="d{{$index}}"> {{verta($pdates->date)->format('Y/m/d')}}
<hr>
{{$pdates->price}}</label>
</div>
#endforeach
<div class="col-lg-12">
<input type="submit" value="send" class="btn btn-primary">
</div>
</div>
</form>
You need to define the id on the route itself, as the route you have is not accepting the id.
Route::post('/properties/startreserve/{property}','PropertyController#startreserve');
So using a post request, you should be passing the ID in your action, you are missing that here.
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator-dashed"
action="/properties/startreserve/{{$property->id}}" method="post">

Method links does not exist in Laravel 5.6 app?

working with laravel 5.6 and in My comtroller I have two tables like vehicles and uploads.relationship with both two tables are,
Vehicle Model,
public function uploads()
{
return $this->hasMany(Upload::class);
}
and Upload Model,
public function vehicle()
{
return $this->belongsTo(Vehicle::class);
}
and I have following index function in My VehicleController,
$vehicles = Vehicle::with('uploads')
->orderBy('adtype','DESC')
->latest('updated_at')
->paginate(5);
return view('vehicles.index')->withVehicles($vehicles);
and index blade file is,
<form method="GET" action="{{ url('search') }}">
{{csrf_field()}}
<div class="row">
<div class="col-md-6">
<input type="text" name="search" class="form-control" placeholder="Search">
</div>
<div class="col-md-6">
<button class="btn btn-info">Search</button>
</div>
</div>
</form>
<br>
#forelse( $vehicles as $vehicule )
#if( $vehicule->uploads->count() > 0 )
<a href="{{ route('vehicles.show', $vehicule->id) }}">
#php
$upload = $vehicule->uploads->sortByDesc('id')->first();
#endphp
<div style="border-style: solid; background-color: {{ $vehicule->adtype === 1 ? '#FFEFD5' : '#FFFFFF' }} ">
<img src="/images/{{ $upload->resized_name }}" height="150" width="250"></a>
{{ Carbon\Carbon::parse($vehicule->created_at)->diffForHumans()}}
{{$vehicule->provincename}}
{{$vehicule->milage}}
</div>
<br>
<hr>
#endif
#empty
<td>No Advertisment to display.</td>
#endforelse
</div>
</div>
</div>
{{ $vehicles->links() }}
</div>
#endsection
my pagination is working fine, but in my index file I have search input using algolia. when I use keyword and click search button following error is occured,
(2/2) ErrorException
Method links does not exist. (View: C:\Users\banda\Desktop\ddddd\resources\views\vehicles\index.blade.php)
when I remove {{ $vehicles->links() }} in the view file it is working.
how can fix this problem?
Can you try
{{ $vehicles->render() }}
instead on ->links() ?
------ EDIT
Can you try passing the data to view like this?
$vehicles = Vehicle::with('uploads')
->orderBy('adtype','DESC')
->latest('updated_at')
->paginate(5);
return view('vehicles.index')->with(['vehicles' => $vehicles]);
and check?

MethodNotAllowedHttpException not found when I paginate in Laravel

Hello this is my first question here.
I am using php laravel framework and I am getting this error
MethodNotAllowedHttpException in RouteCollection.php line 233:
This error comes when I go to second page of the result list.
My controller code.
public function find_product(Request $request)
{
$search = trim($request->product);
$products = Store_product::(query-for-products-working)
->paginate(1);
return view('fc.product',compact('products','search'));
}
My web.php code
Route::post('/product', 'FlashCartController#find_product');
My view code
#foreach($products as $product)
<div class="fc-col">
<div class="panel panel-primary">
<div class="panel-heading fc-col-head"><div class="marquee">{{ $product->product_name }}</div></div>
<div class="panel-body fc-col-body">
<img src="{{ image_check('uploads/store/products/',$product->product_image1,'uploads/service/') }}" class="img-responsive" style="width:100%; height: 100%;" alt="{{ $product->product_name }}" />
</div>
<div class="panel-footer fc-col-footer">
<span class="price">Rs.
{{
price_check($product->product_discount, $product->product_price, $product->sale_id, $product->discount)
}}/-
</span>
</div>
</div>
</div>
#endforeach
<div>
{{ $products->links() }}
</div>
and the form
<form action="/product" method="POST">
{{ csrf_field() }}
<div class="input-group container">
<input type="text" name="product" class="form-control" value="{{$search}}" placeholder="Enter product name" />
<div class="input-group-btn">
<input type="submit" class="btn btn-danger" value="Search" />
</div>
</div>
</form>
Why my method is not allowed. And if this is not the method to use what should I do?
Can anyone help me with this please? :(
Okay so your problem as I understand it is that when you paginate to the next page the url becomes empty and no results are shown.
In your view you have this line:
{{ $products->links() }}
Which shows that whatever your url is at the moment, just ignore it and add pagination to it.
That means if your url is like www.abc.com?product=graphics it will ignore product and only add www.abc.com?page=1,2,... Of course your page will be blank.
Instead use this:
{{ $products->appends(request()->input())->links() }}
Now it tells the system to add pagination but append variables to it too. What variables? The variables that are appended on the url already.
Hope it helps

Categories