How do i get a post id in laravel - php

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.

Related

laravel error : InvalidArgumentException : Request::capture() in index.php

I want to learn how csrf works. Then, I found the following website.
The teaching provided in it is: Add a function to modify the user's name for the laravel dashboard. And this teaching is in the chapter "Set Up Simulated Functionality".
https://www.stackhawk.com/blog/laravel-csrf-protection-guide/
Create a new controller /app/Http/Controllers/UserController.php
<?php
namespace AppHttpControllers;
use AppHttpControllersController;
use IlluminateHttpRequest;
use AppModelsUser;
use IlluminateSupportFacadesSession;
class UserController extends Controller
{
public function update(Request $request)
{
$user = User::findOrFail(auth()->user()->id);
$user->name = $request->name;
$user->save();
Session::flash('message', 'Name updated!');
return back();
}
}
update /resources/views/dashboard.blade.php
<x-app-layout>
<x-slot name="header">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
{{ __('Dashboard') }}
</h2>
</x-slot>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
<div class="p-6 bg-white border-b border-gray-200">
You're logged in!
</div>
{{-- This is the new code block to be added to the file --}}
#if(Session::has('message'))
<div class="bg-green-100 border-t-4 border-green-500 px-4 py-3">
<p class="text-sm">{{ Session::get('message') }}</p>
</div>
#endif
<div class="p-6 bg-white border-b border-gray-200">
<form method="POST" action="/users/">
#method('PATCH')
<div class="mt-4 max-w-xs">
<x-input value="{{ auth()->user()->name }}" id="name" class="block mt-1 w-full" type="text" name="name" placeholder="Your name here" required />
</div>
<x-button class="mt-3">
{{ __('Update Name') }}
</x-button>
</form>
</div>
{{-- End of the new code block --}}
</div>
</div>
</div>
</x-app-layout>
update routes/web.php
//add this to the top of the file
use AppHttpControllersUserController;
//This goes with the other routes
Route::patch('/users/', [UserController::class, 'update'])->middleware(['auth']);
After I added/modified the following three files according to his teaching...I got such an error message :
InvalidArgumentException
Unable to locate a class or view for component [input].
public/ index.php : 52 require_once
.
.
$app = require_once __DIR__.'/../bootstrap/app.php';
$kernel = $app->make(Kernel::class);
$response = $kernel->handle(
$request = Request::capture() // error
)->send();
$kernel->terminate($request, $response);
.
.
In my understanding, the code written by this master is not wrong. In addition, this is a container that uses docker to run, I don't think it should be a version problem.
What is the reason for this error? Please how can I fix this error?
The error is in the view /resources/views/dashboard.blade.php,
you don't have any components called <x-input and <x-button,
just raplace it with normal html input and button, or create missing blade component
https://laravel.com/docs/9.x/blade#components

How to pass a value in a form action in laravel

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');
}

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

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