How we can display data from array on blade page - laravel

I have written this code
app\Http\Controller\processController.php
class ProcessController extends BaseController {
public function getData()
{
$data['data']=DB::table('process_table')->get();
if(count($data) > 0)
{
return view('process',$data);
}
else
{
return view('process');
}
} }
route\web.php
Route::get('/process', 'processController#getData');
resources\views\process.blade.php
What should i write here in blade file and how to print $data values in table format ??

The key values of your array are the names of the variables you can use in your view. So, in your case $data will contain all rows from the table process_table.
To make sure that the variable exists, you can use the isset function.
Now you can do this for example:
#if (isset($data))
<ul>
#foreach ($data as $row)
<li>{{ $row->name }}</li>
#endforeach
</ul>
#endif

you can simply dump it
#if (isset($data))
{{{ json_encode($data) }}}
#endif

You should try this:
app\Http\Controller\processController.php
class ProcessController extends BaseController {
public function getData()
{
$data['data']=DB::table('process_table')->get();
if(count($data) > 0)
{
return view('process',compact('data'));
}
else
{
return view('process');
}
}
}
resources\views\process.blade.php
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h1 style="color: purple;"><center><b>Process Data</b></center></h1>
<hr>
#if(isset($data))
<div class="tab-content">
<div role="tabpanel" class="tab-pane tab-margin table-area-margin active" id="profile">
<div class="table-responsive">
<table class="table payment-info-tbl">
<tr class="displaying-passages-title">
<th>Your Field</th>
</tr>
#foreach ($data as $datas)
<tr>
<td>{{$datas->yourField}}</td>
</tr>
#endforeach
</table>
</div>
</div><!--tab panel profile-->
</div><!--tab content-->
#else
<h1>No Data</h1>
#endif
</div>
</div>

you lookin for this:
#if (isset($data))
<table>
#foreach ($data as $key => $row)
<tr>
<td>{{ $key }}</td>
<td>{{ (is_array($row)) ? json_encode($row) : $row }}</td>
</tr>
#endforeach
</table>
#endif

Related

Laravel Livewire strange table rendering behavior

I have a table component in my page that renders a list of users, and one of the columns in the table is the user's role. when I paginate through the table of users, livewire is randomly inserting a row in the table for the role, like it's somehow getting confused and including the relationship in the loop, instead of just the main model.
This is the result after paginating:
Here's what it's doing to the markup:
It only happens the first time the page is loaded and I click one of the pagination buttons. It will randomly happen on one or more pages as I paginate through the table, but once I reach the end, I can paginate through every page any number of times without seeing it again until I refresh the page.
Here is my User model:
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable, SoftDeletes, CanResetPassword, HasFactory;
protected $with = ['role'];
public function role()
{
return $this->belongsTo(Role::class);
}
}
Here's my Role model:
class Role extends Model
{
use HasFactory, SoftDeletes;
public function user()
{
return $this->hasOne(User::class);
}
}
My Livewire UserListComponent, which is a full-page component:
class UserListComponent extends Component
{
use WithPagination;
public $search;
public $roles;
public $user;
protected $paginationTheme = 'bootstrap';
protected $listeners = ['refreshUsers' => '$refresh'];
public function mount()
{
$this->search = '';
}
public function render()
{
return view('livewire.users.index', [
'users' => User::withTrashed()->search(['first_name', 'last_name'], $this->search)->paginate(5)
]);
}
public function show($id)
{
return redirect()->route('users.edit', ['user' => $id]);
}
}
My blade view:
<x-table search="true">
#slot('head')
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Role</th>
<th>Status</th>
#endslot
#slot('body')
#forelse($users as $user)
<x-table.row id="{{ $user->id }}" includeStatus="true" :status="$user->deleted_at">
<td>{{ $user->id }}</td>
<td>{{ $user->first_name }}</td>
<td>{{ $user->last_name }}</td>
<td>{{ $user->email }}</td>
<td>{{ $user->role->name }}</td>
</x-table.row>
#empty
<x-table.empty-row colSpan="6" />
#endforelse
#endslot
#slot('paginationLinks')
{{ $users->links() }}
#endslot
</x-table>
And here's the table component content:
#props(['search' => false, 'paginationLinks' => false])
<div class="table-responsive">
<div class="d-flex flex-row justify-content-between">
<div class="col-md-3"></div>
<div class="col-md-2">
#if ($search)
<input wire:model="search" placeholder="Search" type="text" class="form-control">
#endif
</div>
</div>
<table class="table">
<thead>
<tr>
{{ $head }}
</tr>
</thead>
<tbody>
{{ $body }}
</tbody>
</table>
<div class="mt-4">
#if ($paginationLinks)
{{ $paginationLinks }}
#endif
</div>
</div>
And the table row component:
#props(['includeStatus' => false, 'status' => false, 'id'])
<tr wire:key="{{ $id }}" wire:loading.class.delay="opacity-50" wire:target="search" wire:click="show({{ $id }})">
{{ $slot }}
#if ($includeStatus)
<td>
#if ($status)
<span class=" ms-2 badge bg-danger">Inactive</span>
#else
<span class="ms-2 badge bg-success">Active</span>
#endif
</td>
#endif
</tr>

Laravel Error Whoops, looks like something went wrong. 2/2 ErrorException in path/storage/framework/views/44812f12bcefe0281da2f29a7f94d872 line 40

I got an error as follow and I don't understand it. Is that a session issue.
2/2 Whoops, looks like something went wrong.
ErrorException in /path-to-app/storage/framework/views/44812f12bcefe0281da2f29a7f94d872 line 40:
Trying to get property of non-object (View: /path-to-app/resources/views/backend/base/clients/companies/peoples/index_all.blade.php)
1/2
ErrorException in 44812f12bcefe0281da2f29a7f94d872 line 40:
Trying to get property of non-object
this is the view index_all.blade.php:
#extends('backend/base/layouts/default')
#section('title')
Clients Management
#stop
#section('header')
<link href="{{ asset('assets/plugins/forms/togglebutton/toggle-buttons.css') }}" type="text/css" rel="stylesheet" />
#stop
#section('content')
{{ Company::filterForm() }}</div>
<div class="col-lg-12">
<div class="page-header">
<h3>All People
<span class="icon16 iconic-icon-plus"></span>
</h3>
</div>
<div class="row">
<div class="col-lg-12">
<table cellpadding="0" cellspacing="0" border="0" class="dynamicTable display table dataTable">
<thead>
<tr>
<th>Full name</th>
<th>e-mail</th>
<th>Phone Number</th>
<th>Company</th>
<th>Country</th>
<th>City</th>
<th>Industry</th>
<th>Products</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach($companies as $company)
#foreach($company->peoples as $people)
<tr>
<td>{{ $people->fullName }}</td>
<td>{{ $people->email1 }}</td>
<td>{{ $people->landline }}</td>
<td>{{ $company->name }}</td>
<td>{{ $company->country->name }}</td>
<td>{{ $company->city }}</td>
<td>
#foreach($company->industries as $industry)
{{ $industry->title }}
#endforeach
</td>
<td>{{ $company->tags }}</td>
<td>
<div class="left marginR10">
<div class="iToggle-button"><input type="checkbox" class="nostyle"
#if($people->User)
#if( !$people->User->isActivated() )
onchange="window.location.replace('/admin/users/{{encrypt($people->User->id)}}/activate');"
#else
checked="checked"
#if(!$people->User->isCurrent())
onchange="window.location.replace('/admin/users/{{encrypt($people->User->id)}}/deactivate');"
#else
disabled
#endif
#endif
#else
disabled
#endif
>
</div>
</div>
</td>
<td>
<a title="Update" class="tip" href="{{ URL::route('clients.companies.peoples.update', array($company->id, $people->id)) }}"><span class="icon16 typ-icon-pencil"></span></a>
#if(Sentry::getUser()->hasAccess('contacts'))
<a title="Delete" href="{{ URL::route('clients.companies.peoples.delete', array($company->id, $people->id)) }}"><span class="icon16 typ-icon-cross"></span></a>
#endif
</td>
</tr>
#endforeach
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#stop
#section('footer_script')
<script type="text/javascript" src="{{ asset('assets/plugins/forms/togglebutton/jquery.toggle.buttons.js') }}"></script>
#stop
#section('footer')
<script type="text/javascript">
$('.iToggle-button').toggleButtons({
width: 70,
label: {
enabled: "<span class='icon16 icomoon-icon-checkmark white'></span>",
disabled: "<span class='icon16 icomoon-icon-close white marginL10'></span>"
}
});
function toggleButtons () {
$('.iToggle-button').toggleButtons({
width: 70,
label: {
enabled: "<span class='icon16 icomoon-icon-checkmark white'></span>",
disabled: "<span class='icon16 icomoon-icon-close white marginL10'></span>"
}
});
}
</script>
#stop
and this is the index of the controller
namespace Controllers\Admin\Clients;
use BackendController;
use People;
use Redirect;
use Company;
use Config;
use Input;
use Activity;
use Todo;
use Sentry;
use Breadcrumbs;
use Email;
use EMailTemplate;
use Token;
use Lang;
use URL;
use Response;
use Validator;
use Session;
class PeoplesController extends BackendController {
public function __construct(){
parent::__construct();
if(Sentry::check() && !(Sentry::getUser()->hasAccess('contacts.peoples') || Sentry::getUser()->hasAccess('contacts'))){
throw new \PermissionDeniedException();
}
}
/**
* Display a listing of the resource.
*
* #return Response
*/
public function getIndex($id = null)
{
if($id == null)
{
$companies = Company::hasPermission(array('c', 'r', 'u', 'd'), Sentry::getUser()->id, false)->with('peoples', 'country', 'industries')->filter()->get();
Breadcrumbs::register('clients.peoples', function($b){
$b->parent('cp');
$b->push('Clients');
$b->push('Companies', route('clients.companies'));
$b->push('Peoples');
});
self::$breadcrumbs = Breadcrumbs::render('clients.peoples');
return self::view('clients/companies/peoples/index_all')
->with('companies', $companies);
}
else
{
$company = Company::hasPermission(array('c', 'r', 'u', 'd'), Sentry::getUser()->id, false)->with('peoples', 'country', 'industries')->filter()->find($id);
Breadcrumbs::register('clients.peoples', function($b, $company){
$b->parent('cp'); // # we can actuall inherit this class from CompaniesController to make it easier and more structural.
$b->push('Clients');
$b->push('Companies', route('clients.companies'));
$b->push($company->name, route('clients.companies.show', $company->id));
$b->push('Peoples');
});
self::$breadcrumbs = Breadcrumbs::render('clients.peoples', $company);
return self::view('clients/companies/peoples/index')
->with('company', $company);
}
}

How to get data from a related table in laravel

I am trying to get data of an animal through a relationship with the user table
Here is my controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use App\Clinic;
use App\Role;
use App\Slaughter;
use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ClinicController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$farms = User::where('role_id', 3)->get();
$user = Auth::user();
$animal = Animal::all();
return view('clinic.index', compact('user', 'animal', 'farms'));
}
public function show($id)
{
$farm = User::query()->findOrFail($id);
return view('clinic.show', compact('farm'));
}
While getting the user which is Farm in my case, I would like to get the animals the farm admin registered through this relationship
Model
class Clinic extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
}
From My tinker, the relationship is working perfectly
Here comes my index page
#extends('layouts.app')
#section('content')
<br><br><br><br><br><br>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-20">
<div class="card">
<div class="card-header">
<center>
<h1>Clinic Dashboard</h1>
</center>
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<center>
<h2>Welcome! <strong>{{ Auth::user()->name }}</strong></h2>
</center>
<hr>
<br>
<div class="container box">
<div class="table-responsive">
<table class="table table-striped table-bordered" style="background: white">
<thead>
<tr>
<th>Farm Id</th>
<th>Farm Name</th>
<th>Action</th>
</tr>
</thead>
#foreach( $farms as $farm)
<tbody>
<tr>
<td>{{ $farm->id }}</td>
<td>{{ $farm->name }}</td>
<td><a href="/clinic/{{ $farm->id }}"><button
class="btn btn-outline-primary">View Farm
Animals</button></a></td>
</tr>
</tbody>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
And my route
Route::get('/clinic/{farm}', 'ClinicController#show');
And finally the show view where I am getting all the errors
#extends('layouts.app')
#section('content')
<br><br><br><br><br><br>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-20">
<div class="card">
<div class="card-header">
<center>
<h1>Farm Dashboard</h1>
</center>
</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<center>
<h2>Welcome! <strong>{{ Auth::user()->name }}</strong></h2>
</center>
<hr>
<br>
<div class="container box">
<div class="table-responsive">
<table class="table table-striped table-bordered" style="background: white">
<thead>
<tr>
<th>Id</th>
<th>Animal Type</th>
<th>Sex</th>
<th>Farm</th>
<th>Clinic</th>
<th>Vaccination</th>
<th>Nutrition</th>
</tr>
</thead>
#foreach( $farm as $farm)
<tbody>
<tr>
<td>{{ $farm->animals->id }}</td>
<td>{{ $farm->animals->type->category }}</td>
<td>{{ $farm->animals->gender }}</td>
<td>{{ $farm->animals->user->name }}</td>
#if(! $farm->animals->clinic)
<td>N/A</td>
<td>N/A</td>
<td>N/A</td>
<td>
<a href="/clinic/{{ $farm->animals->id }}/create">
<button type="button" class="btn btn-primary">
Attach Clinic Detail
</button>
</a>
</td>
#elseif( $farm->animals->clinic)
<td>{{ $farm->animals->clinic->user->name }}</td>
<td>{{ $farm->animals->clinic->vaccination ?? 'N/A' }}</td>
<td>{{ $farm->animals->clinic->nutrition ?? 'N/A'}}</td>
<td>
<a
href="/clinic/{{ $farm->animals->clinic->id }}/edit">
<button type="button"
class="btn btn-primary">Edit Animal
Clinic details</button>
</a>
</td>
#endif
</tr>
</tbody>
#endforeach
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
I hope I have provided all the fields that could be generating errors. Any assist will be kindly taken as it is a very important project for me
The error I am getting is
Trying to get property 'animals' of non-object
this setup allows you to get all the animals of all the users of a specific clinic. I leveraged route/model binding on your show() method too. Whatever ID you pass in the URL it will automatically load the clinic up.
// app/User.php
class User extends Autheticatable
{
public function animals()
{
return $this->hasMany('App\Animal');
}
public function clinic()
{
return $this->belongsTo('App\Clinic');
}
}
// app/Clinic.php
class Clinic extends Model
{
public function users()
{
return $this->hasMany('App\User');
}
}
// app/Animal.php
class Animal extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
class ClinicController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function show(Clinic $clinic)
{
return view('clinic.show', compact('clinic'));
}
}
// view
#foreach($clinic->users as $farm)
#foreach($farm->animals as $animal)
{{ $animal->name }} - {{ $animal->weight }} etc...
#endforeach
#endforeach
In your view you have #foreach($farm as $farm)
What you need: #foreach($farms as $farm)
Edit: this only addresses part of the issue, upon closer inspection your relationships are out of whack, I'll see if I can whip something up.
To get the related Animals for the $farm I would go
public function show($id)
{
$farm = User::with(['animals'])->findOrFail($id);
return view('clinic.show', compact('farm'));
}
Then in your blade
#foreach($farm->animals as $animal)
{{ $animal->id }}
#endforeach
This is assuming you have your animal relation set in your user model of course which would be something like
public function animals()
{
return $this->hasMany('App\Animals')
}
(All untested)

Laravel 5 : Undefined variable: post

in my view, I got an error, Undefined variable: post (View: /Applications/MAMP/htdocs/night-copy/resources/views/posts/index.blade.php).
I don't know why it happens. Please help me out.
I am creating a CRUD dashboard for admin side.
I will paste some of my codes, so if you need more codes, please ask me.
PostsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Posts\CreatePostsRequest;
use App\Http\Requests\Posts\UpdatePostRequest;
use App\Post;
class PostsController extends Controller
{
public function index()
{
return view('posts.index')->with('posts', Post::all());
}
public function create()
{
return view('posts.create');
}
public function store(CreatePostsRequest $request)
{
//upload the image to strage
//dd($request->image->store('posts'));
$image = $request->image->store('posts');
//create the posts
Post::create([
'image' => $image,
'title' => $request->title,
'place' => $request->place,
'map' => $request->map,
'date' => $request->date,
'tag' => $request->tag,
'description' => $request->description
]);
//flash message
session()->flash('success', 'Post created successfully.');
//resirect user
return redirect(route('posts.index'));
}
public function show($id)
{
//
}
public function edit(Post $post)
{
return view('posts.create')->with('post', $post);
}
public function update(UpdatePostRequest $request, Post $post)
{
$data = $request->only(['title', 'place', 'map', 'date', 'published_at', 'tag', 'description']);
//check if new image
if($request->hasFile('image')){
//upload it
$image = $request->image->store('posts');
//delete old image
$post->deleteImage();
$data['image'] = $image;
}
//update attributes
$post->update($data);
//flash message
session()->flash('success', 'Post updated sucessfully.');
//redirect user
return redirect(route('posts.index'));
}
public function destroy($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
if($post->trashed()) {
$post->deleteImage();
$post->forceDelete();
} else {
$post->delete();
}
session()->flash('success', 'Post deleted successfully.');
return redirect(route('posts.index'));
}
public function trashed()
{
$trashed = Post::onlyTrashed()->get();
return view('posts.index')->with('posts', $trashed);
}
public function restore($id)
{
$post = Post::withTrashed()->where('id', $id)->firstOrFail();
$post->restore();
session()->flash('success', 'Post restore successfully.');
return redirect()->back();
}
}
index.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://use.fontawesome.com/releases/v5.6.1/css/all.css" rel="stylesheet">
<link rel="stylesheet" href="{{ asset('/css/main-posts.css') }}">
<title>Event Confirmation</title>
</head>
<body>
<div class="container">
<div class="header">
<h2 class="logo">Dark Code</h2>
<input type="checkbox" id="chk">
<label for="chk" class="show-menu-btn">
<i class="fas fa-bars" style="color: white;"></i>
</label>
<ul class="menu">
<div class="menu-list">
<i class="fa fa-home" ></i>
Dashboard
Post
Category
Suspended
Logout
<label for="chk" class="hide-menu-btn">
<i class="fas fa-times" style="color: white;"></i>
</label>
</div>
</ul>
</div>
<div class="content">
<div class="userinfo">
<div class="content">
#if($posts->count() > 0)
<table class="table">
<thead>
<th>ID</th>
<th>Title</th>
<th>Location</th>
<th>Map</th>
<th>Date</th>
<th>Tags</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr></tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->place }}</td>
<td>{{ $post->map }}</td>
<td>{{ $post->date }}</td>
<td>{{ $post->tag }}</td>
#if($post->trashed())
<form action="{{ route('restore-posts', $post->id) }}" method="POST">
#csrf
#method('PUT')
<button class="save-btn" type="submit">Restore</button>
</form>
<br>
#else
<button btn="" class="edit-btn">
Edit
</button><br>
#endif
</td>
<td>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-btn" >
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button><br>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 style="margin: 15rem; color: white;">No Posts Yet</h3>
#endif
</div>
</div>
</div>
</div>
#if($post->trashed())
#else
<button btn="" class="add-btn">Add</button>
#endif
<div class="footer">
</div>
</body>
</html>
web.php
Route::resource('posts', 'PostsController');
Route::get('trashed-posts', 'PostsController#trashed')->name('trashed-posts.index');
Route::PUT('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
In your view, you're calling #if($post->trashed()) outside of #endforeach block so the $post is outside the scope by then and hence undefined variable.
Besides the #if statement there is redundant, you want the user to be able to create a new post regardless whether a specific post is trashed or not
<div class="content">
<div class="userinfo">
<div class="content">
#if($posts->count() > 0)
<table class="table">
<thead>
<th>ID</th>
<th>Title</th>
<th>Location</th>
<th>Map</th>
<th>Date</th>
<th>Tags</th>
</thead>
<tbody>
#foreach($posts as $post)
<tr></tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
<td>{{ $post->place }}</td>
<td>{{ $post->map }}</td>
<td>{{ $post->date }}</td>
<td>{{ $post->tag }}</td>
#if($post->trashed())
<form action="{{ route('restore-posts', $post->id) }}" method="POST">
#csrf
#method('PUT')
<button class="save-btn" type="submit">Restore</button>
</form>
<br>
#else
<button btn="" class="edit-btn">
Edit
</button><br>
#endif
</td>
<td>
<form action="{{ route('posts.destroy', $post->id) }}" method="POST">
#csrf
#method('DELETE')
<button type="submit" class="delete-btn">
{{ $post->trashed() ? 'Delete' : 'Trash' }}
</button><br>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
#else
<h3 style="margin: 15rem; color: white;">No Posts Yet</h3>
#endif
</div>
</div>
</div>
</div>
<button btn="" class="add-btn">Add</button>
In your view file Check this line #if($post->trashed()). this is outside of foreach loop. comment this line out or remove it

Error "Trying to get property 'pertanyaan' of non-object" on Dompdf Laravel 5.8

I have a view and I want to have a link that downloads a PDF.
View
<div class="col-lg-12 col-xs-12">
<div class="box">
Download PDF
<div class="box-header">
<div style="text-align:center"><h3 class="box-title">PEMELIHARAAN DAN PERAWATAN ALAT UJI </h3></div>
<div style="text-align:center">Jln. Kabupaten Sragen</div>
</div>
<p> Laporan : {{ $pemeliharaan->status }} </p>
<p> Tanggal : {{ $pemeliharaan->created_at }} </p>
<p> Jenis Alat : {{ $pemeliharaan->alat->nama_alat }} </p>
<p> User : {{ $pemeliharaan->user->name }} </p>
<div class="box">
<div class="box-header">
<h3 class="box-title"></h3>
</div>
<div class="box-body no-padding">
<table class="table table-condensed">
<tbody>
<tr>
<th style="width: 10px">#</th>
<th>Pertanyaan</th>
<th>Hasil</th>
</tr>
<tr>
<td>1.</td>
<td>{{ $pemeliharaan->pertanyaan['question1'] }}</td>
<td>{{ $pemeliharaan->pertanyaan['answer1'] }}</td>
</tr>
<tr>
<td>2.</td>
<td>{{ $pemeliharaan->pertanyaan['question2'] }}</td>
<td>{{ $pemeliharaan->pertanyaan['answer2'] }}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
The link 'download' has an error.
Just Showing 404
Controller
public function showQuestion(Request $request, $id)
{
$pemeliharaan = Pemeliharaan::findOrFail($id);
$pemeliharaan->pertanyaan = json_decode($pemeliharaan->pertanyaan, true);
if ($request->has('download')) {
$pdf = PDF::loadView('users.view_question', $pemeliharaan);
return $pdf->download('view_question.pdf');
}
return view('users.view_question', compact('pemeliharaan'));
}
Routes
Route::get('/user/show/question/pdf/{id}','userController#showQuestion')->name('pdf');
Route::get('user/show/question/{id}', 'userController#showQuestion')->name('usershowQuestion');
Can someone help me with the code for the download?
You are not supplying the id route parameter to the named route 'pdf'. That's causing the line $pemeliharaan = Pemeliharaan::find($id) to yield null and later an error.
Try this:
{{ route('pdf', [ $id ] }}
In order for it to work you must supply the variable $id to the view. You can do that something like
return view('your-view')->with([
"id" => $id
]);

Resources