Autocomplete cannot search in table with two foreign key Laravel - laravel-8

and i want make autosearch from local database, but in other case with table in detail cannot be get, but in just manual search is successfully:
Image of table with two foreign key
code in my controller for method index is (this is just manual search) :
public function index(Request $request)
{
$filterKeyword = $request->get('keyword');
$data['course'] = Course::paginate(5);
if ($filterKeyword) {
$data['course'] = Course::where('title', 'LIKE', "%$filterKeyword%")->paginate(5);
}
return view('course.index', $data);
}
code in my routes/web is
Route::get('course.search', function (Request $request) {
$query = $request->get('query');
$filterResult = Course::where('title', 'LIKE', '%' . $query . '%')->get();
return response()->json($filterResult);
});
my code in view(interface) is :
<div class="col-8">
<input type="search" class="typeahead form-control" value="{{ Request::get('keyword') }}"id="keyword" name="keyword">
</div>
<div class="col-2">
<button type="submit" class="btn btn-outline-info"><span class="fas fa-search"></span></button>
</div>
my javascript for get query when input :
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<script type="text/javascript">
var route = "{{ url('course.search') }}";
$('#keyword').typeahead({
source: function(query, process) {
return $.get(route, {
query: query
}, function(data) {
return process(data);
});
}
});
</script>
is there a certain way to anticipate from foreign field?

Related

How to send upload file to controller - files is always empty

UserAdmin.cshtml
<div class="modal-body">
<form id="upload-file-dialog-form"
class="needs-validation form-group" novalidate
onsubmit="UploadFile()"
enctype="multipart/form-data"
method="post">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file_Uploader" />
</div>
<div class="form-group">
<div class="col-md-10 modal-footer">
<input type="submit" class="btn btn-primary" value="Upload"/>
</div>
</div>
</form>
</div>
UserAdmin.js
function UploadFile() {
var form = $('form')[0];
var formData = new FormData(form);
console.log(formData);
$.ajax({
url: '/API/Upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (data) {
},
error: function () {
}
});
}
Controller
[HttpPost]
public async Task<IActionResult> Upload(List<IFileUpload> files)
{
try
{
var check = (HttpContext.Request.Form.Files);
long size = files.Sum(f => f.Length);
//some code removed
return Ok(new { count = files.Count, size, filePaths });
}
catch (Exception exc)
{
logger.Error("Error in upload() " + exc.Message);
throw;
}
}
the files in controller is always 0.
If onsubmit="UploadFile()" is replaced with
asp-controller="API" asp-action="Upload"
then I get something in check but again converting it to List of IFileUpload is another blocker
First of all, If you want to upload multiple files you have to add multiple="multiple" in your input. FormData will be empty if you print it like this, you have to iterate through the items.
<input type="file" name="file_Uploader" multiple="multiple" />
Please follow the codes below, I tested it working.
Complete form
<form id="upload-file-dialog-form"
onsubmit="UploadFile(event)">
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="file_Uploader" multiple="multiple" />
</div>
<div class="form-group">
<div class="col-md-10 modal-footer">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</div>
</form>
Construct form data like below
<script>
function UploadFile(e) {
e.preventDefault();
var formData = new FormData($('#upload-file-dialog-form')[0]);
$.each($("input[type='file']")[0].files, function(i, file) {
formData.append('files', file);
});
$.ajax({
url: '/API/Upload',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(data) {
},
error: function() {
}
});
}
</script>
Action method
[HttpPost]
public async Task<IActionResult> Upload(List<IFormFile> files)
{
try
{
var check = (HttpContext.Request.Form.Files);
long size = files.Sum(f => f.Length);
return Ok(new { count = files.Count, size });
}
catch (Exception exc)
{
_logger.LogWarning("Error in upload() " + exc.Message);
throw;
}
}
In model class, use IFormFile
public List<IFormFile> file_Uploader {get;set;}"
In controller, change the parameter like this
public async Task<IActionResult> Upload(List<IFormFile> file_Uploader)
add multiple to upload more files, and keep the name attribute the same as parameter to post value, code like below:
<input type="file" name="file_Uploader" multiple/>
result:

foreach loop for two variables in laravel

below is my codes in controller and php file. How do I run the foreach for both $posts and $users? I have tried #foreach(array_merge($posts,$users) as $post) but doesn't work.
WelcomeController:
public function index()
{
$posts = Post::all();
$users = User::all();
return view('welcome', [
'posts' => $posts,
'users' => $users
]);
}
blade.php:
#foreach($posts as $post)
<div class="column">
<div class="content">
<img src="/storage/{{$post->image}}" style="width:100%" id="myImg">
<h4>By {{$user->name}}</h4>
<p>{{$post->caption}}</p>
<p class="description">{{$post->description}}</p>
</div>
</div>
#endforeach
I suggest you to use one to many (inverse) relationship visit
In post model add:
public function user()
{
return $this->belongsTo('App\Models\User');
}
And in blade.php:
{{ $post->user->name }}

Filter in AngularJS converted to VueJS

I used AngularJS for a long time and now I'm making the switch to VueJS, but I can't figure out why this simple Angular code isn't easily converted to in VueJS.
This is a search-field:
<input type="search" ng-model="searchFor.$">
And then I'm using it like this:
<ul>
<li ng-repeat="user in users | filter: search">
{{ user.email }}
</li>
</ul>
This filter is an easy thing and search in everything in the 'users'-array, so not even the mailaddresses.
How can I do this easily in Vue? Can't figure it out, only can find solutions where you define the specific column it should look.
In this case you must use a computed property that returns a filtred array. The computed array will recursively search in each string properties of your user.
Here is an example
new Vue({
el: '#app',
data() {
return {
search : '',
users : [{name : "John Doe", email : "xerox#hotmail.us"}, {name : "Jane Doe"}],
}
},
computed : {
filteredUsers() {
if (!this.search) return this.users
var find = function(object, search) {
for (var property in object) {
if (object.hasOwnProperty(property)) {
if (typeof object[property] == "object"){
find(object[property]);
} else if (object[property].includes !== undefined){
if (object[property].includes(search)) return true;
}
}
}
return false;
}
return this.users.filter(user => {
return find(user, this.search)
})
}
}
})
<script src="https://npmcdn.com/vue/dist/vue.js"></script>
<div id="app">
<input type="text" v-model="search" placeholder="Filter users">
<p v-show="!filteredUsers.length">No results</p>
<ul>
<li v-for="user in filteredUsers">{{user.name}}, email : {{user.email || 'N/A'}}</li>
</ul>
</div>

How to toggle individual row at a time in vue for rows generated from an array? [duplicate]

I work with single file components and have a list in one of them. This list should work like a accordion, but as far as I can find in the Vuejs docs, it's not that easy to make each item open separately very easily. The data (questions and answers) is retrieved from an ajax call. I use jQuery for that, but would like to know how I can make the accordion work Vuejs-style. Any help would be appreciated!
Here's the code:
export default {
name: 'faq-component',
props: ['faqid', 'faqserviceurl', 'ctx'],
data: function () {
return {
showFaq: "",
totalFaqs: this.data,
isOpen: true
}
},
watch: {
'showFaq': function(val, faqid, faqserviceurl) {
var self = this;
$.ajax ({
url: this.faqserviceurl,
type: 'GET',
data: {id: this.faqid, q: val, scope:1},
success: function (data) {
self.totalFaqs = data;
},
error: function () {
$("#answer").html('Sorry');
}
});
}
},
methods: {
'toggle': function() {
this.isOpen = !this.isOpen
}
}
}
<template>
<div class="card faq-block">
<div class="card-block">
<form>
<div class="form-group">
<input class="form-control" type="text" placeholder="Your question" id="faq" v-model="showFaq">
</div>
</form>
<div id="answer"></div>
<ul class="faq">
<li v-for="faq in totalFaqs">
<p class="question" v-html="faq.vraag" v-bind:class={open:isOpen} #click="isOpen = !isOpen"></p>
<p class="answer" v-html="faq.antwoord"></p>
</li>
</ul>
</div>
</div>
</template>
Add an isOpen property to each object in totalFaqs and use that instead of your single isOpen property in data.
<p class="question" v-html="faq.vraag" v-bind:class={open: faq.isOpen} #click="faq.isOpen = !faq.isOpen"></p>
If you can't change the model from the server side, then add it client side.
success: function (data) {
data.forEach(d => self.$set(d, 'isOpen', false))
self.totalFaqs = data
}

Using Javascript to send an invite to facebook friend

I'm trying inviting facebook friends to our application since from 2 days. Still not yet got the solution.
I have tried the following code and its sending request to friends but those are not getting any timeline or notification or anything.
<ul id="fcbklist">
<?php foreach($facebook_friends as $key => $friend): ?>
<li> <img src="https://graph.facebook.com/<?php echo $key; ?>/picture"/><strong><?php echo $friend;?></strong><br />
<input type="checkbox" name="friendids[]" class="checkbox" value="<?php echo $key;?>" />
</li>
<?php endforeach; ?>
</ul>
<div id="fb-root"></div>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
<script type="text/javascript">
FB.init({
appId : '259234574212521',
frictionlessRequests: true
});
function sendRequestToRecipients() {
var ids = [];
$('.checkbox').each(function() {
if($(this).is(':checked')) {
ids.push($(this).val());
}
})
alert(ids);
var user_ids = ids;
FB.ui({method: 'apprequests',
message: 'Request to StoryTag',
to: user_ids
}, requestCallback);
}
function sendRequestViaMultiFriendSelector() {
FB.ui({method: 'apprequests',
message: 'Request to StoryTag'
}, requestCallback);
}
function requestCallback(response) {
// Handle callback here
if(response){
///SUCCESS HERE
alert('successful');
} else {
///FALIURE COMES HERE
alert('failure');
}
}
</script>
Please help me get rid of it. The work is more appreciated.
Paremeter "to" of apprequest should be a String, not an Array, so you need to change
var user_ids = ids;
to
var user_ids = ids.join(',');
Documentation: http://developers.facebook.com/docs/reference/dialogs/requests/#direct_request