Method Illuminate\Database\Eloquent\Collection::appends does not exist. I used kyslik/column-sortable package, sort and pagination are not working - laravel

Student Model
class Student extends Model
{
use Sortable;
protected $fillable = ['firstName', 'lastName', 'date', 'score', 'batch_id', 'subject_id', 'mark_id'];
public $sortable = [
'id', 'firstName', 'lastName', 'date', 'score', 'batch_id', 'subject_id', 'mark_id', 'created_at'
];
public function batch()
{
return $this->belongsTo('\App\Batch', 'batch_id');
}
public function subject()
{
return $this->belongsTo('\App\Subject', 'subject_id');
}
public function mark()
{
return $this->belongsTo('\App\Mark', 'mark_id');
}
public function role()
{
return $this->belongsTo('\App\Role', 'role_id');
}
}
Route
Route::get('/studentrecord', 'StudentController#sort');
Controller
public function sort()
{
$sort = Student::sortable()->paginate(5);
return view('/studentrecord', compact('sort'));
}
studentrecord.blade
<table class="table table-striped">
<thead>
<tr class="thead">
<th>#sortablelink('Exam Date')</th>
<th>#sortablelink('Student ID Number')</th>
<th>#sortablelink('Student Name')</th>
<th>#sortablelink('Batch')</th>
<th>#sortablelink('Subject')</th>
<th>#sortablelink('Results')</th>
<th>#sortablelink('Marks')</th>
<th>#sortablelink('Updated')</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if($students->count())
#foreach($students as $student)
<tr class="tbody">
<td>{{$student->date}}</td>
<td>0001-00{{$student->id}}</td>
<td>{{$student->firstName.' '.$student->lastName}}</td>
<td>{{$student->batch->name}}</td>
<td>{{$student->subject->name}}</td>
<td>{{$student->score}}</td>
<td>{{$student->mark->name}}</td>
<td>{{$student->created_at->diffForHumans()}}</td>
<td>
<!-- View -->
#auth
#if(auth()->user()->role_id === 1)
<a href="/admin/editstudent/{{$student->id}}" class="btn btn-info form-control"><i
class="fa fa-edit" style="font-size:20px;color:#fff;"></i></a>
<form class="delete_form" action="/admin/removestudent/{{$student->id}}" method="POST">
#csrf
{{method_field("DELETE")}}
<button type="submit" class="btn btn-danger form-control">
<i class="fa fa-remove" style="font-size:20px;color:#fff;"></i>
</button>
</form>
#endif
#endauth
</td>
</tr>
#endforeach
#endif
</tbody>
</table>
<div>
{!! $students->appends(\Request::except('page'))->render() !!}
</div>
Laravel sort by descending or ascending with pagination.
if I clicked sort link it's not sorting but in url it changes to http://localhost:8000/studentrecord?sort=Batch&direction=asc and desc
please help me...thank you in advance

Instead of:
<th>#sortablelink('Student ID Number')</th>
Use this: <th>#sortablelink('id','Student ID Number')</th>
The first parameter of #sortablelink should be the column name in your database and the second parameter should be the name by which you want to display the column.
Do the same for all the table headings too.
Also, you need to add the following statement at the end of your table tag:-
</table>
{!! $students->appends(\Request::except('page'))->render() !!}
Here, div is not required.

Related

Laravel 7 Relationship many to many not working

An event can be in one to several years and a year can have several events, hence the use of the many-to-many relationship.
So I have 3 tables: evenements, years and evenement_year (pivot table).
I carefully read the Laravel 7 documentation and thought I had followed the procedure :
Evenement Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Evenement extends Model
{
protected $fillable = ['name', 'year_id','mnemonique','color'];
//One yar can have severals events and I give the name events_years to pivot
public function years()
{
return $this->belongsToMany(Year::class, 'evenement_year');
}
}
Year Model :
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Year extends Model
{
protected $fillable = ['name'];
public function evenements()
{
// a event can be in several years and I give the name events_years to pivot
return $this->belongsToMany(Evenemnt::class, 'evenement_year');
}
}
When I try to SELECT all events with years with this code (in the EventementController) at the index method :
<?php
namespace App\Http\Controllers;
use App\Evenement;
use App\EvenementType;
use App\Type;
use App\Year;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use stdClass;
class EvenementController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$evenements = Evenement::orderBy('year_id')->orderBy('mnemonique')->get();
$years = Year::all();
$evenTypes= EvenementType::all();
$types= Type::All();
return view('evenement.index', compact('evenements', 'years','evenTypes','types'));
}
}
I have this error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'year_id' in
'order clause' (SQL: select * from evenements order by year_id
asc, mnemonique asc)
Thank you for your help and have a nice Sunday.
Edit :
This is the view code :
#extends('adminlte::page')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.css">
#section('title', 'Cours')
#section('content_header')
<h1>Liste des évènements</h1>
#stop
#section('content')
<p>La liste de tous les évènements enregistrer</p>
<div class="card">
<div class="card-header">
Ajouter un événement
</div>
<div class="filtre">
<p margin:50>Selectionner une année <br>
<SELECT name="filtreAnnée" margin: 50>
<libellé>Selectionner une année</libellé>
<option valeur="tout">Toutes les années</option>
<option valeur="BA1">BA1</option>
<option valeur="BA2">BA2</option>
<option valeur="BA3">BA3</option>
<option valeur="MA1">MA1</option>
<option valeur="MA2">MA2</option>
</SELECT>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Mnémonique</th>
<th>Nom</th>
<th>Année</th>
<th>Couleur</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($evenements as $evenement)
<tr style="outline: thin solid">
<td>{{ $evenement->mnemonique }}</td>
<td>{{ $evenement->name }}</td>
<td>{{ $evenement->year->name }}</td>
<td>{{ $evenement->color}}</td>
<td>
<button type="button" class="btn btn-sm btn-warning" id="edit" data-toggle="modal" data-target="#edit-modal-{{ $evenement->id }}">
<i class="far fa-edit"></i>
</button>
#include('evenement.update')
<button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#delete-modal-{{ $evenement->id }}">
<i class="far fa-trash-alt"></i>
</button>
#include('evenement.delete')
</td>
</tr>
<?php $displayTh = false ?>
#foreach ($evenTypes as $evenT)
#if (!$displayTh)
<?php $displayTh=true ?>
<tr>
<th> </th>
<th>Type de cours </th>
<th>Nombre d'heure</th>
<th>
<button type="button" class= "btn btn-sm btn-primary" data-toggle="modal" data-target="#create-type-modal-{{ $evenement->id }}">
<i class="fa fa-plus-circle" aria-hidden="true"></i>
</button>
#include('evenement.createEvenementType')
</th>
</tr>
#endif
#if ($evenement->id == $evenT->evenement_id )
<tr>
<td> </td>
<td>{{$evenT->type->name}}</td>
<td>{{$evenT->total_hours}}</td>
<td><button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#delete-type-modal-{{ $evenT->id }}">
<i class="fas fa-minus-circle"></i>
</button>
#include('evenement.deleteEvenementType')
</td>
</tr>
#endif
#endforeach
<tr></tr>
#endforeach
<script>
$(".basic").spectrum();
</script><!-- palette de couleur-->
</tbody>
</table>
</div>
</div>
</div>
#stop
#section('css')
#stop
#section('js')
#stop
edit 2 (dd to array)
I need name from array62 and name from array 5 for example.
array:62 [▼
0 => array:7 [▼
"id" => 61
"name" => "Accueil"
"mnemonique" => "Accueil"
"color" => "#bcbcbc"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"years" => array:2 [▼
0 => array:5 [▼
"id" => 1
"name" => "BA1"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"pivot" => array:2 [▶]
]
1 => array:5 [▼
"id" => 4
"name" => "MA1"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"pivot" => array:2 [▶]
]
] ]
using with we can order by related data
For Ascending order
$evenements = Evenement::with(['years'=>function ($query){
$query->orderBy('year_id');
}])->get();
For Descending order
$evenements = Evenement::with(['years'=>function ($query){
$query->orderByDesc('year_id');
}])->get();
For retrieving those Evenement which has years then
$evenements = Evenement::with(['years'=>function ($query){
$query->orderByDesc('year_id');
}])->has('years')->get();
To get related table columns if its in blade file then
#foeach($evenements as $event)
#if(isset($event->years)&&count((array)$event->years))
#foreach($event->years as $year)
{{$year->name??null}}
#endforeach
#endif
#endforeach

Unlimited Nested Categories not working, Method Illuminate\Database\Eloquent\Collection::childrenRecursive does not exist

I tried #foreach $categories->children() aswell in index, still gives the same error which is Method Illuminate\Database\Eloquent\Collection::childrenRecursive does not exist, whichever function i use i get the same error, I want to display all the categories and their subcategories. Do not seem to figure out how
Category:
public function parent()
{
return $this->belongsTo(Category::class, 'cat_id');
}
public function children()
{
return $this->hasMany(Category::class, 'cat_id');
}
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
Controller:
public function index()
{
$categories = Category::with('childrenRecursive')->whereNull('cat_id')->get();
return view('categories.index',compact('categories'));
}
blade.php
#foreach ($categories->childrenRecursive() as $category)
<tbody>
<tr>
<td>
{{$category->name}}
</td>
<td data-cat-id="{{$category->id}}">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary add-subcat-modal-trigger">
Add Subcategory
</button>
<!-- Modal -->
</td>
<td>
<form action="{{route('categories.destroy',$category->id)}}" method="POST">
#csrf
#method('DELETE')
<button class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
The relationship definition seems to be logically incorrect.
Parent hasMany Children and Children belongsTo Parent seems logical
public function parent()
{
return $this->hasMany(Category::class, 'cat_id');
}
public function children()
{
return $this->belongsTo(Category::class, 'cat_id');
}
//Defining a relationship with eagerloading would not work
//and on top of it you are trying to eager load childrenRecursive within childrenRecursive relation definition
public function childrenRecursive()
{
return $this->children()->with('childrenRecursive');
}
#foreach ($categories as $cat)
#foreach($cat->children as $category)
<tbody>
<tr>
<td>{{$category->name}} </td>
<td data-cat-id="{{$category->id}}">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary add-subcat-modal-trigger">
Add Subcategory
</button>
<!-- Modal -->
</td>
<td>
<form action="{{route('categories.destroy',$category->id)}}" method="POST">
#csrf
#method('DELETE')
<button class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
</tbody>
#endforeach
#endforeach

Sorting and searching a foreign entity field on a Laravel Livewire table

I’ve just implemented a Livewire data table based on the Caleb’s tutorial on Laracasts. Everything works as expected when working with just one model. However I’m stuck trying to apply sorting and searching to a foreign model field.
User model:
namespace App;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use Notifiable;
use HasRoles;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
/**
* Get the user's email verified status.
*
* #param string $value
* #return string
*/
public function getEmailVerifiedAtAttribute($value)
{
if ($value == null) {
return "No";
}
return $value;
}
public function getRoleAttribute()
{
if($this->roles()->count() > 0) {
return $this->roles()->first()->name;
} else {
return "Usuario registrado";
}
}
public static function search($query)
{
return empty($query) ? static::query()
: static::where('name', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%');
}
}
Tried adding another orWhere() clause to the search() method in some ways. None worked. Now I left just the default ones.
Livewire controller:
namespace App\Http\Livewire\Users;
use Livewire\Component;
use Livewire\WithPagination;
class Table extends Component
{
use WithPagination;
public $perPage;
public $sortField;
public $sortAsc;
public $search;
public function mount()
{
$this->perPage = 10;
$this->sortField = 'name';
$this->sortAsc = true;
$this->search = '';
}
public function sortBy($field)
{
if ($this->sortField === $field) {
$this->sortAsc = ! $this->sortAsc;
} else {
$this->sortAsc = true;
}
$this->sortField = $field;
}
public function updatingPerPage()
{
$this->resetPage();
}
public function render()
{
return view('livewire.users.table', [
'users' => \App\User::search($this->search)
->with('roles')
->orderBy($this->sortField, $this->sortAsc ? 'asc' : 'desc')
->paginate($this->perPage),
]);
}
}
Livewire view:
<div>
<div class="row mb-4">
<div class="col form-inline">
Mostrar
<select wire:model="perPage" class="form-control form-control-sm custom-select custom-select-sm">
<option>10</option>
<option>100</option>
<option>1000</option>
</select>
registros
</div>
<div class="col-sm-3">
<input wire:model="search" class="form-control form-control-sm" type="text" placeholder="Buscar usuarios...">
</div>
</div>
<div class="table-responsive mb-4" >
<div class="table-header">
<table class="table table-sm text-nowrap" role="grid">
<thead>
<tr>
<th width="30%">
<a wire:click.prevent="sortBy('name')" role="button" href="#">
Nombre
#include('partials._sort-icon', ['field' => 'name'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('email')" role="button" href="#">
Correo electrónico
#include('partials._sort-icon', ['field' => 'email'])
</a>
</th>
<th width="30%">
<a wire:click.prevent="sortBy('')" role="button" href="#">
Rol
#include('partials._sort-icon', ['field' => ''])
</a>
</th>
<th></th>
</tr>
</thead>
</table>
</div>
<div class="table-body">
<table class="table table-sm table-hover text-nowrap" role="grid">
<tbody>
#foreach ($users as $user)
<tr>
<td width="30%">{{ $user->name }}</td>
<td width="30%">{{ $user->email }}</td>
<td width="30%">{{ $user->role }}</td>
<td>
<form method="POST" action="{!! route('backend.users.user.destroy', $user->id) !!}" accept-charset="UTF-8">
<input name="_method" value="DELETE" type="hidden">
{{ csrf_field() }}
<div class="btn-group btn-group-xs float-right" role="group">
#can('users.show')
<a href="{{ route('backend.users.user.show', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.show') }}">
<i class=" fas fa-fw fa-eye" aria-hidden="true"></i>
</a>
#endcan
#can('users.edit')
<a href="{{ route('backend.users.user.edit', $user->id ) }}" class="btn btn-outline-default btn-xs" title="{{ trans('users.edit') }}">
<i class=" fas fa-fw fa-pencil-alt" aria-hidden="true"></i>
</a>
#endcan
#can('users.destroy')
<button type="submit" class="btn btn-outline-default btn-xs" title="{{ trans('users.delete') }}" onclick="return confirm("{{ trans('users.confirm_delete') }}")">
<i class=" fas fa-fw fa-trash-alt" aria-hidden="true"></i>
</button>
#endcan
</div>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
<div class="table-footer">
<div class="text-muted">
Showing {{ $users->firstItem() }} to {{ $users->lastItem() }} out of {{ $users->total() }} results
</div>
<div>
{{ $users->links() }}
</div>
</div>
</div>
Tried also some ways to pass an argument to the sortBy() and [‘field’ => ‘’] on the role column. Now I left them with empty strings.
I know, this issue probably is more related to Laravel than Livewire, but I’ll really appreciate any help.
Update:
Solved using the Laravel Query Builder instead of Eloquent.

Delete Data using code igniter not working

I'm trying to delete data by id but it doesn't work.
I have some code like this.
Controller :
public function delete()
{
if (isset($_GET['del'])) {
$ii = $this->input->post('id');
$this->P6_model->delete($ii);
$this->load->view('p6home');
}
}
Model :
public function delete($i)
{
return $this->db->delete('contacts', array('id' => $i));
}
Routes :
$route['deldata'] = 'p6/delete';
View :
foreach ($contacts as $data) {
?>
<tr>
<input type="hidden" name="id" value="<?=$data->id?>"/>
<td data-label="Name"><?=$data->name?></td>
<td data-label="address"><?=$data->address?></td>
<td data-label="phone"><?=$data->phone?></td>
<td>
<button class="positive ui button">Update</button>
<button class="negative ui button" onclick="return confirm('Are you sure?')" name="del" href="deldata">Delete</button>
</td>
</tr>
<?php
}
?>
Thanks before.
you must have declared base_url, right? Use that in your link to redirect a page. Also, give the get parameter in the URL itself. POST will not work without a form. This should work for you. View:
<?php
foreach ($contacts as $data) {
?>
<tr>
<td data-label="Name"><?=$data->name?></td>
<td data-label="address"><?=$data->address?></td>
<td data-label="phone"><?=$data->phone?></td>
<td>
<button class="positive ui button">Update</button>
<button class="negative ui button" onclick="return confirm('Are you sure?')" name="del" href="<?php echo base_url('deldata')."/$data->id"; ?>">Delete</button>
</td>
</tr>
<?php
}
?>
Controller:
public function delete($id)
{
$this->P6_model->delete($id);
$this->load->view('p6home'); //instead of loading the view here, try redirecting to a controller function and load the view there.
}

ErrorException thrown with message "Trying to get property 'subo_name' of non-object

ErrorException thrown with message
"Trying to get property 'subo_name' of non-object (View:
C:\xampp\htdocs\org\resources\views\users\index.blade.php)"
Main model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Maino extends Model
{
protected $fillable = [
'maino_name'
];
public function subo()
{
return $this->hasMany('App\Subo');
}
}
Sub model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Subo extends Model
{
protected $fillable = [
'subo_name','maino_id'
];
public function maino()
{
return $this->belongsTo('App\Maino');
}
public function users()
{
return $this->hasMany('App\User');
}
}
user model
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password','role_id'
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
public function role()
{
return $this->belongsTo('App\Role');
}
public function profile()
{
return $this->hasMany('App\Profileinfo');
}
public function suborg()
{
return $this->belongsTo('App\Subo');
}
}
UserController code
public function index()
{
// $user=User::all();
$users=User::all();
return view('users.index',compact('users'));
}
index.blade.php
#extends('mainorg.main')
#section('title','Users')
#section('content')
<!-- DataTables Example -->
#if(Session::has('status'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span></button>
{{ Session::get('status') }}
</div>
#endif
<div class="card mb-3">
<div class="card-header">
<!-- <i class="fas fa-table"></i>
MainOrg --><div class="container"><button class="btn btn-primary float-right">Add SubOrg</button></div></div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>user</th>
<th>main org</th>
<th>suborg</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tfoot>
<tr>
<th>id</th>
<th>name</th>
<th>user</th>
<th>main org</th>
<th>suborg</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</tfoot>
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->role_name}}</td>
<td>{{$user->suborg->subo_name}}</td>
<td>Edit</td>
<td><form action="{{route('users.destroy',$user->id)}}" method="post">
#method('DELETE')
#csrf
<input type="submit" name="" value="DELETE" class="btn btn-danger">
</form></td>
</tr>
#endforeach
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#endsection
I am facing problem regarding to this code so please help me solve this problem ......................
The error means that one of your $users doesn't have a suborg while looping. So {{ $user->suborg }} is null, and you can't access ->name of null. To handle this, restrict your users to only those that have a suborg, or check while looping:
public function index() {
$users=User::with('suborg')->has('suborg')->get();
return view('users.index',compact('users'));
}
Note: You can use both with and has in a single query; they do different things.
Or, while looping your users, check existence:
#foreach($users as $user)
<tr>
<td>
#if($user->suborg)
{{ $user->suborg->subo_name }}
#else
No Suborg
#endif
</td>
</tr>
#endforeach
When you creating relation between two or more models then you should use relational method during model use using with in your eloquent call, you can also write when you want to pass multiple like - with(['suborg', 'example']). In index method, bellow $users variable make dd($users) and check is there have any relational data. If found I think, it should work.
public function index()
{
// $user=User::all();
$users=User::with('suborg')->get();
return view('users.index',compact('users'));
}
And your index.blade.php
#foreach($users as $user)
<tr>
<td>{{$user->id}}</td>
<td>{{$user->name}}</td>
<td>{{$user->role->role_name}}</td>
<td>{{$user->suborg->subo_name || 'Not Found'}}</td>
......
#endforeach

Resources