PHP/Laravel search query controller - php

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.

Related

Undefined variable in Laravel trying to post source ID route

Currently Working on building out a news api behind a dashboard. I have just recently started getting the error Undefined variable: sourceId (View: C:\Laravel8Auth\resources\views\dashboard.blade.php).
Ive gone everywhere that has source Id and I cant see to figure out what it could be.
Here are some of the codes necessary, im using Laravel 8.x with JetStream Im fairly new at this just wanted to mess around.
web php
`<?php
use Illuminate\Support\Facades\Route;
use App\Models\Api;
use App\Http\Controllers\ApiController;
///Route::get('/', [ApiController::class,'displayNews']);
///Route::get('/fetchNewsFromSource', [ApiController::class, 'fetchNewsFromSource'])->name('fetchNewsFromSource');
///Route::post('/sourceId', 'ApiController#displayNews');
Route::get('/', 'App\Http\Controllers\ApiController#displayNews');
Route::post('sourceId', 'App\Http\Controllers\ApiController#displayNews');
Route::middleware(['auth:sanctum', 'verified'])->get('/dashboard', function () {
return view('dashboard');
})->name('dashboard');
`
Dashboard php
<!DOCTYPE html>
<html lang="{{ config('app.locale') }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>News Application with Laravel</title>
<!-- Fonts -->
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700" rel="stylesheet" type="text/css">
<!-- Styles -->
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<div id="appendDivNews">
<nav class="navbar fixed-top navbar-light bg-faded" style="background-color: #e3f2fd;">
<a class="navbar-brand" href="#">News Around the World</a>
</nav>
{{ csrf_field() }}
<section id="content" class="section-dropdown">
<p class="select-header"> Select a news source: </p>
<label class="select">
<select name="news_sources" id="news_sources">
<option value="{{$sourceId}} : {{$sourceName}}">{{$sourceName}}</option>
#foreach ($newsSources as $newsSource)
<option value="{{$newsSource['id']}} : {{$newsSource['name'] }}">{{$newsSource['name']}}</option>
#endforeach
</select>
</label>
<object id="spinner" data="spinner.svg" type="image/svg+xml" hidden></object>
</section>
<div id="news">
<p> News Source : {{$sourceName}} </p>
<section class="news">
#foreach($news as $selectedNews)
<article>
<img src="{{$selectedNews['urlToImage']}}" alt=""/>
<div class="text">
<h1>{{$selectedNews['title']}}</h1>
<p style="font-size: 14px">{{$selectedNews['description']}} <a href="{{$selectedNews['url']}}"
target="_blank">
<small>read more...</small>
</a></p>
<div style="padding-top: 5px;font-size: 12px">
Author: {{$selectedNews['author'] ? : "Unknown" }}</div>
#if($selectedNews['publishedAt'] !== null)
<div style="padding-top: 5px;">Date
Published: {{ Carbon\Carbon::parse($selectedNews['publishedAt'])->format('l jS \\of F Y ') }}</div>
#else
<div style="padding-top: 5px;">Date Published: Unknown</div>
#endif
</div>
</article>
#endforeach
</section>
</div>
</div>
</body>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- Scripts -->
<script src="{{ asset('js/site.js') }}"></script>
</html>
apicontroller.php supposed to grab from this to get the news api
<?php
namespace App\Http\Controllers;
use App\Models\Api;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
class ApiController extends Controller
{
/**
* #param Request $request
* #return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
*/
public function displayNews(Request $request)
{
$response = $this->determineMethodHandler($request);
$apiModel = new Api();
$response['news'] = $apiModel->fetchNewsFromSource($response['sourceId']);
$response['newsSources'] = $this->fetchAllNewsSources();
return view('dashboard', $response);
}
/**
* #param $request
* #return mixed
*/
protected function determineMethodHandler($request)
{
if ($request->isMethod('get')) {
$response['sourceName'] = config('app.default_news_source');
$response['sourceId'] = config('app.default_news_source_id');
} else {
$request->validate([
'source' => 'required|string',
]);
$split_input = explode(':', $request->source);
$response['sourceId'] = trim($split_input[0]);
$response['sourceName'] = trim($split_input[1]);
}
return $response;
}
/**
* #return mixed
*/
public function fetchAllNewsSources()
{
$response = Cache::remember('allNewsSources', 22 * 60, function () {
$api = new Api;
return $api->getAllSources();
});
return $response;
}
}
You should pass an array with variables to views
view('dashboard', ["sourceId" => 1, /* and so on */]);
I can't understand what are you doing there.

how to create a function to fetch variables, retrieve them, and access them on the preview page

how to create a function to fetch variables, retrieve them, and access them on the preview page, getting data from a user by the related id in another table?
I need to create a function that looks for the parameter passed by url in the database, more specifically in the table "company", column "name"
the user types company / name in the address bar and laravel should search for this name and find it (if any), with that name in hand, I need it sent to the view page, where it will load bootstrap classes from the personalite table, that is related to the user through the id, I've tried everything, but I don't have much experience
I found this code that does not have much to do with my question, but it was the closest I came, but I didn't copreendi very well, in the end, it didn't work out and I need to finish my project :(
public function retorna_disciplina($id)
{
$prontuario = session('prontuario');
$cargo = session('cargo');
if($cargo == "P")
{
$disciplina = DB::table('oferecimento_disciplina')
->where('id_professor','=', $prontuario)
->where('dsa', '=', $id)
->first();
if(count($disciplina)>0)
{
$postagens = DB::table('postagens')
->where('dsa', '=', $id)
->get();
return view('disciplinas.disciplina')->with([
'disciplina' => $disciplina,
'postagens' => $postagens
]);
}
else{
Redirect::to('/perfil')->withErros("A disciplina não existe ou você não tem permissão de acesso");
}
}
}
I created a route and it seems to work well
Route::get('/company/{name}', "company/index_controller#search_base_home(name)");
I created a model, a controller and 2 views, 1 if the laravel finds the name and another if not (a search page)
my problem is really creating the function, I'm not getting
tell me what i need to do to put this into practice i would be very grateful for the help
There may be something wrong with the code, disagreements or something, sorry if that is the case, just an example for you to understand my question better
Right now I'm trying hard with this here, but nothing, I don't know, doesn't seem to get the url name
$this->validate($request, [
'name' => 'required|unique:company|name',
]);
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
the view code is this (companybase_lg.blade.php)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>iofrm</title>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://brandio.io/envato/iofrm/html/css/fontawesome-all.min.css">
<link rel="stylesheet" type="text/css" href="https://brandio.io/envato/iofrm/html/css/iofrm-style.css">
<link rel="stylesheet" type="text/css" href="https://brandio.io/envato/iofrm/html/css/iofrm-theme1.css">
</head>
<body>
<div class="form-body">
<div class="website-logo">
<a href="index.html">
<div class="logo">
<img class="logo-size" src="images/logo-light.svg" alt=""><!--- db class here --->
</div>
</a>
</div>
<div class="row">
<div class="img-holder"><!--- db class here --->
<div class="bg"></div>
<div class="info-holder">
</div>
</div>
<div class="form-holder"><!--- db class here --->
<div class="form-content">
<div class="form-items">
<h3>Get more things done with Loggin platform.</h3>
<p>Access to the most powerfull tool in the entire design and web industry.</p>
<div class="page-links">
LoginRegister
</div>
<form>
<input class="form-control" type="text" name="username" placeholder="E-mail Address" required><!--- db class here ---><!--- db class here --->
<input class="form-control" type="password" name="password" placeholder="Password" required><!--- db class here --->
<div class="form-button">
<button id="submit" type="submit" class="ibtn">Login</button> <!--- db class here --->
Forget password?
</div>
</form>
<div class="other-links">
<span>Or login with</span>FacebookGoogleLinkedin
</div>
</div>
</div>
</div>
</div>
</div>
<script src="https://brandio.io/envato/iofrm/html/js/jquery.min.js"></script>
<script src="https://brandio.io/envato/iofrm/html/https://brandio.io/envato/iofrm/html/js/popper.min.js"></script>
<script src="https://brandio.io/envato/iofrm/html/js/bootstrap.min.js"></script>
<script src="https://brandio.io/envato/iofrm/html/js/main.js"></script>
</body>
</html>
FINAL PART
I tried to get the data to fill in with the classes, but returns nothing related to the name, I don't know if I made a mistake somewhere ...
#foreach($companies as $company)
<div class="{{ $companies->personalite->div_class_1 }}"></div>
<div class="{{ $companies->personalite->div_class_2 }}"></div>
<div class="{{ $companies->personalite->div_class_3 }}"></div>
<div class="{{ $companies->personalite->div_class_4 }}"></div>
#endforeach
so I need to take div_class_1 which is in the personalite table and put in div
each user has their classes in this table and is related to it by an ID number, I created a column "name" in the table to do the test but so far nothing
I don't understand the whole question. But I can answer this part of your question.
Question : I need to create a function that looks for the parameter passed by url in the database, more specifically in the table "company", column "name"
Route
Route::get('companies/{name}', 'CompaniesController#searchByName');
Controller
public class CompaniesController extends Controller
{
public function searchByName($name)
{
$company = Company::where('name', $name)->first();
return view('your_blade_view', compact('company'));
}
}

How can I give HyperLink in my full calender?

I am displaying my events in calender. It will display it properly. But I want that when I click on that event it will redirect on particular event_detail page.
I am beginner in laravel so woll you please help me???
This Is my controller file
<?php
namespace App\Http\Controllers\Admin;
use Carbon;
use Calendar;
use App\Event;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class CalendarController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/*
*Display All The Events In Calendar
*
*/
public function calendar()
{
$event = [];
$allEvent = Event::all();
if($allEvent->count())
{
foreach ($allEvent as $key => $eventList)
{
$event[] = Calendar::event(
$eventList->name,
true,
new \DateTime($eventList->event_date),
new \DateTime($eventList->evet_date)
);
}
}
$showInCalendar = Calendar::addEvents($event);
return view('admin.calendar.event_calendar', compact('showInCalendar', 'allEvent'));
}
}
This is muy blade file
#extends('admin.layout.default')
#section('css')
<link href="{{ url('assets/plugins/calendar/dist/fullcalendar.css') }}" rel="stylesheet" />
#endsection
#section('content')
<div class="row page-titles">
<div class="col-md-5 col-8 align-self-center">
<h3 class="text-themecolor">Calendar</h3>
<ol class="breadcrumb">
<li class="breadcrumb-item">Dashboard</li>
<li class="breadcrumb-item active">Calendar</li>
</ol>
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="card card-outline-info">
<div class="card-body">
<div class="container">
<div class="row justify-content-center">
<div id="calendar">
{!! $showInCalendar->calendar() !!}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('jsPostApp')
{!! $showInCalendar->script() !!}
<script src="{{ url('assets/plugins/calendar/jquery-ui.min.js') }}"></script>
<script src="{{ url('assets/plugins/moment/moment.js') }}"></script>
<script src="{{ url('assets/plugins/calendar/dist/fullcalendar.min.js') }}"></script>
<script type="text/javascript">
</script>
#endsection
I dont know how to handle that hyperlink to open that particular event's detils page.
It's very easy to achieve that behavior.
You will need to set the property url in your event objects. Once you have it, you can use the callback eventClick to redirect the user. By default, eventClick will always redirect to link inside url.
If you want to display it in a different tab, or a popup, take a look at the section Cancelling Default Behavior in the eventClick link I posted here.
Owk I got the solution
public function calendar()
{
$event = [];
$allEvent = Event::all();
if($allEvent->count())
{
foreach ($allEvent as $key => $eventList)
{
$event[] = Calendar::event(
$eventList->name,
true,
new \DateTime($eventList->event_date),
new \DateTime($eventList->event_date),
null,
[
'url' => 'event/' .$eventList->id,
]
);
}
}

Correct view output Laravel

That's my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Spieler;
class SpielerController extends Controller
{
public function getSpieler(Request $request){
$spielID = $request->get('spielID');
$spielerOutput = Spieler::where('spielPlanID', '=', $spielID)->get();
return view('spieler')->with('alleSpieler', $spielerOutput);
}
}
here you can see my view which I will trigger
#extends('app')
#section('contentSpieler')
<h1>Spieler</h1>
#if(count($alleSpieler) > 0)
#foreach($alleSpieler as $teamSpieler)
{{ $teamSpieler->note }}
#endforeach
#endif
#endsection
And here is my main index/app page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dateneingabe</title>
<link rel="stylesheet" href="/css/app.css">
<script src="{{ asset('/js/jquery-3.2.1.min.js') }}"></script>
</head>
<body>
<div class="container">
<h1>Spiele und Spieler AJAX - Drop Down</h1>
<div class="col-lg-4">
#yield('contentSpiel')
</div>
<div class="col-lg-4">
#yield('contentSpieler')
</div>
</div>
</body>
</html>
When my controller is going to trigger i get back this in my console
<script src="http://localhost:8000/js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<h1>Spiele und Spieler AJAX - Drop Down</h1>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<h1>Spieler</h1> 2.5 Blasdasd
</div>
</div>
</body>
</html>
But I want only that {{ $teamSpieler->note }} should appear in my index/app page in the part #yield('contentSpieler'). What is wrong with my code? The correct value of note 2.5 is in the html console output but at the moment I don't know why there is no output on my index/app page?
if your master view file location is view->index->app.blade.php then
your view file should be like this
#extends('index.app')
#section('contentSpieler')
<h1>Spieler</h1>
#if(count($alleSpieler) > 0)
#foreach($alleSpieler as $teamSpieler)
{{$teamSpieler->note}}
#endforeach
#endif
#endsection
here your master view file location should be correct to extend it in your view file

Laravel yield and extends not working

This is master.blade.php placed in views folder
<html ng-app="planner">
<head>
<title>MeetUp Planner</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/master.css" type="text/css">
</head>
<body ng-controller="MainController">
<div class="container" ng-controller="MainController">
<div class="row row-centered planner-block">
<div class="col-md-12">
<div class="col-md-5 col-centered col-min form-area">
<div class="row row-centered">
#yield('signup')
</div>
</div>
</div>
</div>
</div>
<script src="js/master.js"></script>
</body>
</html>
This is forms/signup.blade.php place in views folder
#extends('master')
#section('signup')
<div class="col-md-11 col-centered form-area-inner">
<span class="form-text">Sign Up</span>
<hr class="seperator"/>
</div>
#stop
This is routes file
<?php
Route::get('/', function () {
return view('master');
});
The yield 'signup' is not wokring, the divs and text are not being show in the master file. What could be the problem?
Directory Structure
resources:
---views->errors
---views->forms->signup.blade.php
---views->vendor
---views->master.blade.php
Using laravel 5.2
That's not how it works. master view will be extended when you'll use forms.signup view:
Route::get('/', function () {
return view('forms.signup');
});
If you want to include some view into master view, you should use #include() clause.
your route file will be
<?php
Route::get('/', function () {
return view('forms.signup');
});
?>
change the location of master.blade.php
move it to ---resources/views/layouts/master.blade.php
in your master.blade.php file change this line
#yield('signup') to #yield('content')
reference link : link

Categories