Laravel CRUD search function - laravel

I need your help that how can i make a search function for my laravel crud system?
I would like to make a search function where admins can search about users name and it works like a filter and after the search only shown the users that equals with the search.
admin.users.index (Blade file):
<div class="col-md-4">
<form action="/search" method="GET">
<div class="input-group">
<input type="search" name="search" class="form-control">
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">Keresés</button>
</span>
</div>
</form>
</div>
<div class="card">
<table class="table">
<thead>
<tr>
<th scope="col">Profilkép</th>
<th scope="col">Név</th>
<th scope="col">Email</th>
<th scope="col">Telefonszám</th>
<th scope="col">Műveletek</th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<th scope="row"><img src="/uploads/avatars/{{ $user->avatar }}" style=" width:32x; height:32px; float:left; border-radius:50%; margin-right:25px;"></th>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->phone }}</td>
<td>
<a class="btn btn-sm btn-primary" href=" {{ route('admin.users.edit', $user->id) }}" role="button">Szerkesztés</a>
<button type="button" class="btn btn-sm btn-danger" onclick="event.preventDefault(); document.getElementById('delete-user-form-{{ $user->id }}').submit()">
Törlés
</button>
<form id="delete-user-form-{{ $user->id }}" action="{{ route('admin.users.destroy', $user->id) }}" method="POST" style="display: none;">
#csrf
#method("DELETE")
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $users->links() }}
</div>
UserController Search function:
public function index(Request $request)
{
if(Gate::denies('logged-in')){
dd('no acces');
}
if(Gate::allows('is-admin')){
return view('admin.users.index', ['users' => User::paginate(10)]);
}
dd("adminnak kell lenned");
$users = User::paginate(10);
return view('admin.users.index')
->with([
'users' => $users
]);
}
public function search(Request $request) {
$search = $request->get('search');
$users = User::table('users')->where('name', 'like', '%'.$search.'%')->paginate(10);
return view('admin', ['users' => $users]);
}
And i dont have route in web.php because i dont know how can i solve this. :(
Please help me!
thank you for your reply!

$('.table').DataTable({
"paging": true,
"pageLength": 10,
"scrollY": 850,
"scrollX": true,
"columnDefs": [{
"targets": -1,
"orderable": false,
},
],
"ordering": false,
});
Put this command to javascript.
add this css
https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css
add this js
https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js
this is datatable search without anything. if you want use this method.

Related

Laravel 5.7 resource route works for index and create but not edit, delete and show due to missing parameter which is visible in URL

I made a resource for CRUD functionality in laravel 5.7. The index and create routes work okay but for update, show and delete it brings a "Missing required parameters for [Route: suffix.edit] [URI: suffix/{suffix}/edit]." or an error referencing to a missung parameter (id) but in the browser url, the id is displayed and all other CRUD resources have built are working
ROUTE:
Route::resource('suffix', SuffixController::class);
CONTROLLER:
public function show(Sms_message_suffix $sms_message_suffix)
{
//
return view('auth.smssuffix.show',compact('sms_message_suffix'));
}
public function edit(Sms_message_suffix $sms_message_suffix)
{
//
return view('auth.smssuffix.edit',compact('sms_message_suffix'));
}
public function update(Request $request, Sms_message_suffix $sms_message_suffix)
{
//
$request->validate([
'content' => 'required',
]);
$sms_message_suffix->update($request->all());
return redirect()->route('suffix.index')->with('success','Suffix updated successfully');
}
HTML
<table class="table table-hover" id="datatable">
<thead class="text-warning">
<th>Content</th>
<td>Actions</td>
</thead>
<tbody>
<tr>
#foreach($sms_message_suffix as $s)
<tr>
<td>{{ \Str::limit($s->content, 50) }}</td>
<td>
<form action="{{ route('suffix.destroy', $s->id) }}" method="POST">
<a class="btn btn-info" href="{{ route('suffix.show', $s->id) }}">
Show
</a>
<a class="btn btn-primary" href="{{ route('suffix.edit', $s->id) }}">
Edit
</a>
#csrf
#method('DELETE')
<button type="submit" class="btn btn-danger">Delete</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>

Laravel Problem Call to undefined method App\Models\User::getRoleNames()

#extends('layouts.app')
#section('content')
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Users Management</h2>
</div>
<div class="pull-right">
<a class="btn btn-success" href="{{ route('users.create') }}"> Create New User</a>
</div>
</div>
</div>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<table class="table table-bordered">
<tr>
<th>No</th>
<th>Name</th>
<th>Email</th>
<th>Roles</th>
<th width="280px">Action</th>
</tr>
#foreach ($data as $key => $user)
<tr>
<td>{{ ++$i }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->email }}</td>
<td>
#if(!empty($user->getRoleNames()))
#foreach($user->getRoleNames() as $v)
<label class="badge badge-success">{{ $v }}</label>
#endforeach
#endif
</td>
<td>
<a class="btn btn-info" href="{{ route('users.show',$user->id) }}">Show</a>
<a class="btn btn-primary" href="{{ route('users.edit',$user->id) }}">Edit</a>
{!! Form::open(['method' => 'DELETE','route' => ['users.destroy', $user->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</table>
{!! $data->render() !!}
<p class="text-center text-primary"><small>Tutorial by ItSolutionStuff.com</small></p>
#endsection
Im agree with Gary, if you are using Spatie add the next code to User.php
use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
use HasApiTokens, HasFactory, Notifiable, HasRoles;
Please add this method into User.php model file
public function getRoleNames()
{
return $this->belongsToMany(Role::class);
}
If this method not work then share you table structure and user model file code.
In the controller that call this view, you should to do:
$data = Model::all(); // ---> this solved that for me
return view('model.view',compact('data'));

how to implement Laravel AJAX live search on CRUD management table?

I have a CRUD table that's holding records of doctors that get
retrieved from the MySQL database. I've been following a few tutorials
and managed to set up AJAX live results search.
Now the problem comes from the fact that the logic is stored in a
Controller. I can succesfully retrieve the details from the database
using '-- foreach($data as $row) --' but I don't know how to retrieve
the CRUD actions ( In this case Delete.The create method is separated
from the table itself. I also can't implement status cell using i)
I've tried putting the actions inside the td'. .'td. tags but I get
Routing errors.
Any help is appreciated.
I have the code for the CRUD actions, images etc..inside
"index.blade.php". They should be somehow implemented in the
controller though. doctor controller
function liveSearchDoctor(Request $request)
{
if($request->ajax())
{
$output = '';
$query = $request->get('query');
if($query != '')
{
$data =Doctor::
where('name', 'like', '%'.$query.'%')
->orWhere('mobile', 'like', '%'.$query.'%')
->orWhere('email', 'like', '%'.$query.'%')
->orderBy('id', 'desc')
->paginate(2);
}
else
{
$data =Doctor::latest()->paginate(2);
}
$total_data = $data->count();
if($total_data > 0)
{
foreach($data as $row)
{
$output .= '
<tr>
<td class="center"><img src="'.$row->image.'" style="width:40px;height:40px;"/></td>
<td>'.$row->id.'</td>
<td>'.$row->name.'</td>
<td>'.$row->department->name.'</td>
<td>'.$row->email.'</td>
<td>'.$row->mobile.'</td>
//status should be implement here
<td><a class="btn btn-primary" href="'.route('doctors.edit',$row->id).'"><i class="fas fa-edit">Edit</i></a>
//delete form should be implement here
</td>
</tr>
';
}
}
else
{
$output = '
<tr>
<td align="center" colspan="5">No Data Found</td>
</tr>
';
}
$data = array(
'table_data' => $output,
'total_data' => $total_data
);
echo json_encode($data);
}
}
index.blade.php (( Note: The CRUD actions and everything is here
implemented succesfully. I however can't implement delete in the
controller )) here is the index.blade.php
#extends('layout.master')
#section('css')
#endsection
#section('content')
<br>
<div class="br-pagebody">
<div class="br-section-wrapper">
#include('include._message')
<div class="row">
<h6 class="br-section-label">Doctors List</h6>
</div>
<div class="row">
<div class="col-lg-4 ">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Search doctor Data" />
</div>
</div>
<div class="col-lg-3 offset-lg-5">
Add New Doctor
</div>
</div>
</br>
<div class="table-responsive">
<table class="table table-bordered table-colored table-dark">
<thead class="thead-colored thead-dark">
<tr>
<th>Image</th>
<th>Doctor Id</th>
<th>Name</th>
<th>Department</th>
<th>Email</th>
<th>mobile</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach($doctors as $doctor)
<tr>
<td class="center"><img src="{{URL::asset($doctor->image)}}" style="width:40px;height:40px;"/></td>
<td class="center">{{$doctor->id}}</td>
<td class="center">{{$doctor->name}}</td>
<td class="center">{{$doctor->department->name}}</td>
<td class="center">{{$doctor->email}}</td>
<td class="center">{{$doctor->mobile}}</td>
<td class="center">
#if($doctor->status==1)
<span class="badge badge-success">Active</span>
#else
<span class="label label-danger">Deactive</span>
#endif
</td>
<td class="center">
<a class="btn btn-primary" href="{{route('doctors.edit',$doctor->id)}}">
<i class="fas fa-edit">Edit</i>
</a>
{!! Form::open(['method' => 'DELETE','route' => ['doctors.destroy', $doctor->id],'style'=>'display:inline']) !!}
{!! Form::submit('Delete', ['class' => 'btn btn-danger']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
</tbody>
</table>
</div><!-- table-wrapper -->
<div class="d-flex justify-content-center">
{!! $doctors->links() !!}
</div>
</div>
</div>
#endsection
#section('js')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
fetch_doctor_data();
function fetch_doctor_data(query = '')
{
console.log(query)
$.ajax({
url:"{{route('search.doctor')}}",
method:"GET",
data:{'query':query},
dataType:'json',
success:function(data)
{
console.log(data)
$('tbody').html(data.table_data);
}
})
}
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_doctor_data(query);
});
});
</script>
#endsection

Laravel 5 : Undefined variable: post

in my view, I got an error, Undefined variable: post (View: /Applications/MAMP/htdocs/night-copy/resources/views/posts/index.blade.php).
I don't know why it happens. Please help me out.
I am creating a CRUD dashboard for admin side.
I will paste some of my codes, so if you need more codes, please ask me.
PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostsRequest;
use App\Http\Requests\Posts\UpdatePostRequest;
use App\Post;
class PostsController extends Controller
{
public function index()
{
return view('posts.index')->with('posts', Post::all());
}
public function create()
{
return view('posts.create');
}
public function store(CreatePostsRequest $request)
{
//upload the image to strage
//dd($request->image->store('posts'));
$image = $request->image->store('posts');
//create the posts
Post::create([
'image' => $image,
'title' => $request->title,
'place' => $request->place,
'map' => $request->map,
'date' => $request->date,
'tag' => $request->tag,
'description' => $request->description
]);
//flash message
session()->flash('success', 'Post created successfully.');
//resirect user
return redirect(route('posts.index'));
}
public function show($id)
{
//
}
public function edit(Post $post)
{
return view('posts.create')->with('post', $post);
}
public function update(UpdatePostRequest $request, Post $post)
{
$data = $request->only(['title', 'place', 'map', 'date', 'published_at', 'tag', 'description']);
//check if new image
if($request->hasFile('image')){
//upload it
$image = $request->image->store('posts');
//delete old image
$post->deleteImage();
$data['image'] = $image;
}
//update attributes
$post->update($data);
//flash message
session()->flash('success', 'Post updated sucessfully.');
//redirect user
return redirect(route('posts.index'));
}
public function destroy($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
if($post->trashed()) {
$post->deleteImage();
$post->forceDelete();
} else {
$post->delete();
}
session()->flash('success', 'Post deleted successfully.');
return redirect(route('posts.index'));
}
public function trashed()
{
$trashed = Post::onlyTrashed()->get();
return view('posts.index')->with('posts', $trashed);
}
public function restore($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
$post->restore();
session()->flash('success', 'Post restore successfully.');
return redirect()->back();
}
}
index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('/css/main-posts.css') }}">
<title>Event Confirmation</title>
</head>
<body>
<div class="container">
<div class="header">
<h2 class="logo">Dark Code</h2>
<input type="checkbox" id="chk">
<label for="chk" class="show-menu-btn">
<i class="fas fa-bars" style="color: white;"></i>
</label>
<ul class="menu">
<div class="menu-list">
<i class="fa fa-home" ></i>
Dashboard
Post
Category
Suspended
Logout
<label for="chk" class="hide-menu-btn">
<i class="fas fa-times" style="color: white;"></i>
</label>
</div>
</ul>
</div>
<div class="content">
<div class="userinfo">
<div class="content">
#if($posts->count() > 0)
<table class="table">
<thead>
<th>ID</th>
<th>Title</th>
<th>Location</th>
<th>Map</th>
<th>Date</th>
<th>Tags</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr></tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->place }}</td>
<td>{{ $post->map }}</td>
<td>{{ $post->date }}</td>
<td>{{ $post->tag }}</td>
#if($post->trashed())
<form action="{{ route('restore-posts', $post->id) }}" method="POST">
#csrf
#method('PUT')
<button class="save-btn" type="submit">Restore</button>
</form>
<br>
#else
<button btn="" class="edit-btn">
Edit
</button><br>
#endif
</td>
<td>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-btn" >
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button><br>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 style="margin: 15rem; color: white;">No Posts Yet</h3>
#endif
</div>
</div>
</div>
</div>
#if($post->trashed())
#else
<button btn="" class="add-btn">Add</button>
#endif
<div class="footer">
</div>
</body>
</html>
web.php
Route::resource('posts', 'PostsController');
Route::get('trashed-posts', 'PostsController#trashed')->name('trashed-posts.index');
Route::PUT('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
In your view, you're calling #if($post->trashed()) outside of #endforeach block so the $post is outside the scope by then and hence undefined variable.
Besides the #if statement there is redundant, you want the user to be able to create a new post regardless whether a specific post is trashed or not
<div class="content">
<div class="userinfo">
<div class="content">
#if($posts->count() > 0)
<table class="table">
<thead>
<th>ID</th>
<th>Title</th>
<th>Location</th>
<th>Map</th>
<th>Date</th>
<th>Tags</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr></tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->place }}</td>
<td>{{ $post->map }}</td>
<td>{{ $post->date }}</td>
<td>{{ $post->tag }}</td>
#if($post->trashed())
<form action="{{ route('restore-posts', $post->id) }}" method="POST">
#csrf
#method('PUT')
<button class="save-btn" type="submit">Restore</button>
</form>
<br>
#else
<button btn="" class="edit-btn">
Edit
</button><br>
#endif
</td>
<td>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-btn">
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button><br>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 style="margin: 15rem; color: white;">No Posts Yet</h3>
#endif
</div>
</div>
</div>
</div>
<button btn="" class="add-btn">Add</button>
In your view file Check this line #if($post->trashed()). this is outside of foreach loop. comment this line out or remove it

in laravel pass updated value from view to controller without submit button

I am tiring to store manager auth id, I have view page that contents of user tickets, in my database name called "ticket" in that table I have column name called "ticket_view_by_manager_id" in this column I am trying to store manager auth id, when manager open that ticket that time manager auth id, store in this "ticket_view_by_manager_id" column,
my controller
public function manager_assigned_Chat(Request $request, $ticket_id){
$this->validate($request, [
'ticket_view_by_manager_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input['ticket_view_by_manager_id'] = $request->submit;
$input->save();
}
my route
Route::post('user_ticket_chat{ticket_id}', 'Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat{ticket_id}');
my view "showing all user ticket list"
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
<form method="POST" action="{{ route('user_ticket_chat{ticket_id}')}}" enctype="multipart/form-data">
#csrf
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<td style="text-align:center"> {{ $key + 1 }} </td>
<td >{{ $my_tickets_list->ticket_id }}</td>
<td > <input type="hidden" name="submit" value="{{ Auth::user()->staff_id }}" href="ticket_chat{{ $my_tickets_list->ticket_id }}" >{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td >{{$my_tickets_list->created_at->todatestring()}} </td>
<td >{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
<input type="submit" value="Send.">
</form>
</tbody>
</table>
in your web.php
Route::post('user_ticket_chat','Services\User_TicketController#manager_assigned_Chat')->name('user_ticket_chat');
in your controller
public function manager_assigned_Chat(Request $request){
$this->validate($request,[
'ticket_id' => 'required',
]);
$input = User_Ticket::find($ticket_id);
$input->ticket_view_by_manager_id = Auth::user()->id; // or Auth::user()->staff_id; in your case
$input->save();
}
in blade view add meta tag :
<meta name="csrf-token" content="{{ csrf_token() }}">
in table :
<table id="myTable" class="table table-bordered table-striped">
<thead>
<tr>
<th>slNo</th>
<th>Ticket ID</th>
<th>Subject</th>
<th>Status</th>
<th>Last Update</th>
<th>Created</th>
</tr>
</thead>
<tbody>
#foreach ($my_tickets as $key=>$my_tickets_list)
<tr>
<tdstyle="text-align:center"> {{ $key + 1 }} </td>
<td>{{ $my_tickets_list->ticket_id }}</td>
<td class="ticket" data-ticketid="{{ $my_tickets_list->ticket_id}}">{{ $my_tickets_list->subject }}</td>
<td style="text-align:center">
#if($my_tickets_list->status == 'OPEN')
<span class="btn waves-effect waves-light btn-sm btn-success">OPEN</span>
#elseif($my_tickets_list->status == 'COMPLETE')
<span class="btn waves-effect waves-light btn-sm btn-info">COMPLETE</span>
#else($my_tickets_list->status == 'PENDING')
<span class="btn waves-effect waves-light btn-sm btn-danger">PENDING</span>
#endif
</td>
<td>{{$my_tickets_list->created_at->todatestring()}} </td>
<td>{{$my_tickets_list->updated_at->todatestring()}} </td>
</tr>
#endforeach
</tbody>
</table>
now using Jquery AJAX request :
<script>
$(document).on('click','.ticket',function(){
var ticketID=$(this).attr('data-ticket');
$.ajax({
url:'/user_ticket_chat',
type:'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType:'json',
data:{"ticket_id":ticketID},
success:function(response){
console.log(response);
},
error:function(){
alert('Error');
}
});
});
</script>
You should change your validator. It will be like, Please try this:
$this->validate($request, [
'submit' => 'required',
]);
Because your are not sending any info about ticket_view_by_manager_id from view.
Suggestion: may be your code is not well decorated. If you can please
have a look.

Resources