This is the documentation,
https://www.elastic.co/guide/en/elasticsearch/client/php-api/current/_quickstart.html
The questions are in screenshot below:
Edit:
For example,I want to get the search result in this example below,how to write the controller?
view:
<html>
<head>
<meta charset="utf-8">
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/tether/1.3.2/css/tether.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<nav class="navbar navbar-light bg-faded">
<a class="navbar-brand" href="#">Navbar</a>
<ul class="nav navbar-nav">
<li class="nav-item active">
<a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Features</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Pricing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
</ul>
<form class="form-inline pull-xs-right">
<input class="form-control" type="text" placeholder="Search">
<button class="btn btn-success-outline" type="submit">Search</button>
</form>
</nav>
</div>
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/tether/1.3.2/js/tether.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js"></script>
</body>
</html>
route:
<?php
Route::group(['middleware' => 'web'], function () {
Route::resource('/search', 'SearchController');
});
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class SearchController extends Controller
{
public function index()
{
//
}
public function create()
{
//
}
public function store(Request $request)
{
//
}
public function show($id)
{
//
}
public function edit($id)
{
//
}
public function update(Request $request, $id)
{
//
}
public function destroy($id)
{
//
}
}
Model:Article.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
protected $fillable = [
'title', 'content'
];
}
Seems to me like they only provided the instructions on how to install composer but you still need to actually require the package with composer by using:
composer require elasticsearch/elasticsearch
If you run composer install it should be autoloaded for you so that you can call it from anywhere. From that point on you can just instantiate the Elasticsearch clientbuilder where you need it.
The "code on the left" is a return response you are getting it is the elasticsearch json converted to a php array.
To actually get up and running you need:
$client = Elasticsearch\ClientBuilder::create()->build();
$params = [
'index' => 'my_index',
'type' => 'my_type',
'id' => 'my_id',
'body' => ['testField' => 'abc']
];
$response = $client->index($params);
print_r($response);
The above should be pretty much what you need, you need to change the params to whatever your settings are and the body to what your search query is.
Edit
Looked over the composer.json edit so you need actually need to composer require since it's already in the file. Simply "composer install" is enough.
This is what I whipped up quickly, I tried the index method and it works fine. In this case I still had an elasticsearch server with an index name of "node" and a type of "vacation" this needs to change depending on your personal elasticsearch server. The logical thing here would be to have a type of "user" ofcourse.
class UsersController extends Controller
{
// the main elasticsearch instance created with the constructor
protected $client;
public function __construct() {
$hosts = [
// since I am using homestead I have to refer to the ip address of my host machine on which I have installed
// elasticcsearch, otherwise the default localhost option will point to homestead localhost
'192.168.178.10:9200'
];
$this->client = \Elasticsearch\ClientBuilder::create()->setHosts($hosts)->build();
}
public function index()
{
$params = [
'index' => 'node',
'type' => 'vacation',
'body' => [
'query' => [
'match_all' => []
]
]
];
$response = $this->client->search($params);
print_r($response);
}
public function create()
{
$params = [
'index' => 'node',
'type' => 'vacation',
'id' => '1029',
'body' => [
'query' => [
'match_all' => []
]
]
];
$response = $this->client->index($params);
print_r($response);
}
}
The elasticsearch documentation has all the settings for updating, deleting, indexing and searching neatly documented so just implement those for each resource method.
There is plenty of room for improvement if you want to do it the laravel way and implement this neatly. But this should at least get you going. A better option is to make a serviceprovider for the Elasticsearch client builder and inject it into your UsersController via typehinting but I will leave that up to you.
Good luck.
Related
I am creating a backend page that i want to use to manage employee data (with laravel 5.8). I Added a link on a sidemenu blade that points to the employee overview page.
Link:
<li class="nav-item">
<a href="{{ action('Profiles\Controllers\EmployeeController#index') }}"
class="nav-link {{ Request::is('admin') ? 'active' : null }}">
<i class="fas fa-user"></i> Employees
</a>
</li>
I also made a controller to fetch the data that i want to display, currently with dd() in the function.
class EmployeeController extends Controller
{
public $model = CustomerLogin::class;
protected $views = 'WebshopCustomers::customerslogins ';
static $routes = ['index', 'create', 'store', 'edit', 'update', 'destroy'];
protected $datatableSelect = 'customer_logins';
protected $datatableRelations = ['roles', 'permissions'];
protected $datatableTrashed = true;
protected $datatableRawColumns = ['email', 'deleted_at'];
public function baseBreadcrumbs()
{
return [
['name' => 'Gebruikersbeheer']
];
}
public function index()
{
dd('test_index');
}
}
After a reloaded the page shows the following error:
ErrorException (E_ERROR):
Action App\Modules\Profiles\Controllers\EmployeeController#index not defined.
(View: C:\xampp\htdocs\shopname\app\Modules\Backend\Views\partials\sidebar-default.blade.php)
Route:
I googled this error and read advice to check if the route to the function existed (it didnt) so i added that.
Route::get('/', 'EmployeeController#index')->name('employeeprofiles.index');
Changing the value of $namespace to null in the RouteServiceProvider was also mentioned, setting it to null did not change the current behavior of my code.
How can i correct this, what other things can i check?
in Laravel 5.8 in the RouteServiceProvider the namespace for routes was pointed to:
App/Http/Controllers
in the new Laravel I think they removed it.
Now for your problem, you should check where is the namespace from RouteServiceProvider pointing too, and then adding extra 'directories' on it; e.g
Route::get('/',
'App\Modules\Profiles\Controllers#index')->name('employeeprofiles.index');
In my Laravel application, the data are loaded via ajax for a data table. The performance is very bad. So I created a test script to measure the loading time.
public function index()
{
$mt1 = microtime(true);
$data = $this->repo->all();
$resource = ProjectResource::collection($data);
$response = response()->json($resource);
$mt2 = microtime(true);
dd($mt2 - $mt1);
}
There are 200 rows in the DB.
The model has 4 relations.
The script above takes> 6s to render the data.
If I uncomment the line $response = response()->json($resource);, the loading time is < 0.2s
What are the possibilities to speed up the render time for the JSON response?
The $data model:
Appends:
trait ProjectAttribute
{
public function getActionAttribute()
{
return $this->editButton().$this->deleteButton();
}
public function editButton()
{
if (Auth()->user()->can('update salesOrder')) {
return '<button data-toggle="tooltip" data-placement="top" title="'.__('buttons.general.crud.edit').'" class="btn btn-info btn-sm editProject mr-1" ><i class="fas fa-pen"></i></button>';
}
return "";
}
public function deleteButton()
{
if (Auth()->user()->can('delete salesOrder')) {
return '<button data-toggle="tooltip" data-placement="top" title="'.__('buttons.general.crud.delete').'" class="btn btn-danger btn-sm deleteProject" ><i class="fas fa-times"></i></button>';
}
return "";
}
public function getActiveLabelAttribute()
{
if ($this->active) {
return "<span class='badge badge-info'>Aktiv</span>";
}
return "<span class='badge badge-secondary'>Inaktiv</span>";
}
}
The model:
<?php
namespace App\Models\Project\Project;
use Altek\Accountant\Contracts\Recordable;
use Altek\Accountant\Recordable as RecordableTrait;
use App\Models\Traits\Uuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Project extends Model implements Recordable
{
use ProjectAttribute, ProjectMethod, ProjectRelationship, ProjectScope, Uuid, RecordableTrait, SoftDeletes;
protected $fillable = [
'name',
'description',
'sales_order_id',
'project_leader_id',
'project_type_id',
'project_status_id'
];
protected $appends = [
'action',
'activeLabel',
'salesOrderName',
'projectLeaderName',
'creatorName',
'statusName',
'statusLabel',
'typeLabel'
];
protected $with = ['projectLeader', 'salesOrder', 'projectType', 'projectStatus'];
}
The resource:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class Project extends JsonResource
{
/**
* Transform the resource into an array.
*
* #param \Illuminate\Http\Request $request
* #return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'sales_order_name' => $this->salesOrder->name,
'sales_order' => $this->salesOrder,
'project_leader' => $this->projectLeader,
'project_leader_name'=> $this->projectLeader->full_name,
'creator' => $this->creator,
'creator_name' => $this->creator->full_name,
'type' => $this->projectType,
'type_name' => $this->projectType->name,
'type_label' => $this->projectType->typeLabel,
'status' => $this->projectStatus,
'status_name' => $this->projectStatus->name,
'status_label' => $this->projectStatus->statusLabel,
'created_at' => $this->created_at->format('Y-m-d'),
'action' => $this->action
];
}
}
There are several ways to profile a request to get some information as to what is taking the server so long to respond.
BlackFire - Which comes by default in Laravel Homestead in development or Laravel Forge for production
Laravel DebugBar - Can also be used in development (my personal favorite)
These will give you a lot more information regarding the parts of your code that may be taking time to complete and there are several more if you google around for Laravel or PHP profilers to find something that suits your needs.
Check out Enlightn, a tool to boost your Laravel app's performance and security. It scans your code and server configurations to provide actionable recommendations on improving performance and security.
I'm new to laravel, axios and vue and I used this tutorial to help make a ToDo list:
I want to tweak the basic tutorial by allowing different users to store and view their tasks. I added new user registration and login, but each user would see everyone's list, not only theirs. So I made a one to many relationship between the User and Task model and added these methods to the models:
class User extends Authenticatable
{
...
public function tasks()
{
return $this->hasMany('App\Task');
}
}
class Task extends Model
{
...
public function user()
{
return $this->belongsTo('App\User');
}
}
I updated TaskController.php and TaskList.vue to display only the active user's tasks, but now in the view no list appears and new tasks can't be added.
Here is the code for the two. Everything is the same as the tutorial, except I commented next to the parts that I added:
<?php
namespace App\Http\Controllers;
use App\Task;
use Illuminate\Http\Request;
class TaskController extends Controller
{
$user = Auth::user(); //Added by me
public function index()
{
return Task::latest()->where('user_id', $user->id)->get(); //Added by me,
//this query returns whats expected in php artisan tinker
//was previously return Task::latest()->get();
//I also tried this: return $this->user->tasks->toJSON()
}
public function store(Request $request)
{
$this->validate($request, [
'body' => 'required|max:500'
]);
return Task::create([
'body' => request('body'),
'user_id' => $user->id //Added by me
]);
}
public function destroy($id)
{
$task = Task::findOrFail($id);
$task->delete();
return 204;
}
}
In TaskList.vue
<template>
<div class='row'>
<h1>My Tasks</h1>
<h4>New Task</h4>
<form action="#" #submit.prevent="createTask()">
<div class="input-group">
<input v-model="task.body" type="text" name="body" class="form-control" autofocus>
<span class="input-group-btn">
<button type="submit" class="btn btn-primary">New Task</button>
</span>
</div>
</form>
<h4>All Tasks</h4>
<ul class="list-group">
<li v-if='list.length === 0'>There are no tasks yet!</li>
<li class="list-group-item" v-for="(task, index) in list">
{{ task.body }}
<button #click="deleteTask(task.id)" class="btn btn-danger btn-xs pull-right">Delete</button>
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
list: [],
task: {
id: '',
body: '',
user_id: '' ///Added by me
}
};
},
created() {
this.fetchTaskList();
},
methods: {
fetchTaskList() {
axios.get('api/tasks').then((res) => {
this.list = res.data;
});
},
createTask() {
axios.post('api/tasks', this.task)
.then((res) => {
this.task.body = '';
this.task.user_id = ''; ///added by me
this.edit = false;
this.fetchTaskList();
})
.catch((err) => console.error(err));
},
deleteTask(id) {
axios.delete('api/tasks/' + id)
.then((res) => {
this.fetchTaskList()
})
.catch((err) => console.error(err));
},
}
}
</script>
</script>
The app worked until I added the few lines mentioned above. Now nothing shows in the display and no new tasks can be added. I am new to laravel and totally new to axios and vue, but to me it seems like what I added should work. There are no error messages when I run it, it just doesn't produce what I want.
I made a StatusController to change the status. I have Banner model and Page model.
My StatusController Looks like:
namespace App\Http\Controllers;
use App\Banner;
use App\Page;
use Illuminate\Http\Request;
class StatusController extends Controller
{
public function changeStatus($modelName, $id)
{
$model = $modelName::select('id','status')->whereId($id)->first();
if($model->status == 1)
{
$model->status = 0;
} else {
$model->status = 1;
}
$model->update();
$notification = [
'message' => 'Updated Successfully!',
'alert-type' => 'success'
];
return back()->with($notification);
}
}
My Web.php is :
Route::post('status/{modelName}/{status}', 'StatusController#changeStatus')->name('status');
My View looks Like this:
<form action="{{route('status',['model' => 'Page', 'status' => $page->id])}}" method="POST">
{{csrf_field()}}
<button title="Turn OFF" class="btn btn-xs btn-default">
<i class="fa
#if($page->status==1)
status-active
fa-toggle-on
#else
status-inactive
fa-toggle-off
#endif
fa-2x"></i>
</button>
I want to change my status when I click status icon. But when i click it. It shows an error.
FatalThrowableError in StatusController.php line 15:
Class 'Page' not found
When I tried dd($modelName) it shows Page. What's going wrong
Also, Please tell me if there is any other better idea to change status. For all my models.
Even though you have the use App\Page; statement at the top, php will have issues calling functions on a class when all you have is the class string. Page is different from 'Page'. Instead, you need to use call_user_func:
$model = call_user_func("App\\$modelName::select", ['id','status'])
->whereId($id)
->first();
I am trying to insert record using Cakephp.My model name is something like User.php.
And My working controller name is SignupsController.I want to insert record using this two but I cant.I am give my some codes below :
View :
<?php echo $this->Form->create('Signups',array('action' => 'registration'));?>
<div class="row-fluid">
<div class="span5">
<label class="">*First Name</label>
<?php echo $this->Form->input('first_name', array('type' => 'text','label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
<div class="span5">
<label class="">*Last Name</label>
<?php echo $this->Form->input('last_name', array('type' => 'text', 'label' => false, 'class' => 'input-xlarge validate[required]', 'div' => false)); ?>
</div>
</div>
<?php echo $this->Form->end(); ?>
My controller code is given below :
class SignupsController extends AppController {
var $name = 'Signups';
var $uses=array("User");
public function registration()
{
$this->layout="reserved";
$this->Club->create();
if (isset($_POST['registration'])) {
echo "This is";
echo "<pre>";print_r($this->request->data);echo"</pre>";
$this->User->save($this->request->data);
//$this->Session->setFlash(__('Promoter registration has been done successfully'));
//$this->redirect('registration');
//$this->redirect(array('action' => 'registration'));
}
}
}
My model name is different which's name is User.php
I want to insert the record using this above code.Any idea how to insert?
you can do this by loading the users model in current controller just write the following line
$this->loadModel('Name of the Model').
then
$this->nameofmodel->save()
As you are unable to understand see this
Controller::loadModel(string $modelClass, mixed $id)¶
The loadModel() function comes handy when you need to use a model which is not the controller’s default model or its associated model:
$this->loadModel('Article');
$recentArticles = $this->Article->find(
'all',
array('limit' => 5, 'order' => 'Article.created DESC')
);
$this->loadModel('User', 2);
$user = $this->User->read();
Above pasted code is taken from CookBook of Cakephp, if you still do not understand just read it it has complete detailed explanation you can also see this to understand
you can use it with $uses variable in SignupController
class SingupController extends AppController
{
public $uses = array('User');
//rest of stuff
}
Or, if you want, you can load it on-demand inside a method:
$this->loadModel('User'); //now model is loaded inside controller and used via $this->User
EDIT: Your data array has to include the name of the model you're saving. So, replace:
$this->Form->create('Signups',array('action' => 'registration')
with:
$this->Form->create('User',array('url' => array('controller' => 'signups', 'action' => 'registration'));