Laravel Livewire hide checked checkbox - laravel

in my laravel project in livewire component i need to hide/set display none or something a checked checkbox and later i need to show again if its needed . Any solutions? I could simply delete it but i wanna store it in DB
I tried do this:
https://larainfo.com/blogs/laravel-livewire-show-and-hide-div-example
but its hidding my all input checkboxes
here is my Livewire component code:
<?php
namespace App\Http\Livewire\Tasks\Types;
use App\Http\Livewire\Forms\BaseForm;
use App\Models\Task\Task;
use App\Models\Task\TaskStatus;
use App\Models\Task\TaskType;
use App\Models\Task\TaskTypeStatus;
use Livewire\Component;
use App\Traits\HasPosition;
use Mpdf\Tag\Input;
class TaskTypeStatusModal extends BaseForm
{
public $task_type_id = 0;
public $availableStatuses = [];
public $selectedStatuses = [];
public $selectedStatusesList = [];
public function mount($params = [])
{
$this->task_type_id = $params['task_type_id'];
$this->title = 'Edytuj statusy';
$this->availableStatuses = TaskStatus::orderBy('position')->get();
$this->selectedStatuses = TaskTypeStatus::where('task_type_id', $this->task_type_id)->pluck('task_status_id');
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get();
}
public function submit()
{
foreach ($this->selectedStatuses as $status) {
TaskTypeStatus::create([
'task_type_id' => $this->task_type_id,
'task_status_id' => $status,
]);
}
$this->closeFromModal();
$this->emit( 'Zapisano');
$this->emit('list:refresh');
}
public function render()
{
return view('livewire.tasks.types.task-type-status-modal',[
$this->selectedStatusesList = TaskTypeStatus::where('task_type_id', $this->task_type_id)->orderBy('position')->get()
]);
}
public function reorder($list)
{
foreach ($list as $item) {
TaskTypeStatus::find($item['value'])->update(['position' => $item['order']]);
}
}
public function deleteStatus($id)
{
TaskTypeStatus::find($id)->delete();
}
and here is my blade code:
<div>
<form wire:submit.prevent="submit">
<div class="modal-header">
<h5 class="modal-title">{{ $title }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close" wire:click.prevent="closeFromModal">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<h6>Wybierz statusy</h6>
#forelse($availableStatuses as $availableStatus)
<div class="form-check checkbox">
<input class="form-check-input" name="status-{{ $availableStatus->id }}" id="status-{{ $availableStatus->id }}" wire:key="status-{{ $availableStatus->id }}"
wire:model.defer="selectedStatuses" type="checkbox" value="{{ $availableStatus->id }}"
wire:click="$toggle">
<label class="form-check-label" for="status-{{ $availableStatus->id }}">{{ $availableStatus->name }}</label>
</div>
#empty
<tr>
<td colspan="3">{{ __('Brak dostępnych statusów') }}</td>
</tr>
#endforelse
<hr>
<h6>Dodane statusy</h6>
<tr><span style="color:#3c4b64;font-size: 9pt"><b>{{ __('Przeciągnij za nazwę, aby zmienić kolejność.') }}</b></span></tr>
<ul class="list-group" wire:sortable="reorder">
#forelse ($selectedStatusesList as $selectedStatus)
<li class="list-group-item" value="{{ $selectedStatus->id }}" wire:sortable.item="{{ $selectedStatus->id }}" wire:key="selectedStatus-{{ $selectedStatus->id }}">
<td wire:sortable.handle>{{ __($selectedStatus->taskStatus->name) }}
<div class="float-right">
<button wire:click.prevent="deleteStatus({{ $selectedStatus->id }})" class="btn btn-sm btn-danger">{{ __('Usuń') }}</button>
</div>
</td>
</li>
#empty
<tr>
<td colspan="3">{{ __('Brak dodanych statusów') }}</td>
</tr>
#endforelse
</ul>
</div>
<div class="modal-footer">
<button wire:click.prevent="closeFromModal" class="btn btn-secondary" data-dismiss="modal">Anuluj</button>
<button type="submit" class="btn btn-primary">Zapisz</button>
</div>
</form>
</div>

Related

Pre-Populating Parent Child Form from DB

I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given
Edit Component Code
<?php
namespace App\Http\Livewire\Admin;
use App\Models\Products;
use App\Models\Tariffs;
use Livewire\Component;
class AdminEditTariffsComponent extends Component
{
// public $productId;
public $tariffId;
public $allTariffs = [];
public $rowProducts = [];
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
$tariff = Tariffs::where('id', $tariffId)->first();
$this->tariffName = $tariff->tariff_name;
// $allTariffs = $tariff->products()->where('tariffs_id', $tariffId)->get()->toArray();
$allTariffs = $tariff->products->find($tariffId);
// var_dump($allTariffs) ;
// dd( $allTariffs);
foreach ($allTariffs->products as $product)
{
['productId' => $product->pivot->products_id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function updateStatus()
{
$tariff = Tariffs::find($this->tariffId);
$tariff->tariff_name = $this->tariffName;
$tariff->created_by = auth()->user()->id;
$tariff->save();
foreach ($this->allTariffs as $product) {
$tariff->products()->sync($product['productId'],
['basic_charge' => $product['basicCharge'],
'additional_charge' => $product['additionalCharge']]);
}
session()->flash('message', 'Tariff added successfully!');
return redirect('/admin/tariffs/');
}
public function addProduct()
{
$this->allTariffs[] = ['productId' => '', 'basicCharge' => '', 'additionalCharge' => ''];
}
public function removeProduct($index)
{
unset($this->allTariffs[$index]);
$this->allTariffs = array_values($this->allTariffs);
}
public function render()
{
$rowProducts = Products::all();
return view('livewire.admin.admin-edit-tariffs-component',['rowProducts'=>$rowProducts])->layout('layouts.admin.base');
}
}
Edit View
<div class="container-fluid">
<!-- Begin Page Content -->
<!-- Page Heading -->
<div class="row">
<div class="col-lg-8">
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">Edit Tariff</h6>
</div>
<div class="card-body">
<form wire:submit.prevent="editTariff">
#csrf
<div class="form-row">
<!-- Default input -->
<div class="form-group col-md-8">
<input type="text" class="form-control" placeholder="Enter Tariff Name"
wire:model="tariffName" required>
</div>
</div>
<hr>
<div class="card">
<div class="card-header">
<h6 class="text-primary">Products, Basic and Weight Charges</h6>
</div>
<div class="card-body">
<table class="table" id="products_table">
<thead>
<tr>
<th>Product</th>
<th>Basic Charge</th>
<th>Weight Charge</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach ($allTariffs as $index => $allTariff)
<tr wire:key="tariff-{{ $value->wireKey }}">
<td>
<select
wire:model="allTariffs.{{$index}}.productId"
class="custom-select custom-select-sm form-control form-control-sm">
<option value="">Select Product</option>
#foreach ($rowProducts as $product)
<option value="{{ $product->id }}">
{{ $product->product_name }}
</option>
#endforeach
</select>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Basic Charge"
wire:model="allTariffs.{{$index}}.basicCharge" required>
</td>
<td>
<input type="text"
class="form-control custom-select-sm form-control form-control-sm"
placeholder="Weight Charge"
wire:model="allTariffs.{{$index}}.additionalCharge" required>
</td>
<td>
<a href="#" wire:click.prevent="removeProduct({{$index}})" class="btn btn-danger btn-circle btn-sm">
<i class="fas fa-trash"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="row">
<div class="col-md-12">
<a href="#" wire:click.prevent="addProduct" class="btn btn-success btn-circle btn-sm">
<i class="fas fa-plus"></i>
</a>
</div>
</div>
</div>
</div>
<hr>
<div class="form-row">
<div class="form-group col-md-3">
<button type="submit" class="form-control btn btn-small btn-primary">Edit
Tariff</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
Model File
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tariffs extends Model
{
use HasFactory;
protected $table = "tariffs";
public function products()
{
return $this->belongsToMany(Products::class, 'products_tariffs',
'products_id', 'tariffs_id')
->withPivot('basic_charge', 'additional_charge');
}
public function productstariffs()
{
return $this->hasMany(ProductsTariffs::class);
}
}
I have tried prepopulating the forms from DB records, not happening for child form, I have use all conventions for Laravel table, pivot table etc., still nothing. The array display with the dd('$allTariffs') but doesn't show on view file, please help am stuck with
ErrorException
foreach() argument must be of type array|object, null given .thankyou
In your foreach in your mount function, you are creating an array but you aren't assigning it to anywhere. Therefore, $allTariffs is empty.
Also, you're casting your variables by default as an array. You are setting $rowProducts as a Collection, however. But then in your render you are also getting the $rowProducts again. I'd suggest removing the = [] and removing the fetching of the $rowProducts each render.
public $allTariffs = [];
public $rowProducts;
public $tariffName;
public function mount ($tariffId)
{
$this->rowProducts = Products::all();
// This assumes the $tarrifId always exists. If this isn't the case, perhaps
// wrap the related code in an "if ($tariff instanceof Tariff)"
$tariff = Tariffs::find($tariffId);
$this->tariffName = $tariff->tariff_name;
foreach ($tariff->products as $product) {
$this->allTariffs[] = ['productId' => $product->id, 'basicCharge' => $product->pivot->basic_charge, 'additionalCharge' => $product->pivot->additional_charge];
}
}
public function render()
{
return view('livewire.admin.admin-edit-tariffs-component')->layout('layouts.admin.base');
}

checkboxes and icons disappear on search

I am using livewire components but when begin typing in the search input field, the checkboxes and icons in the component disappear, and they only reappear after refreshing the page. What could be the cause of this behaviour?
Blade view
<div>
<div class="row">
<div class="col-md-12 grid-margin stretch-card">
<div class="card">
<div class="card-header">
<div class="d-flex justify-content-between align-items-center flex-wrap grid-margin">
<div>
<h4 class="mb-3 mb-md-0">User Roles</h4>
</div>
<div class="d-flex align-items-center flex-wrap text-nowrap">
<div class="form-inline">
<div class="input-group mr-2 mb-2 mb-md-0 d-md-non d-xl-flex">
<input type="text" wire:model="search" class="form-control" placeholder="Search role...">
</div>
<div class="input-group mr-2 mb-2 mb-md-0 mt-3 d-md-non d-xl-flex">
<select wire:model="sortAsc" class="form-control form-control-s mb-3">
<option value="1">Ascending</option>
<option value="0">Descending</option>
</select>
</div>
<div class="input-group mr-2 mb-2 mb-md-0 mt-3 d-md-non d-xl-flex">
<select wire:model="perPage" class="form-control form-control-s mb-3">
<option value="5">5</option>
<option value="10">10</option>
<option value="15">15</option>
</select>
</div>
</div>
<a href="{{ route('create-role') }}" class="btn btn-success btn-icon-text mr-2 mb-2 mb-md-0">
<i class="btn-icon-prepend" data-feather="plus"></i>
Add Role
</a>
<button wire:click="deleteRoles" type="button" class="btn btn-danger btn-icon-text mb-2 mb-md-0">
<i class="btn-icon-prepend" data-feather="trash-2"></i>
Delete Role
</button>
</div>
</div>
</div>
<div class="card-body">
#if (count($roles) > 0)
<div class="table-responsive">
<table id="dataTableExample" class="table">
<thead>
<tr>
<th></th>
<th>#</th>
<th>Display Name</th>
<th>Description</th>
<th>Created</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach ($roles as $role)
<tr wire:key="{{ $role->name }}">
<td>
<div class="form-check">
<label class="form-check-label">
<input type="checkbox" wire:model="selectedRoles.{{ $role->id }}" class="form-check-input">
</label>
</div>
</td>
<td>{{ $role->id }}</td>
<td>{{ $role->display_name }}</td>
<td>{{ $role->description }}</td>
<td>{{ $role->created_at->diffForHumans() }}</td>
<td>
<a href="{{ route('edit-role', $role->name) }}" class="btn btn-primary btn-icon-text mr-2 mb-2 mb-md-0">
<i class="btn-icon-prepend" data-feather="edit-2"></i>
Edit
</a>
</td>
</tr>
#endforeach
</tbody>
</table>
<div>{{ $roles->links() }}</div>
</div>
#else
<p>No user roles found.</p>
#endif
</div>
</div>
</div>
</div>
</div>
Corresponding livewire component
<?php
namespace App\Http\Livewire\Roles;
use Livewire\Component;
use App\Models\Role;
use Livewire\WithPagination;
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $selectedRoles = [];
public $search = '';
public $perPage = 10;
public $sortField = 'id';
public $sortAsc = true;
public function render()
{
return view('livewire.roles.index', [
'roles' => Role::search($this->search)
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->simplePaginate($this->perPage)
])
->extends('layout.master');
}
public function createRole(){
return view('livewire.roles.create')
->extends('layout.master');
}
public function deleteRoles(){
Role::destroy($this->selectedRoles);
}
}
What could be causing this issue?
try changing this lines, actually I use this like livewire documentation
'roles' => Role::where('someColumn','like','%'.$this->search.'%')
orWhere('anotherColumn','like','%'.$this->searchTerm.'%')
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->paginate($this->perPage)

product is not deleting from cart

hi m trying to delete product from cart but its not deleting , any suggestion to fix it,when i click on submit button then it says 404|not found
controller:
public function deleteCartProduct(Product $product)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->delProduct($product);
Session::put('cart', $cart);
return redirect()->route('product.cart')->with('flash_message_success', 'Product product has been removed from Cart');
}
model
public function deleteProduct($product)
{
if ($this->contents) {
if (array_key_exists($product->product_slug, $this->contents)) {
$delProduct = $this->contents[$product->slug];
$this->totalQty -= $delProduct['qty'];
$this->totalPrice -= $delProduct['price'];
array_forget($this->contents, $product->slug);
}
}
}
blade file
#foreach($contents as $slug => $cartItem)
<form action="{{ route('deleteCartProduct', $product) }}" method="POST">
#csrf
<tr class="table-row">
<td class="column-1">
<div class="cart-img-product b-rad-4 o-f-hidden">
<img src="{{ URL::to('/') }}/images/backend_images/product_images/{{ $cartItem['product']->product_image }}" alt="IMG-PRODUCT">
</div>
</td>
<td class="column-2">{{ $cartItem['product']->product_name }}</td>
<td class="column-3">${{ $cartItem['product']->product_price }}</td>
<td class="column-4">
<div class="flex-w bo5 of-hidden w-size17">
<button class="btn-num-product-down color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-minus" aria-hidden="true"></i>
</button>
<input class="size8 m-text18 t-center num-product" type="number" name="num-product1" value="{{ $cartItem['qty'] }}">
<button class="btn-num-product-up color1 flex-c-m size7 bg8 eff2">
<i class="fs-12 fa fa-plus" aria-hidden="true"></i>
</button>
</div>
</td>
<td class="column-5">${{ $cartItem['price'] }}</td>
<td class="column-5">
<input type="submit" class="btn btn-danger value="Remove Product">
</td>
</tr>
</form>
#endforeach
route:
Route::get('/cart/delete-product/{id}','ProductController#deleteCartProduct')->name('deleteCartProduct');
Your route should be Route::delete instead of Route::get and then in the form add this as well:
#method('delete')
I saw your error on the button:
<input type="submit" class="btn btn-danger value="Remove Product">
Change it with this:
<input type="submit" class="btn btn-danger" value="Remove Product">
Missing quote..
EDIT
Your route should be this:
Route::delete('/cart/delete-product/{id}','Admin\ProductController#deleteCartProduct')->name('deleteCartProduct');
You need to change the code in a controller as below.
public function deleteCartProduct(Product $product)
{
$oldCart = Session::has('cart') ? Session::get('cart') : null;
$cart = new Cart($oldCart);
$cart->deleteProduct($product);
Session::put('cart', $cart);
return redirect()->route('product.cart')->with('flash_message_success', 'Product product has been removed from Cart');
}
You defined it as method="POST" in blade. and "get" in route. So you need to change verb to Route::post

Getting validation to work for address in laravel

I'm making a page that before the user submits they need to add their address.
For example: The user goes to the order confirmation and they forget to add their address and they fill in the rest of the page (the page has delivery/collection radio buttons and payment option radio buttons) when the user clicks on the confirm button the page needs to go back and give an error that the address wasn't entered.
The address portion of the page only has a "Add Address" button that takes the user to a form to enter their address.
Is there a way to do this. I thought maybe validation would work but I don't think I'm doing it correctly in this instance.
I have a hidden form that grabs some info and it has an address field in it so that it gets passed into the controller so that I can save it, but it's like it doesn't pick it up
My order-confirmation.blade.php
#extends('layouts.public')
#section('content')
<div class="content_wrapper">
<h1>Order Confirmation</h1>
<?php
$delivery = getDeliveryFee();
?>
{{ $invoice_number }}
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12 mt-15">
#if($message = Session::get('success'))
<div class="alert alert-success" role="alert">
{{ $message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
#if($message = Session::get('error'))
<div class="alert alert-danger" role="alert">
{{ $message }}
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
#endif
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-link" type="button" data-toggle="collapse" data-target="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
Billing Information
</button>
</h2>
</div>
<div id="collapseOne" class="collapse {{ !$errors->any() ? 'show' : '' }}" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<div class="row">
<div class="col-lg-6">
<div class="address">
#if ($errors->confirmation_errors->has('delivery_address'))
<div class="help-block text-danger">
<strong>Please add an address NOW</strong>
</div>
#endif
#foreach($addresses as $address)
#if(!empty($address->complex))
{{ $address->complex }},
#endif
<div>{{ $address->address }},</div>
<div>{{ $address->suburb }},</div>
<div>{{ $address->city }},</div>
<div>{{ $address->province }},</div>
<div>{{ $address->postal_code }}</div>
<div class="row edit-delete">
<div class="col-lg-2">
<a class="btn btn-primary edit-button" href="{{ route('account.edit.delivery.address', [$address->id]) }}">Edit</a>
<span>/</span>
</div>
<div class="col-lg-2">
<form action="{{ route('account.delete.delivery.address', [$address->id]) }}" method="post">
#csrf
{{ method_field('DELETE') }}
<button class="btn btn-danger delete-button"><i class="fa fa-pencil"></i> Delete</button>
</form>
</div>
</div>
#endforeach
</div>
</div>
<div class="col-lg-6">
Add Address
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingTwo">
<h2 class="mb-0">
<button class="btn btn-link collapsed" id="delivery-collection" type="button" data-toggle="collapse" data-target="#collapseTwo" aria-expanded="false" aria-controls="collapseTwo">
Delivery/Collection
</button>
</h2>
</div>
<div id="collapseTwo" class="collapse {{ $errors->confirmation_errors->any() ? 'show' : '' }}" aria-labelledby="headingTwo" data-parent="#accordionExample">
<div class="card-body">
<p>
Please select your delivery option
</p>
#if ($errors->confirmation_errors->has('delivery_collection'))
<div class="help-block text-danger">
<strong>Please select your delivery option</strong>
</div>
#endif
<div class="delivery-option">
<input type="radio" class="form-check-input {{ $errors->confirmation_errors->has('delivery_collection') ? 'is-invalid' : '' }}" name="delivery-option" id="delivery" value="delivery">
<label for="delivery" class="form-check-label">
Delivery
</label>
<input type="radio" class="form-check-input {{ $errors->confirmation_errors->has('delivery_collection') ? 'is-invalid' : '' }}" name="delivery-option" id="collection" value="collection">
<label for="collection" class="form-check-label">
Collection
</label>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseThree" aria-expanded="false" aria-controls="collapseThree">
Payment Options
</button>
</h2>
</div>
<div id="collapseThree" class="collapse {{ $errors->any() ? 'show' : '' }}" aria-labelledby="headingThree" data-parent="#accordionExample">
<div class="card-body">
#if ($errors->has('payment_option'))
<div class="help-block text-danger">
<strong>Please select a payment option</strong>
</div>
#endif
<div class="row">
<div class="col-lg-12">
<div class="payment-option">
<input type="radio" class="form-check-input {{ $errors->has('payment_method') ? 'is-invalid' : '' }}" name="payment_method" id="payfast-eft" value="payfast-eft">
<label for="payfast-eft" class="form-check-label">
EFT with PayFast
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-header" id="headingThree">
<h2 class="mb-0">
<button class="btn btn-link collapsed" type="button" data-toggle="collapse" data-target="#collapseFour" aria-expanded="false" aria-controls="collapseThree">
Review Your Order
</button>
</h2>
</div>
<div id="collapseFour" class="collapse" aria-labelledby="collapseFour" data-parent="#accordionExample">
<div class="card-body">
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Product</th>
<th scope="col">Code</th>
<th scope="col">Quantity</th>
<th scope="col">Unit Price</th>
<th scope="col">Total</th>
</tr>
</thead>
<tbody>
#foreach($products as $product)
<?php
$image = getImagesArray($product['item']['image']);
?>
<tr>
<th>
#if(!empty($image))
<img src={!! asset("product_images/thumbs/$image[0]") !!}>
#endif
{{ $product['item']['title'] }}
</th>
<td>{{ $product['item']['supplier_code'] }}</td>
<td>{{ $product['qty'] }}</td>
<td>R {{ $product['item']['price'] }}</td>
<td>R {{ $product['price'] }}</td>
</tr>
#endforeach
<tr>
<th colspan="4">
<div class="float-right">
Sub Total
</div>
</th>
<td id="totalPrice" data-price="{{ $totalPrice }}">
R {{ $totalPrice }}
</td>
</tr>
<tr class="delivery-fees">
<th colspan="4">
<div class="float-right">
Delivery Fee
</div>
</th>
<td id="delivery-price" data-price="{{ $delivery }}">
R {{ $delivery }}
</td>
</tr>
<?php
$total = $totalPrice + $delivery;
?>
<tr class="total-price">
<th colspan="4">
<div class="float-right">
Total:
</div>
</th>
<td>
R <span id="completePrice"></span>
</td>
</tr>
</tbody>
</table>
<div class="confirm-order-btn pb-15">
#foreach($products as $product)
<!-- BEGIN PAYFAST EFT -->
<div class="payfast-eft" style="display: none">
<form action="{{ route('payment.gateway') }}" method="POST">
#csrf
<input type="hidden" name="merchant_id" value="merchant_id">
<input type="hidden" name="merchant_key" value="merchant_key">
<input type="hidden" name="return_url" value="{{ route('payfast.success') }}">
<input type="hidden" name="cancel_url" value="{{ route('payfast.cancel') }}">
<input type="hidden" name="m_payment_id" value="{{ $invoice_number }}">
<input type="hidden" name="amount" class="completePrice" value="">
<input type="hidden" name="item_name" value="{{ $product['item']['title'] }}">
<input type="hidden" name="item_description" value="{{ $product['item']['description'] }}">
<input type="hidden" name="email_confirmation" value="1">
<input type="hidden" name="confirmation_address" value="">
<input type="hidden" name="payment_method" value="payfast_eft">
<input type="hidden" name="delivery_collection" class="delivery_collection" value="">
<input type="hidden" name="delivery_fee" class="delivery_fee" value="{{ $delivery }}">
<!-- THIS IS WHERE THE ADDRESS IS ADDED TO THE HIDDEN FORM -->
<input type="hidden" name="delivery_address" class="delivery_address" value="{{ $address }}">
<?php
$success = url('payfast-success');
$cancel = url('payfast-cancel');
$notify = url('payfast-notify');
$original_str = getAscii('merchant_id=merchant_id&merchant_key=merchant_key&return_url='.$success.'&cancel_url='.$cancel.'&notify_url='.$notify.'&m_payment_id=01AB&amount='.$totalPrice.'&item_name=Test Item&item_description=A test product&email_confirmation=1&confirmation_address=email#domain.com&payment_method=eft');
$hash_str = hash('MD5', $original_str);
$hash = strtolower($hash_str);
?>
<input type="hidden" name="signature" value="{{ $hash }}">
<button type="submit" class="btn btn-success float-right confirm-payfast-order">
Confirm Order
</button>
</form>
</div>
<!-- END PAYFAST EFT -->
#endforeach
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
var price = $("#totalPrice").data('price'); //get data-price by this syntax
$('#completePrice').html(price);
$('.completePrice').val(price);
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="collection"){
$(".delivery-fees").hide('slow');
var price = $("#totalPrice").data('price'); //get data-price by this syntax
var deliveryprice = 0; //get data-price by this syntax
var totalPrice = parseFloat(price) + parseFloat(deliveryprice);
$('#completePrice').html(totalPrice);
$('.completePrice').val(totalPrice);
$('.delivery_collection').val('collection');
$('.confirm-order').removeAttr('disabled');
$('.confirm-payfast-order').removeAttr('disabled');
}
if($(this).attr("value")=="delivery"){
$(".delivery-fees").show('slow');
var price = $("#totalPrice").data('price'); //get data-price by this syntax
var deliveryprice = $("#delivery-price").data('price'); //get data-price by this syntax
var totalPrice = parseFloat(price) + parseFloat(deliveryprice);
$('#completePrice').html(totalPrice);
$('.completePrice').val(totalPrice);
$('.delivery_collection').val('delivery');
}
});
/* BEGIN EFT PAYFAST */
$('input[type="radio"]').click(function(){
if($(this).attr("value")=="payfast-eft"){
$(".payfast-eft").show('slow');
$(".payfast-card").hide();
$(".i-pay").hide();
$(".confirm-order").hide();
$(".payfast-debit-card").hide();
}
});
/* END EFT PAYFAST */
});
</script>
#stop
my controller function
public function paymentGateway(Request $request)
{
if($request->payment_method == 'payfast_eft')
{
$process = 'Order Paid';
$paid = '1';
}
if($request->delivery_collection == 'collection')
{
$delivery_fee = null;
}else{
$delivery_fee = $request->delivery_fee;
}
$orders = Order::all();
$oldCart = Session::get('cart');
$cart = new Cart($oldCart);
$validation = Validator::make($request->all(), $this->getRules());
if($validation->fails())
{
return redirect()->route('cart.deliveryConfirmation')
->withErrors($validation, 'confirmation_errors')
->with('error', 'There were validation errors');
}
foreach($orders as $order)
{
$order = Order::find($order->id)->where('invoice_number', $request->m_payment_id)->first();
$order->cart = serialize($cart);
$order->address = $request->delivery_address;
$order->delivered_date = null;
$order->delivery_fee = $delivery_fee;
$order->delivery_option = $request->delivery_collection;
$order->process = $process;
$order->order_date = Carbon::now('+2:00');
$order->payment_method = $request->payment_method;
$order->paid = $paid;
$order->order_price = $request->amount;
$order->save();
}
$merchant_id = $request->merchant_id;
$merchant_key = $request->merchant_key;
$return_url = $request->return_url;
$cancel_url = $request->cancel_url;
$m_payment_id = $request->m_payment_id;
$amount = $request->amount;
$item_name = $request->item_name;
$item_description = $request->item_description;
$email_confirmation = '1';
$confirmation_address = 'email#domain.com';
$payment_method = $request->payment_method;
$signature = $request->signature;
if($request->payment_method == 'payfast_eft')
{
$url = 'https://sandbox.payfast.co.za/eng/process?merchant_id='.$merchant_id.'&merchant_key='.$merchant_key.'&return_url='.$return_url.'&cancel_url='.$cancel_url.'&m_payment_id='.$m_payment_id.'&amount='.$amount.'&item_name='.$item_name.'&item_description='.$item_description.'&email_confirmation='.$email_confirmation.'&confirmation_address='.$confirmation_address.'&payment_method='.$payment_method;
}
return redirect()->to($url);
}
protected function getRules()
{
return [
'delivery_collection' => 'required',
'payment_method' => 'required',
'delivery_address' => 'required'
];
}
basically on the paymentGateway controller you need to check whether the address is provided if not redirect to the previous page where address is selected and saved in db

Undefined variable: title (View: C:\xampp\htdocs\myproject\resources\views\categories\index.blade.php)

I try to make a page index.blade, but i getting error
Undefined variable: title (View: C:\xampp\htdocs\myproject\resources\views\categories\index.blade.php)
I am using laravel 5.4 PHP 7.0.33
Is there anything wrong with the code?
My Controller
<?php
namespace App\Http\Controllers;
use App\Category;
use Illuminate\Http\Request;
class CategoryController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$categories = Category::orderBy('created_at', 'DESC')->paginate(10);
return view('categories.index', compact('categories'));//
}
My index.blade
this is my view/categories/index.blade.php
#extends('layout.master')
​
#section('title')
<title>Manajemen Kategori</title>
#endsection
​
#section('content')
<div class="content-wrapper">
<div class="content-header">
<div class="container-fluid">
<div class="row mb-2">
<div class="col-sm-6">
<h1 class="m-0 text-dark">Manajemen Kategori</h1>
</div>
<div class="col-sm-6">
<ol class="breadcrumb float-sm-right">
<li class="breadcrumb-item">Home</li>
<li class="breadcrumb-item active">Kategori</li>
</ol>
</div>
</div>
</div>
</div>
​
<section class="content">
<div class="container-fluid">
<div class="row">
<div class="col-md-4">
#card
#slot('title')
<div class="card">
<div class="card-header with-border">
<h3 class="card-title">{{ $title }}</h3>
</div>
<div class="card-body">
{{ $slot }}
</div>
{{ $footer }}
</div>
#endslot
#if (session('error'))
#alert
<div class="alert alert-{{ $type }} alert-dismissible">
{{ $slot }}
</div>
#endalert
#endif
​
<form role="form" action="{{ route('kategori.store') }}" method="POST">
#csrf
<div class="form-group">
<label for="name">Kategori</label>
<input type="text"
name="name"
class="form-control {{ $errors->has('name') ? 'is-invalid':'' }}" id="name" required>
</div>
<div class="form-group">
<label for="description">Deskripsi</label>
<textarea name="description" id="description" cols="5" rows="5" class="form-control {{ $errors->has('description') ? 'is-invalid':'' }}"></textarea>
</div>
#slot('footer')
<div class="card-footer">
<button class="btn btn-primary">Simpan</button>
</div>
</form>
#endslot
#endcard
</div>
<div class="col-md-8">
#card
#slot('title')
List Kategori
#endslot
#if (session('success'))
#alert(['type' => 'success'])
{!! session('success') !!}
#endalert
#endif
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<td>#</td>
<td>Kategori</td>
<td>Deskripsi</td>
<td>Aksi</td>
</tr>
</thead>
<tbody>
#php $no = 1; #endphp
#forelse ($categories as $row)
<tr>
<td>{{ $no++ }}</td>
<td>{{ $row->name }}</td>
<td>{{ $row->description }}</td>
<td>
<form action="{{ route('kategori.destroy', $row->id) }}" method="POST">
#csrf
<input type="hidden" name="_method" value="DELETE">
<i class="fa fa-edit"></i>
<button class="btn btn-danger btn-sm"><i class="fa fa-trash"></i></button>
</form>
</td>
</tr>
#empty
<tr>
<td colspan="4" class="text-center">Tidak ada data</td>
</tr>
#endforelse
</tbody>
</table>
</div>
#slot('footer')
​
#endslot
#endcard
</div>
</div>
</div>
</section>
</div>
#endsection
My route web.php
Route::resource('/kategori', 'CategoryController',
['except' => ['create', 'show']]);
It should be like this
public function index()
{
$categories = Category::orderBy('created_at', 'DESC')->paginate(10);
$title = ''; //your title
return view('categories.index', compact('categories','title'));
}
because title not getting value from controller.
You dont pass variable title to view
Add some like this:
$title = 'Your title';
return view('categories.index', compact('categories','title'));
If title is a field of Category
If title is a field/member of Category model, then you would do {{ $category->title }}. I think this is the real error.
Otherwise
You need to define and send the variable as other have said.
$tile='Your Title';
return view('categories.index', compact('categories','title'));

Resources