search function from the database in laravel 5.8 - php

This search function does not work yet. I don't know what the reason is.
Can anyone help me to find the mistake?
This is in the studentcontroller
public function testsearch()
{
$q = Input::get ( 'q' );
if($q != ""){
$student = Student::where ( 'uniid', 'LIKE', '%' . $q . '%' )->get();
if (count ( $student ) > 0)
return view ( 'Searchstudent' )->withDetails ( $student )->withQuery ( $q );
else
return view ( 'Searchstudent' )->withMessage ( 'No Details found. Try to search again !' );
}
return view ( 'Searchstudent' )->withMessage ( 'No Details found. Try to search again !' );
}
and this is Searchestudant.blade.php
<html>
<head>
<title>Search</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<form action="/Searchstudent" method="POST" role="Searchstudent">
<div class="input-group">
<input type="text" class="form-control" name="q"
placeholder="Search sickleave number"> <span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<div class="container">
#if(isset($students))
<table class="table table-striped">
<thead>
<tr>
<th>unique id</th>
<th>student_id</th>
</tr>
</thead>
<tbody>
#foreach($students as $student)
<tr>
<td>{{$student->uniid}}</td>
<td>{{$student->student_id}}</td>
</tr>
#endforeach
</tbody>
</table>
#elseif(isset($message))
<p>{{ $message }}</p>
#endif
</div>
</body>
</html>
and this is the route
```Route::get('/searechstudent','StudentController#testsearch'); ```
The error shows when I run this function:
MethodNotAllowedHttpException No message

You have mismatched your routing between your blade form and your routes file. In your blade you have called POST:
<form action="/Searchstudent" method="POST" role="Searchstudent">
With Laravel, it must match in the routing file. In your web.php file (routing) you are accepting a GET response:
Route::get('/searechstudent','StudentController#testsearch');
Change the route to a POST response:
Route::post('/searechstudent','StudentController#testsearch');
Also, it may help you to look at the PHP method compact() for your return variables from your controller in the testsearch() method - it keeps things consistent and easy to read.

Be aware of your route address, it must be exact route as you called in form. Capital character is different with normal character
Route::post('/Searchstudent','StudentController#testsearch');

Related

PHP/Laravel search query controller

I am trying to build a search query to use the user's search input (gene name) and return the gene location and symbol from a JSON file I loaded in.
My Site Controller for the JSON input:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SiteController extends Controller
{
public function index()
{
$results = file_get_contents("http://ftp.ebi.ac.uk/pub/databases/genenames/hgnc/json/locus_groups/protein-coding_gene.json");
$data = json_decode($results, true);
dd($data);
}
}
My Search Controller for the search function:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function search(Request $request){
// Get the search value from the request
$search = $request->input('search');
// Search in the name column from the data table
$data = data::query()
->where('name', 'LIKE', "%{$search}%")
->get();
// Return the search view with the results compacted
return view('search', compact('data'));
}
}
My routes:
<?php
use Illuminate\Support\Facades\Route;
//use App\Http\Controllers\Controller;
use App\Http\Controllers\SiteController;
Route::get('/data', [SiteController::class, 'index']);
Route::get('search', [SearchController::class, 'search']);
Route::get('/', function () {
return view('welcome');
});
And my welcomeblade:
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Geisinger</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/1866062af8.js" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="{{ asset('/styles.css') }}" >
</head>
<body>
<img src="{{ asset('/Geisinger_logo.jpg') }}" alt="Geisinger Logo">
<h1> Geisinger Gene Search </h1>
<div class="container my-8 py-5 px-5 mx-5">
<!-- Search input -->
<form action="{{ route('search') }}" method="GET">>
<input type="search" class="form-control" placeholder="Search Gene Name" name="search">
<button type="submit">Search</button>
</form>
<div class="d-grid gap-2 col-6 mx-auto">
<button class="btn btn-outline-dark" type="button">Search <i class="fa-solid fa-magnifying-glass"></i></button>
</div>
<br>
<br>
<h2>Results <i class="fa-solid fa-square-poll-horizontal"></i></h2>
<!-- List items -->
<?php
#if($data->isNotEmpty())
#foreach ($data as $data)
<ul class="list-group mt-3">
<li class="list-group-item">{{ $data->name }}<</li>
<li class="list-group-item">{{ $data->location }}</li>
<li class="list-group-item">{{ $data->symbol }}</li>
</ul>
#endforeach
#else
<div>
<h2>No Gene found</h2>
</div>
#endif
?>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
</body>
</html>
I keep getting "route 'search' not defined" and "syntax error unexpected token "if"". Thank you for your help!
You can only access the route() method on named routes. In your web.php file, you must give your search route the name search before you can access it via route('search')
In you web.php change:
Route::get('search', [SearchController::class, 'search']);
to this:
Route::get('search', [SearchController::class, 'search'])->name('search');
Please visit the docs to learn more.

Laravel Function called by Route returning '500' error. DB data

public function saveUserToGroup(Request $request, $username){
if (!$this->secure($username)) return redirect('/404');
$member = new UserHobby();
$person = $request->input('person');
$group = $this->group;
$member->user_id = $person->id;
$member->hobby_id = $group->id;
if ($member->save()) {
$request->session()->flash('alert-success', 'Your friend has been added to the group!');
}else{
$request->session()->flash('alert-danger', 'Something went wrong!');
}
return Redirect::back()->withErrors(['msg', 'Success']);
}
<form action="/social/{username}/save/group" method="POST">
#csrf
<table id="modal-table">
#foreach($user_list->get() as $f)
<tr>
<td>
<div class="image">
#if($f->follower->avatar_location)
<img src="{{asset('storage/'.$f->follower->avatar_location)}}" class="img-circle" style="max-height:50px;" />
#else
<img src="{{url('/')}}/assets/media/icons/socialbuttons/user.png" class="img-circle" style="max-height:50px;"/>
#endif
</div>
<div class="detail">
#if($f->follower->verified == 1)
{{ $f->follower->name }}<img id="verified_img_sm_mess_list" src="{{url('/')}}/assets/media/icons/socialbuttons/octagonal_star.png" alt="Recensioni">
#else
<h3>{{ $f->follower->name }}</h3>
#endif
<small id="mess_list_uname">{{ '#'.$f->follower->username }}</small>
</div>
<button type="submit" name="person" value="person" class="btn-link">Go</button>
</td>
</tr>
#endforeach
</table>
</form>
Route::post('/social/{username}/save/group', [GroupController::class, 'saveUserToGroup'])->name('socialprofile.save.user.group');
Hey guys, I'm new to all this, and not sure if I'm calling the route incorrectly or wrong application of my controller function. Obviously I'm trying to add a user from a list into a group. Please Help! I've been a little lost with this and looking for some help to understand where my errors are. Many thanks!
EDIT**
now log reading..
"'hobby_id' cannot be null"..
I have tried to change the variable to take the group id. and that reads error "trying to get id of non-object"
but am I not assigning hobby_id as the group_id?
The problem is that I want to add into 'hobby_id' the 'id' of the current group which this function is being called.

Laravel Searchbar Class 'products' not found / ProductController#?

I am an Laravel beginnner and try now to build an Simple Searchbar on my site.
But I get this error:
Class 'products' not found
Can someone tell me please what I have forget in my Controllers?
Search form on Index:
<ul class="searchbar">
<form action="/search" class="light" method="POST" role="search">
{{ csrf_field() }}
<input type="text" class="form-control" name="q" placeholder="Find your item" />
<input type="submit" value="Search" />
</form>
search.blade.php:
#extends('master.main')
#if(Auth::check())
#section('main-content')
#component('master.notification')
#slot('size')
col-md-8 col-md-offset-2
#endslot
#slot('title')
Product Search
#endslot
<div class="container">
#if(isset($products))
<h2>Product Search</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach($products as $dummy)
<tr>
<td>{{$dummy->name}}</td>
<td>{{$dummy->description}}</td>
</tr>
#endforeach
</tbody>
</table>
{!! $products->render() !!}#endif
</div>
<div class="container">
#if(isset($details))
<p> The Search results for <b> {{ $query }} </b> are :</p>
<h2>Product Search</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Product</th>
<th>Description</th>
</tr>
</thead>
<tbody>
#foreach($details as $products)
<tr>
<td>{{$products->name}}</td>
<td>{{$products->description}}</td>
</tr>
#endforeach
</tbody>
</table>
#if($details){!! $details->render() !!}#endif
#elseif(isset($message))
<p>{{ $message }}</p>
#endif
</div>
#endcomponent
#stop
#endif
web.php:
Route::get ( '/', function () {
$mydatabase = products::paginate(25);
return view ( 'search' )->withproducts($mydatabase);
} );
Route::any ( '/search', function () {
$q = Input::get ( 'q' );
if($q != ""){
$products = products::where ( 'name', 'LIKE', '%' . $q . '%' )->orWhere ( 'description', 'LIKE', '%' . $q . '%' )->paginate (5)->setPath ( '' );
$pagination = $products->appends ( array (
'q' => Input::get ( 'q' )
) );
if (count ( $products ) > 0)
return view ( 'search' )->withDetails ( $products )->withQuery ( $q );
}
return view ( 'search' )->withMessage ( 'No Products found. Try to search again !' );
} );
The error comes from:
Route::get ( '/', function () {
$mydatabase = products::paginate(25);
How is products or Product::paginate defined or must I use in web.php the ProductController#...? Yes, I have found out its not my database table products ;) I think Product instead of products are correct, right?
/App/Product.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Storage;
class Product extends Model
{
public function category(){
return $this->belongsTo('App\Category');
}
public function seller(){
return $this->belongsTo('App\User');
}
public function buyer(){
return $this->belongsTo('App\User');
}
public function bids(){
return $this->hasMany('App\Bid');
}
public function purchases(){
return $this->hasMany('App\Purchase');
}
}
you must add (import your class products) in the begin of your controller (web.php for your case)
use namespace\products
replace namespace by your namespace(the path of the class products) exemple: \app
is better to use a controller ProductController and redefined yours functions
If your products model is Product then you have typo in your code.
Route::get ( '/', function () {
$mydatabase = Products::paginate(25);
return view ( 'search' )->withproducts($mydatabase);
} );
You have a typo in your code change products::paginate to Product::paginate()
Hope this helps
Try replacing products::paginate with \App\products::paginate?
Laravel is namespaced, therefore it cannot find a class just by the correct name.
Laravel 5 promotes the use of namespaces for things like Models and Controllers. Your Model is under the App namespace, so your code needs to call it like this:
Route::get('/', function(){
$myDatabase= \App\Products::paginate(25);
});
Solved! Big Thanks guys for your Help!
I have just must added
use App\Product;
to my web.php file and works great!

Laravel search not print the results

I have search box for my Laravel project it seems working because after request I'll get http://project.dev/search?q=fifth but nothing prints in blade template.
here is my SearchController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use Illuminate\Support\Facades\Input;
use Carbon\Carbon;
class SearchController extends Controller
{
public function index() {
$countTodayOrders = Post::whereRaw('Date(created_at) = CURDATE()')->count();
$yesterday_posts = Post::whereRaw('Date(created_at) = DATE_ADD(CURDATE(), INTERVAL -1 DAY)')->count();
$weekly_posts = Post::whereBetween( 'updated_at', [Carbon::today()->startOfWeek(), Carbon::today()->endOfWeek()] )->count();
$monthy_posts = Post::whereRaw('MONTH(created_at) = ?', Carbon::today()->month)->count();
$q = Input::get('q');
$posts = Post::where('title','LIKE','%'.$q.'%')->orWhere('slug','LIKE','%'.$q.'%')->get();
if(count($posts) > 0)
return view('theme.search', compact('posts', 'countTodayOrders', 'yesterday_posts', 'weekly_posts', 'monthy_posts'))->withQuery ( $q );
else return view ('theme.index')->withMessage('No Details found. Try to search again !');
}
}
Here is my search form
<!-- search box -->
<form action="/search" method="get" role="search">
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search users"> <span class="input-group-btn">
<button type="submit" class="btn btn-default">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
</form>
<!-- search box -->
Here is my routes
Route::any('/search', ['uses' => 'SearchController#index', 'as' => 'search.index']);
Here is my blade
#extends('layout.app')
#section('content')
<div class="col-md-9 technology-left">
<div class="tc-ch wow fadeInDown" data-wow-duration=".8s" data-wow-delay=".2s">
#if(isset($details))
<p> The Search results for your query <b> {{ $query }} </b> are :</p>
<h2>Sample User details</h2>
<table class="table table-striped">
<thead>
<tr>
<th>Post</th>
</tr>
</thead>
<tbody>
#foreach($posts as $post)
<tr>
<td>{{$post->name}}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
</div>
</div>
#endsection
where is my mistake?
Update
Now I have search box which is work and show data with pagination but when i search for example for word sample which i have 3 posts with that title in first page of results I'm getting results like this:
first page
But when i go to second page everything changes!
second page
Why?
Ok guys i got it thanks, the issue was withQuery method as i used compact i shouldn't use with i just added it to `compact and now it's working. but what about counting the results? how can i pass the number of founded result in blade?

Image not Displayed as Expected in Laravel 5.2

I have a form where users enter their details along with their image. I've written code that gets the image and stores it in a column named 'image' as bin file, the data type of the column is a blob. However, when I try to display the image in the view, The image is not getting displayed.
Controller
<?php
public function showProfile($username)
{
$user_details = User::get()->where('name', $username);
return view('profile-page', ['user_details' => $user_details]);
}
View
<div class="panel-body">
<form class="form-horizontal" role="form" method="POST" action="{{ url('/user-post') }}">
{{ csrf_field() }}
<input type='hidden' value='{{Session::token()}}' name="_token">
#foreach($user_details as $user)
<img src="data:image/jpeg;base64,'.base64_encode( {{$user->image}} ).'"/>
<p>
<h2>
<center>hello This is {{$user->name}} </center>
</h2>
<h2>
<center>I am a {{$user->nationality}} </center>
</h2>
<h2>
<center>This great person was born on {{$user->dobday}}-{{$user->dobmonth}}-{{$user->dobyear}} </center>
</h2>
<h2>
<center>Contact me here {{$user->email}} </center>
</h2>
#endforeach
</form>
</div>
All the details are shown as expected except the image, what's the problem here?
You made mistake here:
base64_encode( {{$user->image}}
try like this:
{{ base64_encode($user->image) }}

Categories