Laravel (php) save search options - php

So i am using laravel 5.2 and i am building a search form, there is multiple search queries and options.
I have been wracking my head trying to think of ways to save the users search and auto fill the form when they visit the search page OR even auto search when they visit it.
So far I have been setting the GET's as variables and auto fill in the text fields but that only lasts for the time they are on the page which is not what i am after,
I have thought about saving the gets into the database as separate fields and when they search and pulling them when they are on the page and filling in each field but then how do I auto search?
Or do I save it as 1 string as the get from the URL eg, u=username&p=postcode
and set the route up to check if the user has a search saved and if they visit /search they get redirected to the url+ get options saved in the db. (no clue how to do this either.)
Now the hardest part even with the gets I have fields that are multiple select like genders and sort by. How do you auto fill in those?
Below is my code for just the form
<?php
if(isset($_GET['u'])) { $username = $_GET['u']; } else { $username = ''; }
if(isset($_GET['p'])) { $postcode = $_GET['p']; } else { $postcode = ''; }
if(isset($_GET['o'])) { $orderby = $_GET['o']; } else { $orderby = ''; }
?>
{{ Form::open(['method' => 'GET']) }}
<div id="filter-panel" class="filter-panel collapse in">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-inline" role="form">
<div class="row">
<div class="col-xs-6 col-sm-2">
{{ Form::input('search', 'u', $username, ['class' => 'form-control input-sm', 'placeholder' => 'username...']) }}
</div><!-- form group [search] -->
<div class="col-xs-6 col-sm-2">
{{ Form::input('search', 'p', $postcode, ['class' => 'form-control input-sm', 'placeholder' => 'postcode...']) }}
</div><!-- form group [search] -->
<div class="col-xs-6 col-sm-3">
<select id="attractedToGender" multiple="multiple" name="g[]" class="input-sm" >
<option value="1">Females</option>
<option value="2">Males</option>
<option value="3">Others</option>
</select>
</div><!--END form-group col-xs-6 col-sm-4-->
<div class="col-xs-12 col-sm-3">
<select id="pref-orderby" class="input-sm" name="o[]" multiple="multiple">
<option value="1">Photo Only</option>
<option value="2">User Type</option>
<option value="3">Last Online</option>
</select>
</div> <!-- form group [order by] -->
<div class="col-xs-6 col-sm-2 pull-right text-right">
{{Form::button('<i class="glyphicon glyphicon-search"></i> Search', array('type' => 'submit', 'class' => 'btn btn-primary btn-sm', 'style' => 'margin:0;'))}}
</div><!--END form-group col-xs-6-->
</div>
</form>
</div>
</div>
</div>
{{ Form::close() }}

There are few ways to do that. The best ways are dedicated model and saving data as JSON object.
Model. You can create dedicated table with User has many Searches relationship. And just save object into this table.
JSON. You can serialize object with ->toJson() method and persist in in a users table. Just add json type column:
$table->json('options');
In both cases you're working directly with the object.

Related

Missing route parameter for Route URI using Laravel?

I'm trying to create a Laravel Notification. I created a table called send_profiles. When a Candidate is logged in and searching through jobs, he can send his job profile to the employer. All of that data is in a table called job_seeker_profiles. I'm developing a Job Search type of application.
I created a new Notification class called SendProfile.php:
public function toDatabase($notifiable)
{
$user = Auth::user();
return [
'user_id' => Auth::user()->id,
'employer_profile_id' => DB::table('send_profiles')->where('user_id', $user->id)->orderBy('id', 'desc')->offset(0)->limit(1)->get('employer_profile_id'),
];
}
I don't know the best way to go about this but anyway this is my route.
web.php:
Route::get('/admin/job-seeker/search/employer/{employerId}/post-a-job/{jobPostId}/send-profile', 'AdminEmployerJobPostsController#sendProfile')->name('admin.employer.post-a-job.show.send-profile')->middleware('verified');
AdminEmployerJobPostsController.php:
public function sendProfile($employerId, $jobPostId)
{
$user = Auth::user();
$jobSeekerProfile = JobSeekerProfile::all()->where('user_id', $user->id)->first();
$employerProfile = EmployerProfile::limit(1)->where('id', $employerId)->get();
$jobPosts = JobPosts::all();
$jobPost = JobPosts::findOrFail($jobPostId);
$user->sendProfile()->create();
$employerProfile->notify(new SendProfile());
return back()->with('send-profile', 'Your Profile has been sent!');
}
This is my error:
Missing required parameters for [Route: admin.employer.post-a-job.show.send-profile] [URI: admin/job-seeker/search/employer/{employerId}/post-a-job/{jobPostId}/send-profile]. (View: /Applications/XAMPP/xamppfiles/htdocs/highrjobs/resources/views/admin/employer/post-a-job/show.blade.php)
show.blade:
#extends('layouts.admin')
#section('pageTitle', 'Create a User')
#section('content')
#include('includes.job_seeker_search_employers')
<!-- The Modal -->
<div class="modal" id="myModal5">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">{{ $jobPost->job_title }}</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<h5>{{ $jobPost->job_description }}</h5>
</div>
<!-- Modal footer -->
<div class="modal-footer">
{!! Form::open(['method'=>'POST', 'action'=>'AdminEmployerJobPostsController#sendProfile', 'files'=>true, 'style'=>'width: 100%;']) !!}
<div class="form-group">
{!! Form::hidden('user_id', Auth::user()->id, ['class'=>'form-control']) !!}
</div>
<div class="form-group">
{!! Form::hidden('employer_profile_user_id', $employerProfile->id, ['class'=>'form-control']) !!}
</div>
<div class="row">
<div class="col">
{!! Form::button('Back', ['class'=>'btn btn-danger btn-block float-left', 'data-dismiss'=>'modal']) !!}
</div>
<div class="col">
{!! Form::submit('Send Profile', ['class'=>'btn btn-primary btn-block float-right']) !!}
{!! Form::close() !!}
</div>
</div>
<br><br><br><br>
</div>
</div>
</div>
</div>
#stop
If I remove the form, I at least don't get an error. So I actually think there is an issue with the form.
To be clear, all I want is to insert the user_id and the employer_profile_id into the send_profiles table and then send a notification to the employer.
Your route specifies a GET request to a URL that contains certain parameters:
/admin/job-seeker/search/employer/{employerId}/post-a-job/{jobPostId}/send-profile
Your form is using AdminEmployerJobPostsController#sendProfile as an action; this is translated into a URL by searching the route list, and choosing what Laravel thinks is most appropriate. Since you haven't passed anything to fill the employerId and jobPostId parameters, you're getting this error when the URL is generated.
Even if you could get the URL generated, you'd have a problem because your form is sending a POST request to this GET route.
What you need to do is ensure you have a POST route pointing to a new controller method. You won't pass any parameters to this route in the URL, so your controller method will only typically accept a Request object as a parameter. Second thing you should do is specify your form's target more accurately. Pass in the route name instead of making it guess.
public function sendProfile(Request $request)
{
// you get this here so no need to pass it in the form
$user = Auth::user();
// your relations should be set up so you don't need to do this:
// $jobSeekerProfile = JobSeekerProfile::all()->where('user_id', $user->id)->first();
// instead do this:
$jobSeekerProfile = $user->jobSeekerProfile();
// a simple find is much neater than what you had
$employerProfile = EmployerProfile::find($request->job_seeker_profile_user_id);
// not sure why this is here?
$jobPosts = JobPosts::all();
// also your form isn't passing a job post ID
$jobPost = JobPosts::findOrFail($request->jobPostId);
// ??? creating an empty something?
$user->sendProfile()->create();
$employerProfile->notify(new SendProfile());
return back()->with('send-profile', 'Your Profile has been sent!');
}

Display only if query is found via search in Laravel using php

I have referral code search box that query referral codes. this code must be available before user can register. So basically on Auth.register I have two boxes, firs t box holds the referral code search box and the other one is the registration box. My goal is to hide first the registration box and appear only if the code has found.
RegisterController
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
if (count ( $referral ) > 0)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided is not existing.' );
}
register.blade.php
<!-- THIS IS THE FIRST BOX THAT HOLDS THE CODE SEARCH BOX -->
<div class="card mx-4">
<div class="card-body p-4">
<h1>Referral Code</h1>
<p class="text-muted">Please provide the referral code given to you by your collector</p>
#if(isset($message))
<div class="alert alert-success">
{{ $message }}
</div>
#endif
{!! Form::open(['method' => 'GET', 'url' => '/register', 'class' => 'form-inline my-2 my-lg-0', 'role' => 'search']) !!}
<div style="width: 100%;">
<input type="text" class="form-control" name="search" style="width: 100%;" placeholder="Enter your referral code here!">
</div>
<div style="width: 150px; margin: auto; margin-top: 20px; ">
<button class="btn btn-success btn-default" type="submit">
<i class="fa fa-search"></i> Check Availability
</button>
</div>
{!! Form::close() !!}
</div>
</div>
<!-- THIS IS THE 2ND BOX THAT HOLDS THE REGISTRATION FORM -->
#if(isset($details))
<div class="card mx-4">
<div class="card-body p-4">
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
... the rest of registration form ...
</div>
</div>
#endif
My problem now is, the #details is displaying the current rows of "Referrals"
Is there a way that query from this line,
$referral = Referral::where('code', 'LIKE', '%'.$keyword.'%')->get();
should only display if the result is match from $keyword?
because currently the page is look like this
Thanks!
I think you want something like to match the keyword against your database. So instead of partial matching use exact matching.
public function index(Request $request)
{
$keyword = $request->get('search');
$referral = Referral::where([
['code', $keyword],
['status', 0]
])->first();
if ($referral)
return view ( 'Auth.register')->withDetails ( $referral )->withQuery ( $keyword );
else
return view ( 'Auth.register')->withMessage ( 'The code you provided does not exist or already used.' );
}
And in view you need not to use the following lines.
#foreach($details as $code)
#if($code->status==0)
<h2>Code is available</h2>
#else
<h2>Code is already taken</h2>
#endif
#endforeach
Just add your registration form after #if(isset($details)).
Its weird how you are doing this. You can use AJAX to do it in a single page

Laravel how to echo selected a value in a dropdown using blade when updating a specific resource

I want to echo the selected value when I edit a specific resource in my table. When I edit the specific resource it should display the current data in my dropdown but in the real scenario it displays the first one on the list which is wrong. So how can I echo the selected value in the options of the dropdown using blade in laravel?
Here is some sample of my code in the view below
<!-- Shows Field -->
<div class="form-group col-sm-6">
{!! Form::label('show_id', 'Shows:') !!}
{!! Form::select('show_id', $shows, $shows, ['class' => 'form-control input-md','required'])!!}
</div>
{{-- {{ $channelshows->channel->name }} --}}
<!-- Client Id Field -->
<div class="form-group col-sm-6">
{!! Form::label('channel_id', 'Channels:') !!}
{!! Form::select('channel_id', $channel, $channel, ['class' => 'form-control input-md','required'])!!}
</div>
<!-- Submit Field -->
<div class="form-group col-sm-12">
{!! Form::submit('Save', ['class' => 'btn btn-primary']) !!}
Cancel
</div>
and here is the code in my controller below.
public function edit($id)
{
$channelshows = $this->channelshowsRepository->findWithoutFail($id);
$shows = Show::pluck('name', 'id');
$channel = Channel::pluck('name', 'id');
if (empty($channelshows)) {
Flash::error('Assigned show not found');
return redirect(route('admin.channelshows.index'));
}
return view('admin-dashboard.channelshows.edit', compact('shows', $shows), compact('channel', $channel))->with('channelshows', $channelshows);
}
Everything here works fine even if I updated the specific resource. I just want to auto populate or select the current value of the resource that I will update because when I edit the specific resource it shows the first one on the list.
Am I going to use an #if statement in blade? But how can I do it using the blade template in my select form. Can somebody help me?
Appreciate if someone can help.
Thanks in advance.
Here is an example:
Open form:
{{ Form::model($service, array('route' => array('services.update', $service->id))) }}
Select form field:
<div class="form-group">
{{ Form::label('Related Agreement') }}
{{ Form::select('agreement', $agreementsList, null, array('class'=>'form-control', 'placeholder'=>'Please select ...')) }}
</div>
In Controller:
$agreementsList = Agreement::all()->sortBy('name', SORT_NATURAL | SORT_FLAG_CASE)->pluck('name', 'id');
(Include this when passing data to your view)

Display none not working Laravel

I have a condition, if active is checked then it'll display a text form.
This is my view form code:
<div class="form-group">
<label>Active:</label>
{{ Form::checkbox('active', 0,null, array('id' =>'active_check','class' => 'active_check')) }}
</div>
<div id ="join_date" class="form-group" style="display: none;">
<label>Join Date:</label>
<div class="input-group">
{!! Form::text('join_date', null, array('class' => 'form-control datetimepicker' )) !!}
</div>
</div>
Here is my jQuery toggle and check condition code so far:
$('#active_check').click(function() {
$("#join_date").toggle(this.checked);
$('#join_date').find('input[type="text"], textarea').val('');
});
var activeCheck = $('checkbox[name="active_check"]');
function checkActive(select) {
if (select.val() == 0) {
$('#join_date').hide();
} else {
$('#join_date').show();
}
}
checkActive(activeCheck);
The issue is when it is first loaded the join_date form doesn't hide. I need to toggle the checkbox to hide it. Any idea?
Try this simple logic:
if($('#active_check').is(':not(":checked")')) {//test if active_check is not checked
$('#join_date').hide();//hide it
}
$('#active_check').click(function() {
$("#join_date").toggle();//toggle it
});

Using a datepicker with Phalcon Volt template engine

I am pretty new to the Phalcon PHP framework and the Volt template engine.
So far I really like it though.
One thing that I can't figure out however, is how to implement a date picker to a date field.
I have a date field defined as below, but rather than having to manually input a date I would like the user to select a date from a date picker.
<?php echo Tag::dateField(array("finishdate", "size" => 8, "maxlength" => 8, "type" => "date")) ?>
I thought that maybe it would automatically get a date picker if it was defined as a date field, or maybe there was an option somewhere, but I have looked all over internet and I can't find anything.
I would be very grateful if someone knew how to solve this?
I am also trying to figure out the Volt textArea and I have problems finding any information regarding this as well. I can't seem to get the text area to show as a text box. There just seems to be very little information from users regarding Phalcon Volt. Is no one using this?
I did it! I used datepicker (https://jqueryui.com/datepicker/). I share with you the code.
Form:
$fecha = new Text('fecha_final');
$fecha->setLabel('Fecha Final');
$fecha->addValidators(array(
new PresenceOf(array(
'message' => 'Por favor pon una fecha límite'
))
));
$this->add($fecha);
Controller:
public function nuevakeywordAction(){
$auth = $this->session->get('auth');
$permiso = $auth['active'];
if($permiso!='A'){return $this->forward('servicios/index');}
$form = new NuevakeywordForm;
if ($this->request->isPost()) {
$trackeable = $this->request->getPost('trackeable', array('string', 'striptags'));
$idcliente = $this->request->getPost('idcliente');
$fecha = $this->request->getPost('fecha');
$keyword = new Keyword();
$keyword->trackeable = $trackeable;
$keyword->cliente_idcliente = $idcliente;
$keyword->fecha_inicial = new Phalcon\Db\RawValue('now()');
$keyword->fecha_final = $fecha;
if ($keyword->save() == false) {
foreach ($keyword->getMessages() as $message) {
$this->flash->error((string) $message);
}
} else {
$this->tag->setDefault('trackeable', '');
$this->tag->setDefault('idcliente', '');
$this->tag->setDefault('fecha', '');
$this->flash->success('Keyword agregada correctamente');
return $this->forward('admin/verkeywords');
}
}
$this->view->form = $form;
}
View:
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<section class="container animated fadeInUp">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div id="login-wrapper">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">
Registrar Nueva Keyword
</h3>
</div>
<div class="panel-body">
{{ form('admin/nuevakeyword/', 'id': 'nuevakeywordForm', 'onbeforesubmit': 'return false') }}
<fieldset>
<div class="control-group">
{{ form.label('trackeable', ['class': 'control-label']) }}
<div class="controls">
{{ form.render('trackeable', ['class': 'form-control']) }}
</div>
</div>
<div class="control-group">
{{ form.label('idcliente', ['class': 'control-label']) }}
<div class="controls">
{{ form.render('idcliente', ['class': 'form-control']) }}
</div>
</div>
<div class="control-group">
{{ form.label('fecha_final', ['class': 'control-label']) }}
<div id="datepicker" class="controls">
{{ form.render('fecha_final', ['class': 'form-control']) }}
</div>
</div>
<div class="form-actions">
{{ submit_button('Insertar', 'class': 'btn btn-primary', 'onclick': 'return SignUp.validate();') }}
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</section>
<script type="text/javascript">
$(function() {
$("#fecha_final").datepicker();
});
</script>
I hope it will help you.
The date field merely uses HTML5's date field. If you want a date picker, you must use a Javascript date picker library.
As for text areas and text fields, you should use the function text_field() to create a text field, and text_area() to create a text area. The list of functions you can use are in the Volt – Using tag helpers documentation page.

Categories