Laravel Datatables 1 => active / 0 => not active - laravel

I'm using Laravel Framework and yajrabox datatables.
I have a table of users with 2 columns , a status column and a type of account column. Both of these holds ints.
How can I change these ints to strings? How can I perform an db request on the values of the $users variable in the cntroller?
Also is it possible to concat 2 columns into 1? So first_name and last_name into 1 column?
My current setup :
userlist.blade.php
#extends('app')
#section('content')
<div class='portlet light bordered '>
<div class='portlet-title'>
<div class='caption font-red-sunglo'>
Ledenbeheer
</div>
<div class="actions">
<a id='create' href="javascript:;" class="btn btn-circle red-sunglo">
Nieuw lid </a>
<a id='excel_import' href="javascript:;" class="btn btn-circle btn-default">
<i class="fa fa-fax"></i>Excel import </a>
</div>
</div>
<div class='portlet-body'>
<table class="table table-bordered table-striped table-hover" id="users-table">
<thead>
<tr>
<th>Naam</th>
<th>Email</th>
<th>Status</th>
<th>Account type</th>
<th>Created At</th>
<th>Updated At</th>
</tr>
</thead>
</table>
</div>
</div>
#stop
#push('scripts')
<script>
$(function() {
$('#users-table').DataTable({
processing: true,
serverSide: true,
ajax: '{!! route('configuratie_leden.data') !!}',
});
});
</script>
#endpush
UserController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use yajra\Datatables\Facades\Datatables;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class UserController extends Controller
{
//
public function getIndex(){
$users = User::all();
return view('users.userlist');
}
public function anyData(){
$users = User::select(['first_name','email','status','account_type','created_at','updated_at']);
return Datatables::of($users)->make();
}
}
Routes :
// Routes module configuratie
Route::controller('configuratie_leden','UserController',
[
'getIndex' => 'configuratie_leden',
'anyData' => 'configuratie_leden.data'
]);

Javascript solution:
columns: [
{
data: 'status',
name: 'status',
render: function ( data, type, full, meta ) {
return data ? "active" : "not active" ;
}
}
]
That's how you can change int to string. When data is 1, it will print "active".
Also is it possible to concat 2 columns into 1? So first_name and last_name into 1 column?
Yes it is. You do it in your query.
$users = User::select([
DB::raw("CONCAT(users.name,'-',users.surname) as name_surname"),
'email',
'created_at',
'updated_at'
]);
Example: http://datatables.yajrabox.com/eloquent/post-column-search

For column types, you can define attribute casts in your User model class
class User extends Model
{
protected $casts = [
'status' => 'string',
'account_type' => 'string',
];
protected $appends = ['full_name'];
public function getFullNameAttribute()
{
return $this->first_name . ' ' . $this->last_name;
}
}

Related

Laravel 9 Livewire get Datatable from DB using Ajax request

with laravel controller the app working without anz problem,like that:
UserController.php
public function user_list(Request $request)
{
if ($request->ajax()) {
$data = User::whereHas('roles')->get()->map(function($permission) {
return [
'id' => $permission->id,
'fullname' => $permission->name . ', ' . $permission->lastname,
];
});
return datatables()->of($data)->make(true);
}
$pageConfigs = ['pageHeader' => false];
return view('/content/apps/user/app-user-list', ['pageConfigs' => $pageConfigs]);
}
in my view :
<div class="card">
<div class="table-responsive">
<table class="users-table table">
<thead class="table-light">
<tr>
<th>id</th>
<th>Full Name</th>
</tr>
</thead>
</table>
</div>
</div>
#section('page-script')
<script>
$(function() {
$('.users-table').DataTable({
ajax: "list", // JSON file to add data
columns: [
// columns according to JSON
{ data: "id" },
{ data: "fullname" },
</script>
#endsection
and the route in Web.php is:
Route::get('users', [UsersController::class, 'user_list'])->name('list');
now when i want to use Livewire component instead of Laravel controller , where should i du my request in 'render' function or in 'mount' or schould i create another function, and how can i call if from route. or if there someway to call the function direct from controller without creating a new function on more time in Livewire component.
will be greate when someone can helpe

How to fetch field "nama" from Category Table in Product Table (Laravel 8)

I really need a solution for this problem. I'm using Laravel 8.
I am trying to fetch nama (name) field from the kategoris (category) table and show it in the produks (product) table.
View Blade with JS code in the end
#extends('back.index')
#section('content')
<main>
<div class="container-fluid">
<h1 class="mt-4">Produk</h1>
<ol class="breadcrumb mb-4">
<li class="breadcrumb-item"><a href={{ route('home') }}>Dashboard</a></li>
<li class="breadcrumb-item active">Produk</li>
</ol>
<div class="card mb-4">
<div class="card-body">
DataTables is a third party plugin that is used to generate the demo table below. For more information about DataTables, please visit the
<a target="_blank" href="https://datatables.net/">official DataTables documentation</a>
.
</div>
</div>
<div class="card mb-4">
<div class="card-header">
<i class="fas fa-table mr-1"></i>
DataTable Example
#auth
Tambah Produk
#endauth
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="produks-table" width="100%" cellspacing="0">
<thead>
<tr>
<th>Kode</th>
<th>Nama</th>
<th>Kategori</th>
<th>Updated At</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Kode</th>
<th>Nama</th>
<th>Kategori</th>
<th>Updated At</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
</main>
#endsection
#push('scripts')
<script>
$(function() {
$('#produks-table').DataTable({
processing: true,
serverSide: true,
ajax: 'produk/json',
columns: [
{ data: 'kode', name: 'kode' },
{ data: 'nama', name: 'nama',
fnCreatedCell: function (nTd, sData, oData, iRow, iCol) {
$(nTd).html("<a href='/kategoris/"+oData.id+"'>"+oData.nama+"</a>");
}
},
{ data: 'kategori', name: 'kategori.nama'},
{ data: 'updated_at', name: 'updated_at'},
]
});
});
</script>
#endpush
I already look for solutions for several days, but I still get this error message.
Product Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Produk()
{
return $this->belongsTo(Kategori::class, 'kategori_id');
}
}
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Kategori()
{
return $this->hasMany(Produk::class);
}
}
Product Controller
namespace App\Http\Controllers;
use App\Models\Produk;
use Illuminate\Http\Request;
use RealRashid\SweetAlert\Facades\Alert;
use Yajra\Datatables\DataTables;
class ProdukController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function json()
{
return Datatables::of(Produk::with('Kategori')->get())->make(true);
}
public function index()
{
return view('back.produk.show');
}
}
I was wrong while naming model functions.
Category Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Kategori extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Produk() //Here
{
return $this->hasMany(Produk::class);
}
}
Product Model
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Produk extends Model
{
use HasFactory;
protected $casts = [
'updated_at' => 'datetime:d/m/Y, H:i:s'
];
public function Kategori() //Here
{
return $this->belongsTo(Kategori::class, 'kategori_id');
}
}

404 error on route that exists in Laravel 8

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

How to display subnested arrays in Vue search component - Laravel

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.

laravel delete is not working

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.

Resources