Right so on my website, registered users can create posts and like other peoples posts. When displaying all the posts i have options where the users can sort by title, date and like count. I have done the title and date but im having trouble with sorting by like count. What would be the best way to implement this feature into my system.
This is my post controller method for retrieving and ordering the posts:
public function getEvents(Request $request){
if($request['sort'] == "created_at"){
$posts = Post::orderBy('created_at', 'desc')->get();
}
elseif($request['sort'] == "title"){
$posts = Post::orderBy('title', 'desc')->get();
}
elseif($request['sort'] == "like"){
//how would I go about ordering by like count here
}
return view ('eventspage', ['posts' => $posts]);
}
Here is my view where users select what to order by:
<form action="{{ route('events') }}">
<select name="sort" onchange="this.form.submit()" class="form-control">
<option value="">Sort By</option>
<option value="created_at">Date</option>
<option value="title">Title</option>
<option value="like">Likes</option>
<input type="hidden" name="formName" value="sort">
</select>
</form>
Use this:
$posts = Post::withCount('likes')->orderByDesc('likes_count')->get();
This requires a likes relationship in the Post model:
public function likes() {
return $this->hasMany(Like::class);
}
Related
This question already exists:
how to implement a search with many filters that the user chooses in Laravel? [closed]
Closed 2 years ago.
I have a code on my blade template page with a search field and a select with options.
The user types what he wants to search in the search field and selects a search option, which must be sent to the controller to search and return the searched customers according to the selected search option.
The view part is ready, but I am still unable to find a way for the controller to choose this option and do the research accordingly.
My client view page:
<form action="{{ route('search') }}" method="POST" class="form form-inline" role="search">
#csrf
<label class="procurar">Procurar for:</label>
<div class="col-3">
<input type="text" name="nome" class="form-control" placeholder="">
</div>
<label>Filtro: </label>
<div class="form-group">
<select name="busca" class="form-control">
<option value="nome">Nome</option>
<option value="tipo_pessoa">Tipo de Pessoa</option>
<option value="cidade">Cidade</option>
<option value="uf">Estado</option>
<option value="cpf_cnpj">CPF /CNPJ</option>
<option value="tipo_cliente">Tipo de Cliente</option>
<option value="onde_nos_encontrou">Onde nos encontrou</option>
</select>
</div>
</form>
My search function:
public function search(Request $request)
{
if ($request->nome)
{
$nome = $request->nome;
$clients = Client::where('nome', 'like', '%'.$nome.'%')
->orderBy('nome')
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
if ($request->uf)
{
$uf = $request->uf;
$clients = Client::where('uf', 'like', '%'.$uf.'%')
->orderBy('uf')
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
return redirect()->route('clients.index');
}
Thanks for help!
You need to get the value of busca as that's a select's name. The selected value will be there.
public function search(Request $request)
{
$busca = $request->input('busca', 'nome');
$clients = Client::where($busca, 'like', '%' . $busca . '%')
->orderBy($busca)
->paginate(8);
return view('clients.index')
->with('clients', $clients);
}
On my website, users can display posts created by other users. However, I have 2 select boxes, one for ordering by name or date and the other is ordering by category. The way I have done it is incorrect and I am aware of that. The simple reason for this is that I don't know how to make an if check on which form submitted the request.
Here is my controller method for displaying the events:
public function getEvents(Request $request){
if($request['sort'] == "created_at"){
$posts = Post::orderBy('created_at', 'desc')->get();
}
elseif($request['sort'] == "title"){
$posts = Post::orderBy('title', 'desc')->get();
}
elseif($request['category'] == "sport"){
$post = Post::where('type', '=', 'sport' )->get();
}
elseif($request['category'] == "culture"){
$post = Post::where('type', '=', 'culture' )->get();
}
elseif($request['category'] == "other"){
$post = Post::where('type', '=', 'other' )->get();
}
else{
$posts = Post::orderBy('created_at', 'desc')->get();
}
return view ('eventspage', ['posts' => $posts]);
}
This is currently incorrect, I want it to follow this structure:
if(request submitted by 'sort')
then do this...
elseif(request submitted by 'category')
then do this...
Here is my view containing the 2 select boxes:
<div class="row">
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="category" onchange="this.form.submit()" class="form-control">
<option value="sport">sport</option>
<option value="culture">Culture</option>
<option value="other">Other</option>
</select>
</form>
</div>
<div class="col-md-6">
<form action="{{ route('events') }}">
<select name="sort" onchange="this.form.submit()" class="form-control">
<option value="created_at">Date</option>
<option value="title">Title</option>
</select>
</form>
</div>
</div>
You can have a hidden input in your form with name as formName and the respective values.
Then it's easy to check which form submitted.
//Category form
<input type="hidden" name="formName" value="category">
//Sort form
<input type="hidden" name="formName" value="sort">
Then, in the controller:
if($request['formName'] == 'category') //request submitted by 'category'
//then do this...
elseif($request['formName'] == 'sort') //request submitted by 'sort'
//then do this...
Just be careful not to put too much different code in both conditionals. If you find yourself having two entirely different functions, create an action for each form.
I have two tables on for users, and one for cases, I want my search form that contains a dropdown list selected item to pass it to a controller by using a model, so I can search the two tables at a time.
this is my form:
<form method="POST" action="'dashboard_c/search_engin_user/'.$this->uri->segment(3);?>" method="post">
<select id="dropdown" name="filter">
<option value=""></option>
<option value="1">User Name</option>
<option value="2">Badge Number</option>
<option value="3">Case Type</option>
<option value="5">Case Date</option>
<option value="6">Case Status</option>
<option value="7">Case User</option>
</select>
<!--search bar for search term input -->
<input id="search" type="text" name="search" value="" />
<input id="submit" type ="submit" name ="filter" value ="Search">
</form>
And in my model I tried to wrote this to join the two tables:
function search($search_term) {
$this->db->select('*');
$this->db->from('user');
$this->db->join('cases', 'cases.user_id = user.id');
$this->db->like('user.username', $search_term);
$this->db->or_like('user.badge_number', $search_term);
$this->db->or_like('cases.type', $search_term);
$this->db->or_like('cases.date', $search_term);
$this->db->or_like('cases.statuse', $search_term);
$this->db->group_by("user.id");
return $this->db->get();
//$qu = $query->result_array();
}
I also tried to put two models and each search of table in one separated model.
This is my controller, but I have no result since i'm filtering two tables in one mode and one form
public function search_engin_user()
{
$this->load->model('users_m');
$this->load->model('cases');
$filter = $this->input->post('filter');
$field = $this->input->post('field');
//$field2 = $this->input->post('field2');
$data['id'] = $this->uri->segment(3);
$data['subview'] = 'include/d_header';
$search_term = $this->input->post('search');
if(isset($filter)and !empty($search_term)){
$this->users_m->getUsersSearch($field,$search_term);
redirect("dashboard_c/show_user/" . $this->uri->segment(3));
}
I want to know how should I pass the dropdown selected option to a controller and having one model to process the two tables and the result will show in two different views one to show user and one to show the case I searched for.
I have an edit page where the data of a product is passed, on this page I have a select box for the category change, in it I need to insert all the categories registered in my database but only shows the category related to the product of the page.
Select Box of Edit view
<select class="selectpicker" data-live-search="true">
#foreach($produtos->categoria as $categoria)
<option data-tokens="{{$categoria->erp_name}}" value="{{$categoria->erp_categoryid}}">{{$categoria->erp_name}}</option>
#endforeach
</select>
ProdutosController
public function edit($id)
{
$produtos = Produtos::find($id);
return view('functions.edit')->with('produtos', $produtos);
}
Routes
Route::get('/product/update/{id}', 'ProdutosController#edit')->name("product::updateGet");
Route::post('/product/update/{id}', 'ProdutosController#update')->name("product::updatePost");
Any suggestions?
The problem is you are looping through the categories of that product, not all categories. Here is a solution:
public function edit($id)
{
$produtos = Produtos::find($id);
$categories = Category::all();
return view('functions.edit', compact('produtos', 'categories'));
}
then in your view:
<select class="selectpicker" data-live-search="true">
#foreach($categories as $categoria)
<option data-tokens="{{$categoria->erp_name}}" value="{{$categoria->erp_categoryid}}">{{$categoria->erp_name}}</option>
#endforeach
</select>
problem
I have tables of teachers, students and classes, this is what the students table looks like.
I need to be able to search through and filter the table to find the students. There will be about 100 students to sort through.
I have a MVP that works but I know it is a bad way of solving the problem.
What I have tried
The flow goes like this...
By default when someone lands on the list of students all students
are displayed.
However when someone enters a search and clicks on the 'Go' the form
is submitted back to the same page... where the values are caught in
an if/else statement.
If the fields are set then a different method in the model is called, which takes two parameters, $field (the database column name to search by) and $search the string that we want to partially match.
Here is the search form
<form class="form-inline" action="<?php echo base_url() . 'admin/students'; ?>" method="post">
<select class="form-control" name="field">
<option selected="selected" disabled="disabled" value="">Filter By</option>
<option value="first_name">First Name</option>
<option value="last_name">Last Name</option>
<option value="email">Email Name</option>
</select>
<input class="form-control" type="text" name="search" value="" placeholder="Search...">
<input class="btn btn-default" type="submit" name="filter" value="Go">
</form>
Which submits to the Students Controller
public function index()
{
$filter = $this->input->post('filter');
$field = $this->input->post('field');
$search = $this->input->post('search');
if (isset($filter) && !empty($search)) {
$this->load->model('students/Student_Model');
$data['students'] = $this->Student_Model->getStudentsWhereLike($field, $search);
} else {
$this->load->model('students/Student_Model');
$data['students'] = $this->Student_Model->getStudents();
}
$data['module'] = 'admin';
$data['view_file'] = 'students/view';
$this->load->module('templates');
$this->templates->admin($data);
}
Which calls the in the getStudentsWhereLike() method in the Student_Model
public function getStudentsWhereLike($field, $search)
{
$sql = "
SELECT * FROM students
WHERE $field LIKE '%$search%'
ORDER BY `students`.`registered_at`
";
$query = $this->db->query($sql);
return $query->result();
}
Question
Is this the right way to approach the issue? I know that the $this->db->query($sql) method is open to SQL attacks so I will sanitize input, but I am interested if there is a better, more flexible, standardized approach to filtering/searching tables with Codeigniter.
Use Codeigniter's active record instead:
public function getStudentsWhereLike($field, $search)
{
$query = $this->db->like($field, $search)->orderBy('registered_at')->get('students');
return $query->result();
}