Symfony3: Return a full JsonResponse loop - php

I just created a project to try Algolia search solution and it's working good, but I'm not able to return a JSON response.
Here is my code
controller:
/**
* #Route("/api/search/user/{query}", name="search_query")
*/
public function searchAction($query)
{
$entityManager = $this->getDoctrine()->getManagerForClass(User::class);
$users = $this->indexManager->search($query, User::class, $entityManager);
if($users) {
$result = $this->renderView('xxx/search_user.html.twig', [
'users' => $users
]);
return new JsonResponse(['success' => true, 'users' => [$result]]);
}
return new JsonResponse(['success' => false, 'users' => []]);
}
html:
{{ users[0].username }}
This code is working but only returning 1 user not all users, idem if I do a loop inside my twig file it will render all users but not in a good way:
screenshot
Thanks for the help and sorry for my english.

this is because twig creates the view on the server after the response.
I suggest you to simply create the users array directly inside the controller and remove the part of render view.
for example :
foreach($users as $user) {
$result[]['name'] = $user['name'];
}
and then use $result.
I hope it helps you, Regards

Related

Too few arguments to function when downloading a PDF

I am trying to generate a PDF with some details of an individual user using the Barryvdh DomPDF library but having some problems trying to generate it.
Controller method:
public function downloadPDF(Card $card)
{
$user = User::find($card->user_id);
$pdf = (new \Barryvdh\DomPDF\PDF)->loadView('pdf/cardsReport', $user);
return $pdf->download('cards.pdf');
}
Here is how I am referencing the route.
Download PDF
Route:
$router->get(
'/downloadPDF/{card}',
[
'as' => 'get::admin.download-pdf',
'uses' => 'EditCardController#downloadPDF',
]
);
I get this error:
Type error: Too few arguments to function
Barryvdh\DomPDF\PDF::__construct(), 0 passed in EditCardController.php
and exactly 4 expected.
I'm confused by this as I've seen many samples of using pdf and laravel where you don't need to pass four arguments so was wondering why this would be?
According to documentation, you should use facade instead of constructor:
public function downloadPDF(Card $card)
{
$user = User::find($card->user_id);
$pdf = PDF::loadView('pdf/cardsReport', $user);
return $pdf->download('cards.pdf');
}
Kindly use below format
$data = [
'title' => 'Welcome to ItSolutionStuff.com',
'date' => date('m/d/Y'),
];
$pdf = App::make('dompdf.wrapper');
$pdf->loadView('bill',$data);
return $pdf->stream();

Insert array of arrays in Lumen with Eloquent ORM

The POST request I'm sending looks like this:
{ "array1":
[
{"title":"my blogADD","description":"myblogdescriptionADD","status":1},
{"title":"my blogUPDATEDADD","description":"myblogdescriptionUPDATEDADD","status":1},
{"title":"my blog33ADD","description":"myblogdescription33ADD","status":1}
]
}
Its JSON format, headers have been set.
The controller code which gets the request looks like this:
public function create(Request $request){
$this->validate($request, [
'array1' => 'present|array',
'array1.*.title' => 'required',
'array1.*.description' => 'required'
]);
$data = $request->getContent();
$data = json_decode($data, true);
//dd($data);
Article::insert($data);
}
Now, I've looked into multiple questions and answers on SO on this problem, and the findings are somehow contradictory.
Model::insert() shall be able to insert multiple rows in ONE call.
However, as you can see, this hasn't worked for me so far.
Model::create() is only able to create one new row, but I found solutions which use loops to iterate over the arrays. I would very very much like to avoid such a solution, unless someone can FOR CERTAIN tell me that there is no other, simple solution. Because I very much believe that there must be one.
When I input the json_decoded ARRAY then I get the response that an Array to String conversion is hindering the process.
When I input the mere JSON-String, then I get the error:
"Argument 1 passed to Illuminate\Database\Query\Builder::insert() must be of the type array, string given, called in E:\LumenTut\firstTut\vendor\illuminate\database\Eloquent\Builder.php on line 1350"
Well, here are two links to SO posts which, in my opinion, basically dealt with the same problem. But somehow it seems they could solve it and I can't, so I wonder what I am missing:
How to insert a multidimensional array in a database using laravel
laravel 5.6 bulk inserting json data
For completeness, here is the full Code of ArticleController.php:
EDIT:
<?php
namespace App\Http\Controllers;
//use Validator;
use App\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
//
}
//
public function showAllArticles(){
return response()->json(Article::get(['title', 'description', 'status'])); // ::get([]) spezifiziert die zu referenzierenden Attribute
// ::all() referenziert alle Attribute einer Tabelle/Relation
}
public function showOneArticle($id){
return response()->json(Article::find($id));
}
public function create(Request $request){
$this->validate($request, [
'array1' => 'present|array',
'array1.*.title' => 'required',
'array1.*.description' => 'required'
]);
$data = $request->getContent();
//$data = json_decode($data, true);
//dd($data);
Article::insert($data);
}
public function update($id, Request $request){
$this->validate($request, [
'title' => 'required',
'description' => 'required'
]);
$article = Article::findOrFail($id);
$article->update($request->all());
return response()->json($article, 200);
}
public function delete($id, Request $request){
Article::findOrFail($id)->delete();
return response('Deleted Successfully', 200);
}
public function resetRecords(Request $request){
Article::where('id', '>', 2)->delete();
}
}
From the looks of it, it feels like you are trying to push array1 directly in your table, whereas you need to push the content of it so maybe try like this, in your controller code:
$requestData = $request->all();//this will give you an array with key array1
$data = $requestData['array1'];//this will give you data you want to insert
Article::insert($data);
Based on the error. You are not passing an array. You can change the $data with
$data = $request->all();
$request->all() returns the data from the post in array.
You can rewrite your create method with the following.
public function create(Request $request){
$request->validate([
'array1' => 'present|array',
'array1.*.title' => 'required',
'array1.*.description' => 'required'
]);
$data = $request->all();
Article::insert($data['array1']);
}

how to pass two variables to view in controller (laravel 5.3)

I have two different queries which are saved in two variables.I want to pass the variables to view page from controller.
public function getApprovalList(){
// $users = select query..
// $request = select query..
return view('travelerHome',['users'=>$users,'request'=>$request]);
}
solution:
controller
return view('travelerHome',['users'=>$users,'requestList'=>$request]);
view
#foreach ($requestList as $req)
{{$req->traveler_name }}
#endforeach
return view('travelerHome')->with(array('users'=>$users,'request'=>$request));
You can use return view('travelerHome', compact('users', 'request')); too
Do like this
return view('travelerHome')->with('users'=>$users)->with('request'=>$request);
Code with you have written that is correct, you need to remove the comment only, I am also using the same method for pass the variable to View. Here is the example.
return view('admin.product.product.edit', ['product' => $product,
'attribute_set' => $productAttributes,
'category' => $cates,
'images' => $images,
'status' => $status,
'countries' => $countries,
'crane_manufacture' => $crane_manufacture,
'product_category' => $productCategory]);
}
And it's also working
So, in your code you need to
public function getApprovalList(){
$users = 'select query..';
$request = 'select query..';
return view('travelerHome',['users'=>$users,'request'=>$request]);
}

Yii2: Call to undefined method backend\models\CreateBookings::model()

Trying to fetch data from db
in controllers
$model = new CreateBookings();
$data = CreateBookings::model()->findByPk();
return $this->render('view', [
'data' => $data,
]);
in view :
<?php echo $data->booking_id?>
can somebody tell me what am i doing wrong?
The alternative for Yii1 findByPk in Yii2 is findOne($id)
$model = CreateBookings::findOne($id);
or the equivalent
$model = CreateBookings::find()
->where(['id' => $id])
->one();
for your view you can use
$data = CreateBookings::findOne($id)) ;
and you should have the $id value.
Answering My own question:
I wanted to show database values in my View.
In controller actionView I added-
$data = CreateBookings::findOne($id);
and rendered
'data' => $data,
To show value in view I used
<?php echo Html::encode($data->booking_id);?>

Laravel 4 - view query

I have 3 views (which display settings for each): Users, Groups, Options
Each of these views is successfully rendering, using the below. The controller passes the database info into each view.
#extends('master')
#section('main-title')
Title
#stop
#section('main-content')
// All the divs, content etc (working fine)
#stop
I also have one more view: Settings
The idea of this view is simple, to be an overview of all the settings from the Users, Groups and Options. So essentially I'm trying to pull together each of the 3 views 'main-content' output, and put it within the #section('main-content') within my Settings view. However I have no idea how.
The only option I can think of is to duplicate the content within the Settings view (index function) - however this will cause issues when I want to change something as I'll need to do it in two templates.
My controller:
public function index()
{
$users = User::all();
$options = Option::all();
$groups = Group::all();
return View::make('layouts.settings', array('users' => $users, 'options' => $options, 'groups' => $groups));
}
public function users()
{
$users = User::all();
return View::make('layouts.settings.users', array('users' => $users));
}
public function options()
{
$options = Option::all();
return View::make('layouts.settings.options', array('options' => $options));
}
public function groups()
{
$groups = Group::all();
return View::make('layouts.settings.groups', array('groups' => $groups));
}
Is there anyway, I can say within my Settings view: include the content within 'main-content' from the following views (Users, Groups, Options). Or, use nested view which I have tried but cannot get working.
Thanks in advance.
Here you go - may need fine-tuning: http://paste.laravel.com/xZr

Categories