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();
Related
How can I remove the parameters from a URL after processing in my controller? Like this one:
mydomain/mypage?filter%5Bstatus_id%5D
to
mydomain/mypage
I want to remove the parameters after the ? then I want to use the new URL in my view file. Is this possible in laravel 5.2? I have been trying to use other approaches but unfortunately they are not working well as expected. I also want to include my data in my view file. The existing functionality is like this:
public function processData(IndexRequest $request){
//process data and other checkings
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I want it to be like:
public function processData(IndexRequest $request){
//process data and other checkings
// when checking the full url is
// mydomain/mypage?filter%5Bstatus_id%5D
// then I want to remove the parameters after the question mark which can be done by doing
// request()->url()
// And now I want to change the currently used url using the request()->url() data
return view('admin.index')
->with([
'data' => $data,
'person' => $persons,
]);
}
I'm stuck here for days already. Any inputs are appreciated.
You can use request()->url(), it will return the URL without the parameters
public function processData(IndexRequest $request){
$url_with_parameters = $request()->url();
$url= explode("?", $url_with_parameters );
//avoid redirect loop
if (isset($url[1])){
return URL::to($url[0]);
}
else{
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
}
add new url to your routes and assuming it will point to SomeController#SomeMethod, the SomeMethod should be something like :
public function SomeMethod(){
// get $data and $persons
return view('admin.index')
->with(['data' => $data,
'person' =>$persons,]);
}
I hope this helps
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
Using Laravel Spark, if I wanted to swap in a new implementation for the configureTeamForNewUser, at first it looks like it's possible because of the Spark::interact call here
#File: spark/src/Interactions/Auth/Register.php
Spark::interact(self::class.'#configureTeamForNewUser', [$request, $user]);
i.e. the framework calls configureTeamForNewUser using Spark::interact, which means I can Spark::swap it.
However, if I look at the configureTemForNewUser method itself
#File: spark/src/Interactions/Auth/Register.php
public function configureTeamForNewUser(RegisterRequest $request, $user)
{
if ($invitation = $request->invitation()) {
Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
self::$team = $invitation->team;
$invitation->delete();
} elseif (Spark::onlyTeamPlans()) {
self::$team = Spark::interact(CreateTeam::class, [
$user, ['name' => $request->team, 'slug' => $request->team_slug]
]);
}
$user->currentTeam();
}
This method assigns a value to the private $team class property. It's my understanding that if I use Spark::swap my callback is called instead of the original method. Initial tests confirm this. However, since my callback can't set $team, this means my callback would change the behavior of the system in a way that's going to break other spark functionality.
Is the above a correct understanding of the system? Or am I missing something, and it would be possible to swap in another function call (somehow calling the original configureTeamForNewUser)?
Of course, you can swap this configureTeamForNewUser method. Spark create a team for a user at the registration. You have to add the swap method inside the Booted() method of App/Providers/SparkServiceProvider.php class.
in the top use following,
use Laravel\Spark\Contracts\Interactions\Auth\Register;
use Laravel\Spark\Contracts\Http\Requests\Auth\RegisterRequest;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\CreateTeam;
use Laravel\Spark\Contracts\Interactions\Settings\Teams\AddTeamMember;
In my case I want to add new field call "custom_one" to the teams table. Inside the booted() method, swap the method as bellow.
Spark::swap('Register#configureTeamForNewUser', function(RegisterRequest $request, $user){
if ($invitation = $request->invitation()) {
Spark::interact(AddTeamMember::class, [$invitation->team, $user]);
self::$team = $invitation->team;
$invitation->delete();
} elseif (Spark::onlyTeamPlans()) {
self::$team = Spark::interact(CreateTeam::class, [ $user,
[
'name' => $request->team,
'slug' => $request->team_slug,
'custom_one' => $request->custom_one,
] ]);
}
$user->currentTeam();
});
In order to add a new custom_one field, I had to swap the TeamRepository#createmethod as well. After swapping configureTeamForNewUser method, swap the TeamRepository#create method onside the booted(),
Spark::swap('TeamRepository#create', function ($user, $data) {
$attributes = [
'owner_id' => $user->id,
'name' => $data['name'],
'custom_one' => $data['custom_one'],
'trial_ends_at' => Carbon::now()->addDays(Spark::teamTrialDays()),
];
if (Spark::teamsIdentifiedByPath()) {
$attributes['slug'] = $data['slug'];
}
return Spark::team()->forceCreate($attributes);
});
Then proceed with your registration.
See Laravel Spark documentation
I currently have a function in a project controller class that I am calling to export a specific project to a pdf. I am running into problems when I try to pass that single project page that I am pulling from. If I call function from my view and pass in a string of valid html from my export() function it will create a pdf correctly. I am just wondering how I can get it from that ctp template to my controller to be created as a pdf. Thanks.
In my ProjectsController.php
public function view($id)
{
$creator = $this->Auth->user();
$project = $this->Projects->get($id, [
'contain' => [
'Countries', 'Languages', 'Tags',
'ProjectsLanguages', 'Students'
]
]);
$languages = $this->__getLanguageReqs($id);
$tags = $this->__getTagReqs($id);
$projSupervisors = $this->__getSupervisorsProjects($id);
$this->set('locations',$this->__getLocations($id,"project"));
$this->set('projSupervisors',$projSupervisors);
if($creator['role_id'] == 2){
$this->set('is_owner',in_array($creator['id'],array_keys($projSupervisors)));
}
else{
$this->set('is_owner', false);
}
$this->set('languages',$languages);
$this->set('tags',$tags);
$this->set('project', $project);
$this->set('_serialize', ['project']);
}
public function export($id = null) {
$dompdf = new Dompdf();
$dompdf->loadHtmlFile('/projects/view/' . $id);
$dompdf->render();
$dompdf->output();
$dompdf->stream('project');
}
In my view.ctp
<button class = 'project_edit' onclick = "location.href='/projects/export/<?= h($project->id) ?>'">Export this Project</button>
Update
I got it figured out. Configured a new .ctp with the same information from my view.ctp and called an export there with the populated data in a php script at the end of my file.
You can use a plugin like cakephp-dompdf, your code will be cleaner.
I want to input data to database. I am using Laravel 5. When I clicked the submit button. I got an error like the image below. Here is controller:`
public function tambahjenissurat(Request $request)
{ $this->validate($request, [
'jenis_surat' => 'required'
]);
$jenis_surat = $request['jenis_surat'];
$jenis_surat = new JenisSurat();
$jenis_surat->jenis_surat = $jenis_surat;
$jenis_surat->save();
return redirect()->route('jenissurat');
}`
Your code is expecting a string but you are passing an object. that could be the problem. try to give different names for object and variable. Something like this should fix the problem. See the lines below EDIT sections
public function tambahjenissurat(Request $request)
{ $this->validate($request, [
'jenis_surat' => 'required'
]);
**EDIT**
$jenis_surat_var = $request['jenis_surat'];
$jenis_surat = new JenisSurat();
**EDIT**
$jenis_surat->jenis_surat = $jenis_surat_var;
$jenis_surat->save();
return redirect()->route('jenissurat');
}