search by multiple values using checkbox in laravel - laravel

I have job_sector table in which sector_id and job_id fields are there. I just want to search job_id by the sectors which I have selected through checkbox. One may select multiple sectors.
My model :
public function scopeSelectedOptions($query, $input = [])
{
if(!empty($input)) {
if(array_key_exists('sector_id', $input)) {
$query->whereHas('sector_id', function($q) use ($input) {
return $q->whereIn('sector_id', $input['sector_id']);
});
}
}
return $query;
}
Controller :
public function jobsFilter(Request $request)
{
$jobs = JobSector::SelectedOptions(request()->all())->get();
return view('front.pages.job.jobfilter')->with(['title'=>'Job Filter', 'jobs' => $jobs]);
}
Form from where I am selecting multiple sectors :
<form action="{{ route('job.jobfilter') }}" method="GET" class="mb-4">
{{csrf_field()}}
#foreach(get_sectors() as $k=>$s)
<input type="checkbox" name="input[]" value="{{ $k }}">{{ $k }}<br>
#endforeach
<input type="submit" value="Search" />
</form>
Query showing the output :
#foreach($jobs as $c)
{{ $c->job_id }} <br>
#endforeach
It shows me all the job_id in the table.
Please help me out,

You are giving the wrong array to your scope
it would look like this :
['input' => ['12' => true]]
try this
<form action="{{ route('job.jobfilter') }}" method="GET" class="mb-4">
{{csrf_field()}}
#foreach(get_sectors() as $k=>$s)
<input type="checkbox" name="sector_id[{{ $k }}]">{{ $k }}<br>
#endforeach
<input type="submit" value="Search" />
</form>
public function jobsFilter(Request $request)
{
$jobs = JobSector::whereIn('sector_id', array_keys(request()->sector_id))->get();
return view('front.pages.job.jobfilter')->with(['title'=>'Job Filter', 'jobs' => $jobs]);
}
(I just ignore your scope to be more readable)

Related

Laravel Must be string when saving

I have a mounted variable and an error occurs when i'm about to save the variable.
public $code;
public function mount()
{
$this->code = substr(str_shuffle(str_repeat("ABCDEFGHIJKLMNOPQRSTUVWXYZ", 5)), 0, 3).Carbon::now()->format('md').rand(100, 999);
}
protected function rules(): array
{
return [
'applicant.code' => [
'string',
'required',
],
];
}
blade
<div class="form-group {{ $errors->has('applicant.code') ? 'invalid' : '' }}">
<label class="form-label" for="code" hidden>{{ trans('cruds.applicant.fields.code') }}</label>
<input class="form-control" type="text" name="code" id="code" value="{{ $code }}" disabled hidden>
<div class="validation-message">
{{ $errors->first('applicant.code') }}
</div>
<div class="help-block">
{{ trans('cruds.applicant.fields.code_helper') }}
</div>
</div>
<div class="form-group">
<button class="btn btn-indigo mr-2" type="submit">
{{ trans('global.submit') }}
</button>
<a href="{{ route('admin.applicants.index') }}" class="btn btn-secondary">
{{ trans('global.cancel') }}
</a>
</div>
The code must be a string.
I can't seem to figure out this error. Can anyone help?
<input class="form-control" type="text" name="code" id="code" value="{{ $code }}" disabled hidden>
Your input code is disabled
function mount() {
$characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
$date = date("md");
$numbers = rand(100, 999);
$randomString = substr(str_shuffle(str_repeat($characters, 5)), 0, 3). $date . $numbers;
return $randomString;
}
echo mount();
Your rule defines applicant.code, therefore the validation is expecting a variable named applicant with a key named code:
public array $applicant = [
'code' => null,
];
public function mount()
{
$this->applicant['code'] = ''; // Implement your code
}
Also, you have an input showing the code in your blade view. Is this meant to be editable? If so, you should be using wire:name instead of name (See docs).
However, since you have it disabled, I don't assume you want to allow the user to edit it, so why have it validated in the first place?

production.ERROR: Undefined variable: id Laravel blade

In my Laravel-5.8 I have this code in the controller:
public function appraisal(Request $request)
{
try {
$userCompany = Auth::user()->company_id;
$userId = Auth::user()->id;
$company = OrgCompany::where('id', $userCompany)->first();
$identities = Identity::where('company_id', $userCompany)->pluck('appraisal_name','id');
$goals = AppraisalGoal::where('employee_id', $userId)
->where(function ($query) {
$query->where('is_approved', 3)->orWhere('is_visible', 0);
})
->whereNull('deleted_at')
->orderBy('goal_type_id');
$method = $request->method();
if ($request->isMethod('post')) {
$id = $request->input('identity_id');
if ($request->has('search')) {
// select search
if ($request->input('identity_id')) {
$goals->where('identity_id',$request->input('identity_id'));
}
$goals = $goals->get();
return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
} elseif ($request->has('viewIdentity')) {
// select goal identity
if ($request->input('identity_id')) {
return view('performance_dashboard', $id);
}
}
} else {
//select current year
$goals = $goals->get();
return view('appraisal-default',['goals' => $goals, 'identities' => $identities]);
}
} catch (Exception $exception) {
Log::error($exception);
Session::flash('error', 'Action failed! Please try again');
return back();
}
}
view blade: appraisal-default
<div class="row" style="margin-bottom: 10px">
<label class="control-label"> Performance Period:<span style="color:red;">*</span></label>
<div class="col-sm-8">
<select id="identity" name="identity_id" class="form-control">
<option value="">--- Select Performance Period ---</option>
#foreach ($identities as $ids => $name)
<option value="{{ $ids }}" {{ request( 'identity_id')==$ids ? 'selected' : ''}}>{{ $name }}</option>
#endforeach
</select>
</div>
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-sm" name="search">Search</button>
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>
</div>
</div>
In the view, I have two buttons with names: search and viewIdentity
When the
<select id="identity" name="identity_id" class="form-control">
is selected.
If search button is submitted, it displays the result on the same page. This is working.
However, where I'm having problem is when viewIdentity button is submitted. At this point it suppose to take the id of the dropdown as the parameter in:
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<button type="submit" class="btn btn-secondary btn-sm" name="viewIdentity"><i class="fas fa-file-pdf"></i> View Identity</button>
</form>
and display the result in another page: performance_dashboard
I got this error in the view:
production.ERROR: Undefined variable: id
It points to this line in the view:
<form action="{{ route('performance_dashboard', $id->id) }}" method="get" target="_blank" class="form-horizontal" enctype="multipart/form-data">
How do I get it resolved?
Thanks

I got this error "Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type

When i try to insert data into my table this error occurs
Argument 1 passed to Illuminate\Database\Grammar::parameterize() must be of the type array, string given, called in C:\xampp\htdocs\Portal\vendor\laravel\framew...
view
<form method="post" action="{{ route('notice.store') }}">
{{ csrf_field() }}
<div class="form-group">
<label for="Select Group to Post Notice">Select Group to Post Notice </label>
<select class="bg-white text-danger form-control " name='GroupID[]' multiple>
#foreach ($users as $user)
<option value="{{ $user->GroupID }}">{{ $user->GroupID }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="Enter Notice">Enter Notice</label>
<input class="bg-white text-danger p-2 form-control form-control-sm" type="text" name="Notice" placeholder="Enter Notice">
</div>
<input class="btn btn-danger btn-lg px-5" type="submit" name="submit">
</form>
controller
public function store(Request $request)
{
$member = $request->input('GroupID');
foreach($member as $value) {
$storeInfo = new notice();
$storeInfo->GroupID = $request->input('GroupID');
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}
I would imagine the reason you're getting this error is because of:
$storeInfo->GroupID = $request->input('GroupID');
$request->input('GroupID') will return an array (name='GroupID[]') and not an individual id.
Since you're already looping through the group ids you can instead use the value for the GroupId:
public function store(Request $request)
{
foreach ($request->input('GroupID') as $groupId) {
$storeInfo = new notice();
$storeInfo->GroupID = $groupId; //<--here
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('notice');
}
try changing controller logic
public function store(Request $request)
{
//
$member=$request->input('GroupID');
foreach($member as $value){
$storeInfo = new notice();
$storeInfo->GroupID = $value;
$storeInfo->Notice = $request->input('Notice');
$storeInfo->save();
}
return redirect('/notice');
}

Undefined variable: posts when passing parameter from controller to view

I'm trying to create a search function in Laravel and its returning me with "undefined variable: posts" when I do foreach on my view.
My code:
Post Model
class Post extends Model {
protected $fillable = [
'creator',
'post_url',
'books',
'likes',
'created_at'
];
public function user() { return $this->belongsTo(User::class); }
}
Homeview:
<form action="{{ url('/search') }}" method="get">
<input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
</form>
Controller:
public function search($keyword)
{
$result = Post::where('books', 'LIKE', "'%' . $keyword . '%'")->get();
return view('/search', ['posts' => $result]);
}
Route:
Route::get('/search/{keyword}', 'SearchController#search');
Searchview:
#foreach($posts as $post)
<div class="post">{{ $post->id }}</div>
#endforeach
What am I doing wrong here?
This might help you out.
Homeview.blade.php
<form action="/search" method="POST">
#csrf // include your csrf token
<input type="text" class="search-text form-control form-control-lg" id="q" name="q" placeholder="Search" required>
</form>
Searchview.blade.php
<!-- or did you return a collection? -->
#if( $posts->count() > 1 )
<!-- then loop through the posts -->
#foreach( $posts as $post )
<div class="post"> {{ $post->id }} </div>
#endforeach
#else
#if( !empty($posts) )
<div class="post"> {{ $post->id }} </div>
#endif
#endif
Routes/web.php
Route::post('/search', 'PostsController#show')->name('posts.show');
PostsController
use App\Post;
public function show( Request $request )
{
$result = Post::where("books", "LIKE", "%{$request->input('q')}%")->get();
// Uncomment the following line to see if you are returning any data
// dd($result);
// Did you return any results?
return view('searchview', ['posts' => $result]);
}
The reason it wasn't working,
Route::get('/search/{keyword}', 'SearchController#search');
In your route file you were looking for a {keyword} that was never passed by the form. Your form action is action="{{ url('/search') }}". A get variable will not be picked up by a route and if it was you called the input 'q' anyway.
So then in your controller you were looking for the keyword being passed that is never passed in.
public function search($keyword)
Instead the correct thing to do is pass in the Request object like so
public function search(Request $request)
Then use $request->input('q') to retrieve the passed value through your form.
In your example $keyword would always have been blank.
Corrected code
Homeview:
<form action="{{ url('/search') }}" method="get">
<input type="text" class="search-text form-control form-control-lg" name="q" placeholder="Search" required>
</form>
Controller:
public function search(Request $request)
{
$result = Post::where('books', 'LIKE', "%{$request->input('q')}%")->get();
return view('/search', ['posts' => $result]);
}
Route:
Route::get('/search', 'SearchController#search');
Searchview:
#foreach($posts as $post)
<div class="post">{{ $post->id }}</div>
#endforeach
try:
return view('/search')->with('posts', $result);
Or even better with dinamic vars.
return view('/search')->withPosts($result);

Laravel - How to handle errors on PUT form?

I am working with laravel 5.2 and want to validate some data in an edit form. I goal should be to display the errors and keep the wrong data in the input fields.
My issue is that the input is validated by ContentRequest and the FormRequest returns
$this->redirector->to($this->getRedirectUrl())
->withInput($this->except($this->dontFlash))
->withErrors($errors, $this->errorBag);
which is fine so far. Next step the edit action in the controller is called and all parameters are overwritten.
What I have currently done:
ContentController:
public function edit($id)
{
$content = Content::find($id);
return view('contents.edit', ['content' => $content]);
}
public function update(ContentRequest $request, $id)
{
$content = Content::find($id);
foreach (array_keys(array_except($this->fields, ['content'])) as $field) {
$content->$field = $request->get($field);
}
$content->save();
return redirect(URL::route('manage.contents.edit', array('content' => $content->id)))
->withSuccess("Changes saved.");
}
ContentRequest:
class ContentRequest extends Request
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'title' => 'required|min:3',
'body' => 'required|min:3'
];
}
}
How can I fix this? The form looks like this:
<form action="{!! URL::route('manage.contents.update', array('content' => $content->slug)) !!}"
id="site-form" class="form-horizontal" method="POST">
{!! method_field('PUT') !!}
{!! csrf_field() !!}
<div class="form-group {{ $errors->has('title') ? 'has-error' : '' }}">
<label for="title" class="col-sm-2 control-label">Title</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="title" id="title" placeholder="Title"
value="{{ $content->title }}">
#if ($errors->has('title'))
<span class="help-block">
<strong>{{ $errors->first('title') }}</strong>
</span>
#endif
</div>
</div>
</form>
Try something like the following:
<input
type="text"
class="form-control"
name="title"
id="title"
placeholder="Title"
value="{{ old('title', $content->title) }}" />
Note the value attribute. Also check the documentation and find Retrieving Old Data.

Resources