I get a 404 error when I access this edit_product route that is served by a Product controller, codes are attached below
Route::get('/edit_product{id}', 'ProductController#editproduct');
I would like your help in finding where the error in my code is. Thank you.
Here is the relevant code:
web.php
<?php
use Illuminate\Support\Facades\Route;
Route::get('/', 'ClientController#home');
Route::get('/checkout', 'ClientController#checkout');
Route::get('/shop', 'ClientController#shop');
Route::get('/cart', 'ClientController#cart');
Route::get('/login', 'ClientController#login');
Route::get('/signup', 'ClientController#signup');
Route::get('/dashboard', 'AdminController#dashboard');
Route::get('/addcategories', 'CategoryController#addcategories');
Route::post('/savecategories', 'CategoryController#savecategories');
Route::get('/categories', 'CategoryController#categories');
Route::get('/edit_category{id}', 'CategoryController#edit');
Route::get('/delete{id}', 'CategoryController#delete');
Route::get('/addslider', 'SliderController#addslider');
Route::get('/sliders', 'SliderController#slider');
Route::get('/addproducts', 'ProductController#addproducts');
Route::get('/products', 'ProductController#products');
Route::post('/saveproducts', 'ProductController#saveproduct');
Route::get('/edit_product{id}', 'ProductController#editproduct');
Route::get('/orders', 'ProductController#orders');
products.blade.php
#extends('admin.layouts.appadmin')
#section('title')
Products
#endsection
#section('content')
{{Form::hidden('', $increment=1)}}
<div class="card">
<div class="card-body">
<h4 class="card-title">Products table</h4>
<div class="row">
<div class="col-12">
<div class="table-responsive">
<table id="order-listing" class="table">
<thead>
<tr>
<th>Order #</th>
<th>Image</th>
<th>Name</th>
<th>Price</th>
<th>Category</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
#foreach ($products as $product)
<tbody>
<tr>
<td>{{$increment}}</td>
<td><img src="/storage/product_images/{{$product->product_image}}"></td>
<td>{{$product->product_name}}</td>
<td>KES{{$product->product_price}}</td>
<td>{{$product->product_category}}</td>
#if($product->status ==1)
<td>
<label class="badge badge-success">Activated</label>
</td>
#else
<td>
<label class="badge badge-danger">Un Activated</label>
</td>
#endif
<td>
<button class="btn-sm btn-outline-info" onclick="window.location ='{{url('/edit_product/'.$product->id)}}'">Edit</button>
Delete
#if($product->status==1)
Unactivate
#else
Activate
#endif
</td>
</tr>
{{Form::hidden('', $increment=$increment+1)}}
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('scripts')
<script src="{{'backend/js/data-table.js'}}"></script>
#endsection
ProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\Category;
class ProductController extends Controller
{
public function editproduct($id){
$product=Product::find($id);
return view('admin.product')->with('product', $product);
}
public function products(){
$products=Product::get();
return view('admin.products')->with('products', $products);
}
public function orders(){
return view('admin.orders');
}
public function addproducts(){
$categories=Category::All()->pluck('category_name', 'category_name');
return view('admin.addproducts')->with('categories', $categories);
}
public function saveproduct(Request $request){
$this->validate($request, ['product_name'=> 'required',
'product_price'=> 'required',
'product_image'=>'image|nullable|max:1999']);
if($request->input('product_category')){
if($request->hasFile('product_image')){
//1 : get filename with ext
$fileNameWithExt = $request->file('product_image')->getClientOriginalName();
//2 : get just file name
$fileName = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//3 : get just extension
$extension = $request->file('product_image')->getClientOriginalExtension();
//4 : file name to store
$fileNameToStore = $fileName.'_'.time().'.'.$extension;
//upload image
$path =$request->file('product_image')->storeAs('public/product_images', $fileNameToStore);
}
else{
$fileNameToStore ='noimage.jpg';
}
$product=new Product();
$product->product_name =$request->input('product_name');
$product->product_price =$request->input('product_price');
$product->product_category =$request->input('product_category');
$product->product_image =$fileNameToStore;
$product->status =1;
$product->save();
return redirect('/addproducts')->with('status', 'The '.$product->product_name.' Product has been saved successfully');
}else{
return redirect('/addproducts')->with('status1', 'You need to select a Category for your product');
}
}
}
I have tried.
replacing it with full namespace:
Route::get('/edit_product{id}', 'App\Http\Controllers\ProductController#editproduct');
php artisan cache:clear
php artisan cache:cache
Change your route to:
Route::get('/edit_product/{id}', 'ProductController#editproduct')
and also your delete and edit_category route:
Route::get('/delete/{id}', 'CategoryController#delete');
Route::get('/edit_category/{id}', 'CategoryController#edit');
you forgot the / in this route:
Route::get('/edit_product{id}', 'ProductController#editproduct');
change it to
Route::get('/edit_product/{id}', 'ProductController#editproduct');
and clear the route cache:
php artisan route:cache
Related
I am trying to export to excel using PHP 7, Laravel 5.8, Maatwebsite Excel 3.1. I successfully display on the view blade and also perform the filter.
Model:
use App\UserResponse;
Controller
public function userresponseReport(Request $request,$export=false)
{
$data['title'] = 'User Response';
$userresponses = DB::table('user_response as g')
->select(
//DB::raw('DATE(g.created_at) as created_date'),
DB::raw('g.created_at as created_date'),
'g.msisdn',
'g.game_code',
'g.answer',
'g.answer_code',
'g.Amount_charged',
'g.payment_ref',
'g.status',
'g.user_channel'
)
->orderByRaw('g.created_at DESC');
$start_date = $request->start_date;
$end_date = $request->end_date;
$render=[];
if(isset($request->start_date) && isset($request->end_date))
{
$userresponses=$userresponses->whereBetween('created_at',[$start_date.' 00:00:00',$end_date.' 23:59:59']);
$render['start_date']=$request->start_date;
$render['end_date']=$request->end_date;
}elseif(isset($request->start_date))
{
$userresponses=$userresponses->where('created_at',$request->start_date);
$render['start_date']=$request->start_date;
}
if(isset($request->msisdn))
{
$userresponses=$userresponses->where('msisdn','like','%'.$request->msisdn.'%');
$render['msisdn']=$request->msisdn;
}
if(isset($request->game_code))
{
$userresponses=$userresponses->where('game_code','like','%'.$request->game_code.'%');
$render['game_code']=$request->game_code;
}
if(isset($request->user_channel))
{
$userresponses=$userresponses->where('user_channel','like','%'.$request->user_channel.'%');
$render['user_channel']=$request->user_channel;
}
if(!empty($export))
{
return Excel::download(new UserresponseExport($userresponses->get()), 'userresponse.xlsx');
}
$userresponses= $userresponses->orderBy('created_at','DESC');
$userresponses= $userresponses->paginate(15);
$userresponses= $userresponses->appends($render);
$data['userresponses'] = $userresponses;
return view('report.userresponseReport',$data);
}
Then after that, the view blade:
userresponseReport.blade.php
<div class="row" style="margin-bottom: 10px">
{{ Form::model(request(),['method'=>'get']) }}
<div class="col-sm-2">
{{ Form::text('msisdn',null,['class'=>'form-control','placeholder'=>'MSISDN']) }}
</div>
<div class="col-sm-2">
{{ Form::text('game_code',null,['class'=>'form-control','placeholder'=>'Game Code']) }}
</div>
<div class="col-sm-2">
{{ Form::text('user_channel',null,['class'=>'form-control','placeholder'=>'Channel']) }}
</div>
<div class="col-sm-2">
{{ Form::date('start_date',null,['class'=>'form-control','placeholder'=>'Date']) }}
</div>
<div class="col-sm-2">
{{ Form::date('end_date',null,['class'=>'form-control','placeholder'=>'Date']) }}
</div>
<div class="col-xs-2">
{{ Form::submit('Search',['class'=>'btn btn-warning']) }}
<i class="fa fa-file-excel-o"></i> Excel
</div>
{{ Form::close() }}
</div>
<div class="box box-primary">
<div class="box-header with-border">
<table class="table table-bordered table-hover table-striped table-condesed" id="commenter_info_table">
<caption></caption>
<thead>
<tr>
<td>#</td>
<td>Date</td>
<td>MSISDN</td>
<td>Game Code</td>
<td>Game Name</td>
<td>Answer</td>
<td>Channel</td>
</tr>
</thead>
<tbody>
#foreach($userresponses as $key => $userresponse)
<tr>
<td>{{ ++$key }}</td>
<!-- <td>{{ $userresponse->created_date }}</td>-->
<td>{{ date('Y-m-d h:i:s A', strtotime($userresponse->created_date)) }}</td>
<td>{{ $userresponse->msisdn }}</td>
<td>{{ $userresponse->game_code }}</td>
<td>
#if($userresponse->game_code=='101')
Trivia
#elseif($userresponse->game_code=='102')
Predict and Win
#elseif($userresponse->game_code=='103')
Party With the BBN
#elseif($userresponse->game_code=='104')
Grand Prize
#elseif($userresponse->game_code=='105')
Happy Hour
#elseif($userresponse->game_code=='106')
Power Boost
#endif
</td>
<td>{{ $userresponse->answer }}</td>
<td>{{ $userresponse->user_channel }}</td>
</tr>
#endforeach
<tr>
<td colspan="14">
{{ $userresponses->links() }}
</td>
</tr>
</tbody>
</table>
Then the Export
UserresponseExport
class UserresponseExport implements FromView, WithHeadings, ShouldAutoSize, WithEvents, WithMapping
{
protected $userresponses;
public function __construct($userresponses = null)
{
$this->userresponses = $userresponses;
}
public function view(): View
{
return view('report.userresponseReport', [
'userresponses' => $this->userresponses ?: DB::table('user_response as g')
->select(
DB::raw('g.created_at as created_date'),
'g.msisdn',
'g.game_code',
'g.answer',
'g.answer_code',
'g.Amount_charged',
'g.payment_ref',
'g.status',
'g.user_channel'
)
->orderByRaw('g.created_at DESC')
]);
}
private $headings = [
'Date Created',
'MSISDN',
'game_code',
'Answer',
'Channel'
];
public function headings(): array
{
return $this->headings;
}
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
$cellRange = 'A1:E1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->getFont()->setSize(14);
},
];
}
}
Route
Route::get('/report/userresponse-report/{export?}', ['as' => 'userresponseReport', 'uses' => 'ReportController#userresponseReport']);
On the view blade, when I clicked on search everything was okay. But when I click on export, I got this error:
Symfony \ Component \ Debug \ Exception \ FatalErrorException (E_UNKNOWN)
Declaration of App\Exports\UserresponseExport::view(): App\Exports\View must be compatible with Maatwebsite\Excel\Concerns\FromView::view(): Illuminate\Contracts\View\View
What could have caused this error?
How do I resolve it?
This error indicates that your class App\Exports\UserresponseExport is not following the interface correctly.
By the error we can see that you need to have a method named view which you have, but your method have typehinted App\Exports\View as the return type instead of Illuminate\Contracts\View\View.
To fix this simply change your view method return type to Illuminate\Contracts\View\View.
Your code right now most likely says
public function view(): View
{
...
}
But as you are missing use Illuminate\Contracts\View\View; in your import statements, View is getting resolved to the current namespace of your class + the class you are trying to typehint, which results in App\Exports\View.
So another solution to this instead of typehinting the full namespace is to import Illuminate\Contracts\View\View, in your class by adding use Illuminate\Contracts\View\View; at the top of your file.
I am trying to get 3 copies of invoice printed in codeigniter. I have done a method to get pdf of my invoice. Is there any way to get 3 copies of invoice printed in normal html? I have tried it in by getting normal html by clicking on 'view' and pdf version of it when I click on 'view in pdf'
My View:
<?php include('admin_header.php');?>
<html>
<head>
<title></title>
</head>
<body>
<div class="container box">
<br />
<h3 align="center">Invoice List</h3><br />
<br />
<?php
if(isset($customer_data))
{
?>
<div class="table-responsive">
<table class="table table-striped table-bordered">
<tr>
<th>Invoice ID</th>
<th>Customer Name</th>
<th>Customer Phone Number</th>
<th>Customer Billing Address</th>
<th>Customer Shipping Address</th>
<th>Computer Serial Number</th>
<th>Computer Manufacturer</th>
<th>Computer Model</th>
<th>Computer Configuration</th>
<th>Monthly Hire Rate</th>
<th>Total Hire Rate</th>
<th>View</th>
<th>View in PDF</th>
</tr>
<?php
foreach($customer_data->result() as $row)
{
echo '
<tr>
<td>'.$row->invoice_id.'</td>
<td>'.$row->cus_name.'</td>
<td>'.$row->cus_phone.'</td>
<td>'.$row->cus_badr.'</td>
<td>'.$row->cus_sadr.'</td>
<td>'.$row->com_sno.'</td>
<td>'.$row->com_make.'</td>
<td>'.$row->com_model.'</td>
<td>'.$row->com_config.'</td>
<td>'.$row->mohr.'</td>
<td>'.$row->tohr.'</td>
<td>View</td>
<td>View in PDF</td>
</tr>
';
}
}
?>
</table>
</div>
<?php
{
if(isset($customer_details))
{
echo $customer_details;
}
}
?>
</div>
</body>
</html>
My Controller:
<?php
class HtmltoPDF extends MY_Controller
{
public function __construct()
{
parent::__construct();
$this->load->model('htmltopdf_model');
$this->load->library('pdf');
}
public function index()
{
$this->load->helper('form');
$data['customer_data']=$this->htmltopdf_model->fetch();
$this->load->view('admin/htmltopdf',$data);
}
public function details()
{
if($this->uri->segment(3))
{
$invoice_id=$this->uri->segment(3);
$data['customer_details']=$this->htmltopdf_model->fetch_single_details($invoice_id);
$this->load->view('admin/htmltopdf',$data);
}
}
public function pdfdetails()
{
if($this->uri->segment(3))
{
$invoice_id=$this->uri->segment(3);
$html_content='<h3 align="center">Invoice List</h3>';
$html_content .= $this->htmltopdf_model->fetch_single_details($invoice_id);
$this->pdf->loadHtml($html_content);
$this->pdf->render();
$this->pdf->stream("".$invoice_id."pdf", array("Attachment"=>0));
}
}
}
My Model:
<?php
class Htmltopdf_model extends CI_Model
{
public function fetch()
{
$this->db->order_by('invoice_id','DESC');
return $this->db->get('invoice');
}
public function fetch_single_details($invoice_id)
{
$this->db->where('invoice_id',$invoice_id);
$data=$this->db->get('invoice');
$output='<table width="100%" cellspacing="5" cellpadding="5">';
foreach ($data->result() as $row)
{
$output .='
<tr>
<td width="100%">
<p><b>Name : </b>'.$row->cus_name.'</p>
<p><b>Phone: </b>'.$row->cus_phone.'</p>
<p><b>Address: </b>'.$row->cus_sadr.'</p>
</td>
</tr>
';
}
$output .='
<tr>
<td colspan="2" align="center">Back</td>
</tr>
';
$output .='</table>';
return $output;
}
}
?>
For PDF Generation
$invoice_id=$this->uri->segment(3);
$html_content='<h3 align="center">Invoice List</h3>';
$html_content .= $this->htmltopdf_model->fetch_single_details($invoice_id);
// 3 pages of same content means three times $html_content concatenated
$this->pdf->loadHtml($html_content.$html_content.$html_content);
For HTML View
if($this->uri->segment(3))
{
$invoice_id=$this->uri->segment(3);
$data['customer_details']=$this->htmltopdf_model->fetch_single_details($invoice_id);
// Load the view 3 times
$this->load->view('admin/htmltopdf',$data);
$this->load->view('admin/htmltopdf',$data);
$this->load->view('admin/htmltopdf',$data);
}
Alternatively you can use a "for{ } loop" to iterate the page content three times.
I'm new on Laravel and try to implement real live search and filter on my project, but it doesn't work at all. I dont understand ajax ver much and just copy paste the code from other website. I tried to understand the code and I think its correct but it doesn't work, so please help. Thanks
Here is my controller
public function search(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data = Service::table('service')
->where('keterangan', 'like', '%'.$query.'%')
->orWhere('biaya', 'like', '%'.$query.'%')
->get();
}
else
{
$data = Service::table('service')
->orderBy('kodeService', 'asc')
->get();
}
$total_row = $data->count();
if($total_row > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td>'.$row->kodeService.'</td>
<td>'.$row->keterangan.'</td>
<td>'.$row->biayaService.'</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output
);
echo json_encode($data);
}
}
This is the script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('#table tbody').html(data.table_data);
}
});
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_customer_data(query)
});
});
Route :
Route::resource('service', 'ServiceController');
Route::get('service/search', 'Service#search')->name('live_search.action');
And index.blade
<table class="table table-striped table-hover table-bordered" id="table">
<thead>
<tr>
<th>Kode Service</th>
<th>Keterangan</th>
<th>Biaya</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
#foreach($service as $data)
<tr>
<td><?= $data->kodeService?></td>
<td><?= $data->keterangan ?></td>
<td><?= $data->biayaService?></td>
<td>
<a class="btn btn-sm btn-info" href="{{ route('service.edit', $data['kodeService']) }}"> <i class="oi oi-pencil"></i> Edit</a>
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#myModal"><span class="oi oi-trash"></span> Hapus</button>
</td>
</tr>
#endforeach
</tbody>
</table>
Put your route like this :
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');
After that open the Browser Console panel (Press F12 to open it) and check the Ajax request in Network tab.
Where you can get the specific error if any in the Response tab.
If you need an extra route to your resource route,you should place the new route before the resource route.
Route::get('service/search', 'ServiceController#search')->name('live_search.action');
Route::resource('service', 'ServiceController');
I'm having issues displaying eloquent relationship data via my vue.js search template, specifically my customer->biller fields.
models.student_first_name will display however
models.billers.biller_first_name wont show anything
The search function is working on my customers.index view using the following
CustomerDetailsController:
public function getData(Request $request){
$search = $request->search;
$customer = Customer::with('orders', 'billers', 'paymentplans', 'paidinfulls')->where(DB::raw('concat(student_first_name," ",student_last_name)'), 'like', '%'.$search.'%')->paginate(20);
return response()->json([
'model' => $customer
]);
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Request $request)
{
$customers = Customer::with('orders', 'paymentplans', 'billers')->orderBy('created_at', 'desc')->where('owner', Auth::user()->name)->paginate(25);
return view('customers.index', compact('customers', 'orders', 'paymentplans', 'funding'));
}
Customers.vue:
<template>
<div class="container">
<div class="field m-b-20">
<p class="control has-icons-left">
<input #keyup="fetchDataCustomer()" type="text" class="form-control input" name="search" v-model="search" placeholder="Search">
<span class="icon is-small is-left"><i class="fa fa-search"></i></span>
</p>
</div>
<table class="table">
<thead>
<tr>
<th>Student Name</th>
<th>Email</th>
<th>Biller Name</th>
<th>Biller Email</th>
<th>Courses Purchased</th>
<th>Deposit</th>
<th>Payment Plan</th>
<th>Accepted</th>
<th>Receipted</th>
</tr>
</thead>
<tbody>
<tr v-for="models in model.data">
<td>{{models.student_first_name}} {{models.student_last_name}}</td>
<td>{{models.student_email}}</td>
<td>{{models.billers.biller_first_name}}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import axios from 'axios'
export default{
data(){
return {
model: {},
search:'',
url:'api/customers'
}
},
created:function (){
this.fetchDataCustomer()
},
methods: {
fetchDataCustomer(){
var vm = this
axios.get(`${this.url}?search=${this.search}`)
.then(function (response) {
Vue.set(vm.$data, 'model', response.data.model)
})
}
}
}
</script>
JSON output of a search result
{"model":{"current_page":1,"data":[{"id":"627d0130-4dd0-11e8-91dd-69869f509337","enrolment_id":"John","student_first_name":"John","student_last_name":"Smith","student_email":"johnsmith#mail.com","address":"123 Test Street","suburb":"Townsville","postcode":"9999","state":"AAA","home_phone":null,"work_phone":null,"mobile_phone":"0444444444","dob":"1999-01-01 00:00:00","drivers_license_number":"123738974987498","owner":"Sales Man","owner_email":"salesman#business.com","created_at":"2018-05-02 16:16:43","updated_at":"2018-05-02 16:16:43","orders":[{"id":933,"fc_account":16,"customer_id":"627d0130-4dd0-11e8-91dd-69869f509337","biller_id":246,"enrolment_id":"John","course_id":5,"delivery_mode":0,"course_cost":"2000.00","deposit":null,"gov_funding":"0","location":"0","Monday":0,"Tuesday":0,"Wednesday":0,"Thursday":0,"Friday":0,"Saturday":0,"Sunday":0,"start_time":null,"end_time":null,"start_date":null,"enrolment_issue_date":"2018-05-02","sale_type":2,"created_at":"2018-05-02 16:17:24","updated_at":"2018-05-02 16:17:24"}],"billers":[{"id":246,"customer_id":"627d0130-4dd0-11e8-91dd-69869f509337","biller_first_name":"John","biller_last_name":"Smith","biller_email":"johnsmith#mail.com","biller_address":null,"biller_suburb":null,"biller_postcode":null,"biller_state":null,"biller_phone":null,"created_at":"2018-05-02 16:17:24","updated_at":"2018-05-02 16:17:24"}],"paymentplans":[{"id":"836e7e40-4dd0-11e8-a907-83f96c25a7d0","enrolment_id":"John","customer_id":"627d0130-4dd0-11e8-91dd-69869f509337","paysmart_id":"FIT69869f509337","biller_id":246,"biller_first_name":"John","biller_last_name":"Smith","biller_email":"johnsmith#mail.com","payment_method":-1,"contract_value":"1500.00","interest_free":1,"payment_frequency":1,"commencement_date":"2018-05-24 00:00:00","payment":"100.00","first_payment":"200.00","admin_fee":"1.30","setup_fee":"5.50","deposit":"500.00","deposit_payment_method":"Cash","special_conditions":null,"accepted":null,"accepted_student":null,"created_at":"2018-05-02 16:17:38","updated_at":"2018-05-02 16:17:38","submitted":1,"biller_ip":null,"student_ip":null}],"paidinfulls":[]}]
Vue Debug
Your models.billers is an array but you're treating it as an object. So you'll have to access it via models.billers[0].biller_first_name instead of models.billers.biller_first_name given that it is always available.
I am wondering how to put a csrf token in a form so that delete will work?
Here is my code:
Route:
Route::delete('category_delete/{id}',['as'=>'category_delete','uses'=>'CategoryController#destroy']);
index.blade.php
#section('adminContent')
{!! Form::token() !!}
<div class="table-responsive art-content">
<table class="table table-hover table-striped">
<thead>
<th> NAME</th>
<th> ACTIONS</th>
</thead>
<tbody>
#foreach($categoriesView as $category)
<tr>
<td>{!! $category->name!!}</td>
<td>{!! link_to_route('categories.edit', '', array($category->id),array('class' => 'fa fa-pencil fa-fw')) !!}</td>
<td><button type="button" id="delete-button" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o"></i></button>
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="pagination"> {!! $categoriesView->render() !!}</div>
</div>
#stop
CategoryController:
public function destroy($id,Category $category)
{
$category = $category->find ( $id );
$category->delete ();
Session::flash ( 'message', 'The category was successfully deleted!.' );
Session::flash ( 'flash_type', 'alert-success' );
}
If I used ajax, javascript or jquery, how should the code be?
Using jquery I would do something like the following.
Add the line below in the header of your home view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Now in your javascript
function deleteMe(button)
{
// You might want to put the ajaxSetup function where it will always load globally.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
if(confirm("Are you sure?"))
{
$.get(
'category_delete/'+button.id,
function( response )
{
// callback is called when the delete is done.
console.log('message = '+ response.message);
}
)
}
}
In index.blade.php, make your id more specific.
...
<td><button type="button" id=".$category->id" class="delete-button" data-url = "{!! url('category_delete')."/".$category->id !!}"><i class="fa fa-trash-o" onlick="deleteMe(this);></i></button>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return response()->json(
'message' => 'Deleted',
)
}
Note: No need to add
Form::token in your view
Hope this helps.....
Updated...........
If you were to do it using laravel only, I will suggest you use a link rather than the button you are using.
In index.blade.php, make your id more specific.
...
<td><a href="category_delete/".$category->id class="delete-button" data-url = "{!! url('category_delete')!!}"><i class="fa fa-trash-o"></i></td>
...
In your controller
public function destroy($id,Category $category){
$category = $category->find ( $id );
$category->delete ();
return view('index');//important.
}
If you want your link to look like a button, use css or a css framework like bootstrap
That should be it. hope this helps again.