404 on add to cart laravel - laravel

i have this situation on add to cart when i want to add to cart i am getting 404 error,
this is my route
Route::get('/add-to-cart/{product}', [CartController::class, 'addToCart'])->name('add.cart');
Route::get('/remove/{id}', [CartController::class, 'removeFromCart'])->name('remove.cart');
Route::get('/change-qty/{product}', [CartController::class, 'changeQty'])->name('change_qty');
This is controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Products;
class CartController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('cart.index');
}
public function addToCart(Products $product)
{
$cart = session()->get('cart');
if (!$cart) {
$cart = [$product->id => $this->sessionData($product)];
return $this->setSessionAndReturnResponse($cart);
}
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
return $this->setSessionAndReturnResponse($cart);
}
$cart[$product->id] = $this->sessionData($product);
return $this->setSessionAndReturnResponse($cart);
}
public function changeQty(Request $request, Products $product)
{
$cart = session()->get('cart');
if ($request->change_to === 'down') {
if (isset($cart[$product->id])) {
if ($cart[$product->id]['quantity'] > 1) {
$cart[$product->id]['quantity']--;
return $this->setSessionAndReturnResponse($cart);
} else {
return $this->removeFromCart($product->id);
}
}
} else {
if (isset($cart[$product->id])) {
$cart[$product->id]['quantity']++;
return $this->setSessionAndReturnResponse($cart);
}
}
return back();
}
public function removeFromCart($id)
{
$cart = session()->get('cart');
if (isset($cart[$id])) {
unset($cart[$id]);
session()->put('cart', $cart);
}
return redirect()->back()->with('success', "Removed from Cart");
}
protected function sessionData(Products $product)
{
return [
'name' => $product->nume,
'quantity' => 1,
'price' => $product->pret,
];
}
protected function setSessionAndReturnResponse($cart)
{
session()->put('cart', $cart);
return redirect()->route('cart')->with('success', "Added to Cart");
}
This is what i have in view file:
<a class="theme_btn add_cart w-100" href="{{route('add.cart', [$produs->id])}}">add to cart
<span class="theme_btn_eff"></span>
</a>
In my loop when i fetch products, on click is redirecting me to 404 page without getting an error, i was trying to get dd($product) into controller but i get again 404.

Change this line
<a class="theme_btn add_cart w-100"
href="{{ route('add.cart', [$produs->id]) }}" >add to cart
<span class="theme_btn_eff"></span>
</a>
To This
<a class="theme_btn add_cart w-100"
href="{{ route('add.cart', ['product' => $produs->id]) }}" >add to cart
<span class="theme_btn_eff"></span>
</a>
In routes file you have passed route parameter naming {product} in url /add-to-cart/{product}, hence you need to mention it in view file as well {{ route('add.cart', ['product' => $produs->id]) }} thats the naming convention laravel follows
Route::get('/add-to-cart/{product}', [CartController::class, 'addToCart'])->name('add.cart');

Related

Laravel livewire wire:model with array

From blade component I can give valule product_id
<input wire:model="qty.{{$row->product_id}}" value="{{$row->qty}}" max="{{$row->stock}}">
but how I can display qty from database and when increase qty then wire model will work and updated, what I can should do???
public $qty;
public function render()
{
$this->userId=Auth::id();
if ($this->qty!=null){
foreach($this->qty as $key => $qty)
{
$cart=Cart::where('user_id',$this->userId)->where('product_id',$key)->first();
if ($cart){
$cart->update([
'qty' => $qty,
]);
$this->emit('refreshCart');
}
}
}
}
in your blade
<input wire:model="inputs.{{ $loop->index }}.qty" value="{{$row->qty}}" max="{{$row->stock}}">
<a wire:click.prevent="increase({{$loop->index}})"></a>
<a wire:click.prevent="reduce({{$loop->index}})"></a>
in your livewire component
public $inputs = [];
public function mount()
{
foreach (Cart::where('user_id',$this->userId)->get() as $item) {
array_push($this->inputs, [
"id" => $item->id,
"qty" => $item->quantity,
]);
}
}
public function reduce($index)
{
$product_id = $this->inputs[$index]['id'];
$this->inputs[$index]['qty'] -= 1;
$this->updateCart($product_id, $this->inputs[$index]['qty']);
}
public function increase($index)
{
$product_id = $this->inputs[$index]['id'];
$this->inputs[$index]['qty'] += 1;
$this->updateCart($product_id, $this->inputs[$index]['qty']);
}
public function updateCart($product_id, $productQty)
{
//update yourcart here with productID and qty
}
This code works for me.

ErrorException thrown with message "Trying to get property 'user' of non-object

I am using relationship in my laravel project. I am trying to show my post and replies. But i keep getting this error. I've tried various solution but none of them worked. Can anyone help me?
Post model:
protected $fillable = [
'title', 'content', 'category_id' , 'slug', 'user_id',
];
public function user1()
{
return $this->belongsTo('App\User');
}
public function replies()
{
return $this->hasMany('App\Reply');
}
Reply model:
protected $fillable = ['content','user_id','posts_id'];
public function post(){
return $this->belongsTo('App\Post');
}
public function user()
{
return $this->belongsTo('App\User');
}
PostController:
public function shro($slug)
{
$pst= Post::where('slug',$slug)->first();
return view('posts.show')->with('p', $pst);
}
show.blade.php
<div class="panel panel-default">
<div class="panel-heading">
<img src="/uploads/avatars/{{ $p->user->avatar }}" alt="" width="70px" height="60px">
<span>{{ $p->user->name }}, <b>{{ $p->created_at->diffForHumans() }}</b></span></br>
</div>
$p, or $pst (confusing variable names) is null, and this is because ->first() can return null. Do you have a Post record in your database that matched slug?
Rule of thumb; never assume something exists.
Add some logic to ensure the Post exists before trying to access a property of it:
$post = Post::where("slug", $slug)->first();
if(!$post){
abort(404);
}
return view('posts.show')->with('post', $post);
// OR
$post = Post::where("slug", $slug)->findOrFail(); // or firstOrFail();
return view('posts.show')->with('post', $post);
Also, check your $post->user:
#if($post->user)
<img src="/uploads/avatars/{{ $post->user->avatar }}" width="70px" height="60px"/>
<span>{{ $post->user->name }}, <b>{{ $post->created_at->diffForHumans() }}</b></span></br>
#endif
If $post->user returns null, you'll have a similar error.
You can eager load the user with it's relative post at once by doing :
//...
$pst= Post::where('slug',$slug)->with(['user1'])->first();
//...

laravel-5.8:The POST method is not supported for this route. Supported methods: GET, HEAD

hi m trying to add products in cart but it says: The POST method is not supported for this route. Supported methods: GET, HEAD.. (View: \resources\views\product\detail.blade.php), I wants that by clicking the addtocart it redirect me to that age with products,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,...…………………………………..,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,
route:
Route::get('cart', 'Admin\ProductController#cart')->name('product.cart');
Route::get('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
controller:
public function cart()
{
if (!Session::has('cart')) {
return view('products.cart');
}
$cart = Session::has('cart');
return view('product.cart', compact('cart'));
}
public function addToCart(Product $product, Request $request)
{
if(empty(Auth::user()->email)){
$data['email'] = '';
}else{
$data['email'] = Auth::user()->email;
}
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$qty = $request->qty ? $request->qty : 1;
$cart = new Cart($oldCart);
$cart->addProduct($product);
Session::put('cart', $cart);
return redirect()->back()->with('flash_message_success', 'Product $product->title has been successfully added to Cart');
}
view:
<form method="POST" action="{{ route('addToCart') }}" enctype="multipart/form-data">
<div class="btn-addcart-product-detail size9 trans-0-4 m-t-10 m-b-10">
#if($product->product_status == 1)
<!-- Button -->
<button class="flex-c-m sizefull bg1 bo-rad-23 hov1 s-text1 trans-0-4">
Add to Cart
</button>
#else Out Of Stock #endif
</div>
</form>
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Cart
{
private $contents;
private $totalQty;
private $contentsPrice;
public function __construct($oldCart){
if ($oldCart) {
$this->contents = $oldCart->contents;
$this->totalQty = $oldCart->totalQty;
$this->totalPrice = $oldCart->totalPrice;
}
}
public function addProduct($product, $qty){
$products = ['qty' => 0, 'price' => $product->price, 'product' => $product];
if ($this->contents) {
if (array_key_exists($product->slug, $this->contents)) {
$product = $this->contents[$product->slug];
}
}
$products['qty'] +=$qty;
$products['price'] +=$product->price * $product['qty'];
$this->contents[$product->slug] = $product;
$this->totalQty+=$qty;
$this->totalPrice += $product->price;
}
public function getContents()
{
return $this->contents;
}
public function getTotalQty()
{
return $this->totalQty;
}
public function getTotalPrice()
{
return $this->totalPrice;
}
}
First of all your form method in the view is POST but you don't have a post route.
Second, the route that you have defined expect a parameter(product) you can change the form action as below BUT I think you want to send the user to another page so you can use a link instead of form.
Here's the form action:
action="{{ route('addToCart', $product->id) }}"
And if you want to use link, you can do something like this:
.....
Your method should be POST. In the form, you're calling it Post method but in route.php file, you defined as get to change it as Route::post
Route::post('/addToCart/{product}', 'Admin\ProductController#addToCart')->name('addToCart');
In addition, your route.php file expecting {product} so you need to pass it in form route so your action be like {{ route('addToCart',$product->id) }}
<form method="POST" action="{{ route('addToCart',$product->id) }}" enctype="multipart/form-data">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>

Error in Custom Blade Directives with array as parameter

In my Laravel 5.7 app I want to use Custom Blade Directives and to pass an array in this directive
as there could be different access, like :
#loggedUserHasAccess([USER_ACCESS_ADMIN])
<div class="col">
<a class="social-inner" href="{{ route('admin.dashboard') }}" >
<span class="icon"></span><span>Backend</span>
</a>
</div>
#endLoggedUserHasAccess
And in app/Providers/AppServiceProvider.php :
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
...
\Blade::directive('loggedUserHasAccess', function (array $accessArray) {
$condition = false;
if (Auth::check()) {
$loggedUser = Auth::user();
$usersGroups = User::getUsersGroupsByUserId($loggedUser->id, false);
foreach ($usersGroups as $next_key => $nextUsersGroup) {
if (in_array($nextUsersGroup->group_id, $accessArray)) {
$condition = true;
}
}
}
return "<?php if ($condition) { ?>";
});
Blade::directive('endLoggedUserHasAccess', function () {
return "<?php } ?>";
});
But I got syntax error : https://imgur.com/a/I5s1TmQ
USER_ACCESS_ADMIN is defined in bootstrap/app.php.
looks like my syntax is invalid, but which is valid ?
Thanks!

How to pass variable from blade to LARAVEL commands

I need to pass user_id from blade to routes, and then use the variable into a laravel command. How can I do?
lista_lavori.blade.php
<div class="box-tools">
<i class="fa fa-print"></i>
</div>
web.php - route
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport');
return back();
});
StampaSingoloReport.php - Commands
public function handle()
{
// static id i need to change this dinamically
$id = 5;
$utente = \App\User::where('id',$id)->get();
//invio email per avvertire l'utente
$data = array('utenti'=>$utente);
Mail::send('mail.invioMailReportLavoriSingoli', $data, function($message) {
$message->to('rubertocarmine94#gmail.com', 'Admin Risorse Umane') ->subject('Email da piattaforma BancaStatoHR') ;
$message->from('rubertocarmine94#gmail.com') ;
});
}
You can pass an array to call() method like
Route::get('/stampasingoloreport/{id}', function ($id) {
Artisan::call('StampaSingoloReport:stampasingoloreport',[
'id' => $id
]);
return back();
});
Now in your handle method, you can access these arguments like
protected $signature = 'StampaSingoloReport:stampasingoloreport { id } ' ;
function handle(){
$this->argument('id');
// your code
}
Hope this helps

Resources