Why Does Image Read Null When I Try To Delete My Category? - laravel

I am trying to find a way to delete my category that I have created. I have the image stored in my public folder and I get the error attempt to read image is null, I think the error has to do with category_id being null. How can I retrieve it for my category object?
//Controller class
class Index extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public $category_id;
//setting category_id
public function deleteCategory($category_id)
{
$this->category_id = $category_id;
}
public function destroyCategory() {
$category = Category::find($this->category_id);
// dd($this);
$path = 'uploads/category/'.$category->image;
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
public function render()
{
$categories = Category::orderBy('id', 'DESC')->paginate(10);
return view('livewire.admin.category.index', ['categories' => $categories]);
}
}
this is my component blades file that accompanies it.
//my blade file
<div>
<div class="modal fade" id="deleteModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="modal-title fs-5" id="exampleModalLabel">Category Delete</h1>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<form wire:submit.prevent="destroyCategory">
<div class="modal-body">
<h6>Are you sure you want to delete this data?</h6>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary">Yes. Delete</button>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
#if(session('message'))
<div class="alert alert-success">{{session('message')}}</div>
#endif
<div class="card-header">
<h4>
Category
Add Category
</h4>
</div>
<div class="card-body">
{{-- display all categories using livewire --}}
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($categories as $category)
<tr>
<td>{{$category->id}}</td>
<td>{{$category->name}}</td>
<td>{{$category->status == '1' ? "Hidden" : "Visible"}}</td>
<td>
Edit
<a href="#" wire:click="deleteCategory({{$category->id}})" class="btn btn-danger" data-bs-toggle="modal" data-bs-target="#deleteModal">
Delete
</a>
</tr>
#endforeach
</tbody>
</table>
<div>
{{$categories->links()}}
</div>
</div>
</div>
</div>
</div>
#push('script')
<script>
window.addEventListener('close-modal', event => {
$('#deleteModal').modal('hide');
})
</script>
#endpush

I wanted to add my sugestion as a comment, however is to long and it doesn't look good when i add the code, so i need to add a post.
I see that you are using deleteCategory() to get category_id and set it on a public varaible public $category_id;, when you get the variable then you try to delete the category with destroyCategory().
If that is true you don't need to create 2 functions for that,
so instead try and use this:
public function deleteCategory($category_id) {
$category = Category::find($category_id);
$path = 'uploads/category/'.$category->image;
// dd($path); <- try this on the debbuger, to see the path
if (File::exists($path)) {
File::delete($path);
}
$category->delete();
session()->flash('message', 'Category Deleted');
$this->dispatchBrowserEvent('close-modal');
}
Just use the function deleteCategory with the code of destroyCategory, and let the paramenter $category_id, because deleteCategory gets the id from the view
wire:click="deleteCategory({{$category->id}})"

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

How I can display data using wheredoesnthave

I have one problem.i have group table
This table has many to many relationship with users table and I have declared the relationship in both model.
And this is join table
Group.php
class Group extends Model
{
use SoftDeletes;
use HasFactory;
public $timestamps=true;
protected $dates = ['deleted_at'];
public function creators()
{
return $this->belongsToMany(User::class);
}
}
User.php
class User extends Authenticatable
{
use SoftDeletes;
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
/**
* The attributes that are mass assignable.
*
* #var string[]
*/
protected $dates = ['deleted_at'];
public function grp()
{
return $this->belongsToMany(Group::class);
}
}
This is the page where it will display the group that user have request
And supposedly in this page it will display the group that user have not request yet which is line no 3.
This is the code of my project.
Controller
public function redirectFunct(Request $request)
{
$role=Auth::user()->role;
$userid=Auth::user()->id;
if($role=='3')
{
$user = User::find(Auth::user()->id);
$groups=Group::with('creators');
$exists = Group::whereDoesntHave('creators', function ($query) {
$query->where('user_id', '=', Auth::user()->id);
})->get();
if($exists)
{
$users=Join::where('userID', '=', Auth::user()->id)->get();
}
$request = Join::where('userApprove','=','0')->where('userID',$userid)->get();
return view('member.dashboard',['users'=>$users,'user'=>$user,'groups'=>$groups,'exists'=>$exists,'request'=>$request]);
}
dasboard.blade.php
//sugessted group tab
<div class="tab-pane fade" id="sales" role="tabpanel" aria-labelledby="sales-tab">
<div class="row">
<div class="col-md-12 stretch-card">
<div class="card">
<div class="card-body">
<li class="nav-item nav-search d-none d-lg-block w-100">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="search">
<i class="mdi mdi-magnify"></i>
</span>
</div>
<input type="text" class="form-control" placeholder="Search now" aria-label="search" aria-describedby="search">
</div>
</li>
<br>
<div class="table-responsive">
<table id="" class="table">
<thead>
<tr>
<th>No.</th>
<th>Group Name</th>
<th>Group Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($exists as $group)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$group->groupName}}</td>
<td>{{$group->groupDesc}}</td>
<td>
<button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModalCenter{{$group->id}}">Details</button>
<!-- Modal -->
<div class="modal fade" id="exampleModalCenter{{$group->id}}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Group Details</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p>Group Name:{{$group->groupName}}</p>
<p>Group Description : {{$group->groupDesc}}</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</td>
<td><a href="{{url('/join',$group->id)}}"><button type="button" class="btn btn-secondary .btn-{color}">Join</button></td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
//pending group tab
<div class="tab-pane fade" id="t" role="tabpanel" aria-labelledby="t-tab">
<div class="row">
<div class="col-md-12 stretch-card">
<div class="card">
<div class="card-body">
<div class="table-responsive">
<table id="" class="table">
<thead>
<tr>
<th>No.</th>
<th>Group Name</th>
<th>Group Description</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($request as $req)
<tr>
<td>{{$loop->iteration}}</td>
<td>{{$req->group->groupName}}</td>
<td>{{$req->group->groupDesc}}</td>
<td><a href ="{{url('/cancelrequest',$req->id)}}"><button type="button" class="btn btn-danger .btn-{color}" onclick="return confirm('Are you sure?')">Cancel</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
I really appreciated if someone help me, please inform if there is not enough information, I will add it ASAP.

problem in datatable when use in livewire component

i use livewire defer loading for load data after rendering page.
After opening the page, the information is successfully received and displayed in the table
But the problem is that I use datatable and when the received information is displayed, datatable becomes a simple table. As if I did not use datatable at all.
This is the livewire component code
class Cryptolist extends Component
{
public bool $loadData = false;
public function init()
{
$this->loadData = true;
}
public function render()
{
try {
if ($this->loadData) {
$api = new \Binance\API('api','secret');
$prices = $api->coins();
$one = json_encode($prices, true);
$coins = json_decode($one , true);
} else {
$coins = [];
}
return view('livewire.backend.crypto.cryptolist')->with('coins' , $coins);
}catch(\Exception $e)
{
return view('wrong')->with('e' , $e);
}
}
}
And this is the component view where the table is located and displays the received information
<div wire:init="init">
#if ($loadData)
<div id="loadesh1" wire:ignore>
<table class="datatable-init nk-tb-list nk-tb-ulist" data-auto-responsive="false">
<thead>
<tr class="nk-tb-item nk-tb-head">
<th class="nk-tb-col"><span class="sub-text">name</span></th>
<th class="nk-tb-col tb-col-mb"><span class="sub-text">balance</span></th>
</tr>
</thead>
<tbody>
#foreach ($coins as $item => $value)
<tr class="nk-tb-item">
<td class="nk-tb-col">
<div class="user-card">
<div class="user-avatar d-none d-sm-flex">
#if(file_exists(public_path() . '/img/crypto/'.strtolower($value['coin'].".svg")))
<img style="border-radius: 0"
src="{{asset('/img/crypto/'.strtolower($value['coin']))}}.svg" class="img-fluid"
alt="">
#else
<img style="border-radius: 0"
src="https://demo.rayanscript.ir/-/vendor/cryptocurrency-icons/32/color/noimage.png"
class="img-fluid" alt="">
#endif
</div>
<div class="user-info">
<span class="tb-lead english" style="font-weight: bolder">{{$value['name']}}</span>
<span class="english">{{$value['coin']}}</span>
</div>
</div>
</td>
<td class="nk-tb-col tb-col-mb" data-order="{{$value['coin']}}">
<div class="btn-group" aria-label="Basic example">
<button type="button" class="btn btn-sm btn-dim btn-light"
wire:click="getBalance('{{$value['coin']}}')">
<div wire:loading wire:target="getBalance('{{$value['coin']}}')">
<span class="spinner-border spinner-border-sm" role="status"
aria-hidden="true"></span>
</div>
<span class="w-120px" id="coin-{{$value['coin']}}">get balance</span>
</button>
<button type="button" class="btn btn-sm btn-dim btn-primary">add coin</button>
</div>
</td>
</tr><!-- .nk-tb-item -->
#endforeach
</tbody>
</table>
</div>
#else
Loading data...
#endif
</div>
What do you think is the problem, what code is written incorrectly?

Trying to get property 'nom_matiere' of non-object laravel shows me this error

i want to display the name of matiere in this page but he shows me this error Trying to get property 'nom_matiere' of non-object
i make a selection in the note page to select the matiere then give a note to here it work but when i display the name of matiere in my table it give me error
model note
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
protected $fillable = ['note'];
public function matieres()
{
return $this->belongsToMany(Matiere::class);
}
}
model matiere
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Matiere extends Model
{
protected $fillable = ['nom_matiere','coef'];
public function notes() {
return $this->belongsToMany(Note::class);
}
}
my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Note;
use App\Matiere;
class NoteController extends Controller
{
public function index()
{
$notes = Note::paginate(5);
$matieres = Matiere::all();
return view('admin.notes',compact('notes','matieres'));
}
public function store(Request $request)
{
Note::create($request->all());
session()->flash('success',' cette note a été enregistré avec succés');
return redirect()->back();
}
public function update(Request $request, $id)
{
$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);
$note->update($request->all());
session()->flash('success','cette note a été modifié avec succés');
return redirect()->back();
}
public function destroy(Request $request)
{
$note = Note::findOrFail($request->note_id);
$note->delete();
session()->flash('success','cette note a été supprimé avec succés');
return redirect()->back();
}
}
my view
<section id="no-more-tables">
<table class="table table-bordered table-striped table-condensed cf">
<thead class="cf">
<tr>
<th>id-note</th>
<th>La note</th>
<th>nom matiere</th>
<th>les actions</th>
</tr>
</thead>
<tbody>
#foreach($notes as $note)
<tr>
<td class="numeric" data-title="id-note" >{{$note->id}}</td>
<td class="numeric" data-title="Nom">{{$note->note}}</td>
<td class="numeric" data-title="Nom">{{$note->matiere->nom_matiere}}</td>
<td>
<button href="#editEmployeeModal" class="btn btn-theme" data-target="#editEmployeeModal "data-mynote="{{$note->note}}" "data-mymatiere="{{$note->nom_matiere}}" data-catid={{$note->id}} class="edit" data-toggle="modal" ><i class="material-icons" data-toggle="tooltip" title="Edit"></i> </button>
<button href="#deleteEmployeeModal" class="btn btn-theme" data-target="#deleteEmployeeModal" data-catid={{$note->id}} class="delete" data-toggle="modal" > <i class="material-icons" data-toggle="tooltip" title="Delete"></i> </button>
</td>
</tr>
</tbody>
#endforeach
</table>
<div class="text-center">
{{ $notes->links() }}
</div>
<div class="clearfix">
<div class="hint-text">Affichage de <b>5</b> sur <b>25</b> entrées</div>
<div id="addEmployeeModal" href="create" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<form action="{{route('notes.store')}}" method="post">
{{csrf_field()}}
<div class="modal-header">
<h4 class="modal-title">Ajouter note</h4>
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<div class="form-group">
<label>La note</label>
<input type="text" id="note" name="note" class="form-control" required>
</div>
</div>
<div class="form-group select">
<select name="matiere_id">
<option value="">--selectionner la mtiére svp --</option>
#foreach($matieres as $matiere)
<option value="{{ $matiere->id }}">{{ $matiere->nom_matiere }}</option>
#endforeach
</select>
</select>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default" data-dismiss="modal" value="Annuler">
<input type="submit" class="btn btn-success" value="Ajouter">
</div>
</form>
</div>
</div>
You're calling $note->matiere in your view but the relationship is called matieres, which would be a collection.
Instead of:
<td class="numeric" data-title="Nom">{{ $note->matiere->nom_matiere }}</td>
You'd need:
<td class="numeric" data-title="Nom">
#foreach ($note->matieres as $matiere)
{{ $matiere->nom_matiere }}
#endforeach
</td>
I do however suspect that you have set your relationship up wrong. You've got the Note -> Matiere relationship set to belongsToMany, which means that you need a pivot table to contain the FK relationships. This would only be used if your Note is the child of many Matiere.
It does sound like you have your relationships set up wrong, but without really understanding what you're trying to do it's hard to tell you what exactly needs to be done.
Separate issue, but in your class update() method you've also got:
$note = Note::findOrFail($request->note_id);
$note = Matiere::findOrFail($request->note_id);
$note->update($request->all());
This means that you actually update the Matiere model no the Note model.

Unable to show data from database in Laravel after inserting data into database

I was able to insert data into database in Laravel but when I was trying to show the data in a tabular form I couldn't - it was displaying Route [stock_edit] not defined. (View: C:\wamp\www\pump\core\resources\views\dashboard\stock-show.blade.php)
Like I said in my quetion yesterday, I am new to Laravel and I am yet to understand the environment. I have been on this for the past 48 hours searching for help online but couldn't find a satisfactory ones
Here is my stock-show.blade.php
#extends('layouts.dashboard')
#section('title', 'All Stock')
#section('content')
#if(count($stock))
<div class="row">
<div class="col-md-12">
<div class="portlet light bordered">
<div class="portlet-title">
<div class="caption font-dark">
</div>
<div class="tools"> </div>
</div>
<div class="portlet-body">
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>ID#</th>
<th>Product Name</th>
<th>Price</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($stock as $p)
<tr>
<td>{{ $p->id }}</td>
<td>{{ $p->name }}</td>
<td>{{ $p->price }} </td>
<td>
<i class="fa fa-edit"></i> EDIT
<button type="button" class="btn btn-danger btn-sm delete_button"
data-toggle="modal" data-target="#DelModal"
data-id="{{ $p->id }}">
<i class='fa fa-times'></i> DELETE
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div><!-- ROW-->
<div class="text-center">
{!! $stock->render() !!}
</div>
#else
<div class="text-center">
<h3>No Data available</h3>
</div>
#endif
<!-- Modal for DELETE -->
<div class="modal fade" id="DelModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel"> <i class='fa fa-trash'></i> Delete !</h4>
</div>
<div class="modal-body">
<strong>Are you sure you want to Delete ?</strong>
</div>
<div class="modal-footer">
<form method="post" action="{{ route('stock_delete') }}" class="form-inline">
{!! csrf_field() !!}
{{ method_field('DELETE') }}
<input type="hidden" name="id" class="abir_id" value="0">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-danger">DELETE</button>
</form>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function () {
$(document).on("click", '.delete_button', function (e) {
var id = $(this).data('id');
$(".abir_id").val(id);
});
});
</script>
#endsection
and this is the DashboardController.php
//Stocks
public function createStock()
{
$data['site_title'] = $this->site_title;
$data['page_title'] = "Create Stock";
//$data['currency'] = Currency::all();
return view('dashboard.stock-create',$data);
}
public function storeStock(Request $request)
{
$this->validate($request,[
'name' => 'required|unique:stocks,name',
'price' => 'required',
//'currency_id' => 'required'
]);
try {
$stock = Input::except('_method','_token');
Stock::create($stock);
session()->flash('message', 'Stock Create Successfully.');
Session::flash('type', 'success');
return redirect()->back();
} catch (\PDOException $e) {
session()->flash('message', 'Some Problem Occurs, Please Try Again!');
Session::flash('type', 'danger');
return redirect()->back();
}
}
public function showStock()
{
$data['site_title'] = $this->site_title;
$data['page_title'] = "All Stock";
$data['stock'] = Stock::orderBy('id','ASC')->paginate(100);
return view('dashboard.stock-show',$data);
}
public function editStock($id)
{
$data['stock'] = Stock::findOrFail($id);
$data['site_title'] = $this->site_title;
$data['page_title'] = 'Edit Product';
$data['stock'] = Stock::all();
return view('dashboard.stock-edit',$data);
}
public function updateStock(Request $request,$id)
{
$stocks = Stock::findOrFail($id);
$this->validate($request,[
'name' => 'required|unique:stocks,name,'.$stocks->id,
'price' => 'required',
//'currency_id' => 'required',
]);
try {
$stock = Input::except('_method','_token');
$stocks->fill($stock)->save();
session()->flash('message', 'Stock Updated Successfully.');
Session::flash('type', 'success');
return redirect()->back();
} catch (\PDOException $e) {
session()->flash('message', 'Some Problem Occurs, Please Try Again!');
Session::flash('type', 'danger');
return redirect()->back();
}
}//Stocks End
And lastly the route.php
/* Stock Route List */
Route::get('stock-create',['as'=>'stock-create','uses'=>'DashboardController#createStock']);
Route::post('stock-create',['as'=>'stock-store','uses'=>'DashboardController#storeStock']);
Route::get('stock-show',['as'=>'stock-show','uses'=>'DashboardController#showStock']);
Route::get('stock-edit/{id}',['as'=>'stock-edit','uses'=>'DashboardController#editStock']);
Route::put('stock-edit/{id}',['as'=>'stock-update','uses'=>'DashboardController#updateStock']);
You have a typo in your code,
change stock_edit to stock-edit in your view

Resources