How to show image using storage folder for looping data - php

My image is not displaying. I'm using Storage:: to save my image. Here how my folder looks like and php artisan storage:link has been created. I already try this code {{ asset('storage/complaint' . $c->image)}},{{ storage_path() . '/complaint' .$c->image}}and {{ url('/public/complaint' . $c->image) }} but it seems to be not working at all.
web.php
Route::get('/report-form','ComplaintController#create');
Route::post('/report-create','ComplaintController#store');
Route::get('/report-view','ComplaintController#index');
ComplaintController.php
<?php
namespace App\Http\Controllers;
use Auth;
use Validator;
use Response;
use Carbon\Carbon;
use App\Complaint;
use Illuminate\Support\Facades\Storage;
use Illuminate\Http\Request;
use Intervention\Image\ImageManagerStatic as Image;
class ComplaintController extends Controller
{
public function index(Request $request)
{
if (Auth::user()->role == 'buyer')
{
$complaint = Complaint::where('report_by',Auth::user()->id)->get();
return view('buyers.complaints.index',compact('complaint'));
}
}
public function create(Request $request)
{
return view('buyers.complaints.create');
}
public function store(Request $request)
{
if (count($request->defect_id) > 0) {
foreach($request->defect_id as $item=>$v) {
if (isset($request->image[$item])) {
$images = $request->file('image');
$image_resize = Image::make($images[$item]->getRealPath());
$image_resize->resize(900, 630);
$filename = $images[$item]->getClientOriginalName();
Storage::put($filename, $image_resize);
Storage::move($filename, 'public/complaint/' . $filename);
}
$data = array(
'defect_id' => $request->defect_id[$item],
'image' => $filename,
'description' => $request->description[$item],
'report_by' => Auth::user()->id,
'created_at' => Carbon::now()->toDateTimeString(),
'updated_at' => Carbon::now()->toDateTimeString()
);
Complaint::insert($data);
}
}
return redirect('/report-form')->with('success','Your report is submitted!');
}
create.blade.php
<div class="panel">
<form action="/report-create" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
<table class="table table-bordered">
<thead>
<tr>
<th><center>Type of Defect</center></th>
<th><center>Image</center></th>
<th><center>Description</center></th>
<th><center>Action</center></th>
</tr>
</thead>
<tbody>
<tr>
<td width="20%">
<select class="form-control" name="defect_id[]">
<option value="" selected>Choose Defect</option>
#foreach(App\Defect::all() as $defect)
<option value="{{$defect->id}}">{{$defect->name}}</option>
#endforeach
</td>
<td width="15%">
<input type="file" class="form-control-file" name="image[]">
</td>
<td width="45%">
<input type="text" class="form-control" name="description[]">
</td>
<td width="10%">
<button type="button" class="btn btn-info btn-sm" id="add-btn"><i class="glyphicon glyphicon-plus"></i></button>
</td>
</tr>
</tbody>
</table>
<center><button type="submit" class="btn btn-primary">Submit</button></center>
<br>
</form>
</div>
#section('footer')
<script>
$(document).ready(function () {
$('#add-btn').on('click',function () {
var html = '';
html += '<tr>';
html += '<td><select class="form-control" name="defect_id[]"><option value="" selected>Choose Defect</option>#foreach(App\Defect::all() as $defect)<option value="{{$defect->id}}">{{$defect->name}}</option>#endforeach</td>';
html += '<td><input type="file" class="form-control-file" name="image[]"></td>';
html += '<td><input type="text" class="form-control" name="description[]"></td>';
html += '<td><button type="button" class="btn btn-danger btn-sm" id="remove-btn"><i class="glyphicon glyphicon-minus"></i></button></td>';
html += '</tr>';
$('tbody').append(html);
})
});
$(document).on('click','#remove-btn',function () {
$(this).closest('tr').remove();
});
</script>
#stop
index.blade.php
<div class="panel-heading">
<h3 class="panel-title"><strong>List of Report</strong></h3>
</div>
<div class="panel-body">
<table class="table table-hover">
<thead>
<tr>
<th>Defect Name</th>
<th>Description</th>
<th>Image</th>
</tr>
</thead>
#foreach($complaint as $c)
<tr class="">
<td>{{$c->defect->name}}</td>
<td>{{$c->description}}</td>
<td><img src="{{ asset('storage/complaint' . $c->image)}}" class="" alt="{{$c->image}}"></td>
</tr>
#endforeach
</table>
</div>
What is my mistakes?

use Storage::url() ref link https://laravel.com/docs/8.x/filesystem#file-urls
<td><img src="{{ Storage::url('complaint/' . $c->image)}}" class="" alt="{{$c->image}}"></td>
NOTE: make sure APP_URL=http://exmaplet.test this is set

Related

Can't redirect after update data codeigniter and still in current page

Help, i cant redirect after update data, after edit the page still in current page. but when i place the redirect function after query $update, when i press edit button the page will go to redirect page and data edit form not show. How to fix this?
My Controller
is it i make a wrong if?
public function edit_anggaran($getId)
{
$id = encode_php_tags($getId);
$data_id = $this->uri->segment('4');
$this->_validasi();
if ($this->form_validation->run() == false) {
$data['title'] = "Detail Anggaran Pengajuan Proposal";
$data['detail_anggaran_proposal'] = $this->admin->get('detail_anggaran_proposal', ['id_detail_anggaran_proposal' => $data_id]);
$data['proposal'] = $this->admin->get('proposal', ['id_proposal' => $id]);
if ($this->template->load('templates/dashboard', 'proposal/edit_anggaran', $data)){
$d = array( 'nama_kebutuhan'=> $this->input->post('nama_kebutuhan'),
'harga' => $this->input->post('harga'),
'jumlah'=> $this->input->post('jumlah')
);
}
$update = $this->admin->update_detail('detail_anggaran_proposal', 'id_detail_anggaran_proposal', $data_id, $d);
redirect('proposal/anggaran/'.$id);
} else {
if ($update) {
set_pesan('data berhasil disimpan.');
redirect('proposal/anggaran/'.$id);
} else {
set_pesan('data gagal disimpan', false);
redirect('proposal/add');
}
// $input = $this->input->post(null, true);
}
}
My Model
public function update_detail($table, $pk, $id, $data)
{
$this->db->where($pk, $id);
return $this->db->update($table, $data);
}
My View
<div class="card-body">
<?= $this->session->flashdata('pesan'); ?>
<?= form_open('', [], ['id_detail_anggaran_proposal' => $detail_anggaran_proposal['id_detail_anggaran_proposal']]); ?>
<table class="table table-bordered" id="">
<thead>
<tr>
<th>Nama Kebutuhan</th>
<th>Harga</th>
<th>Jumlah</th>
<th>Total Harga</th>
</tr>
</thead>
<tbody>
<td><input value="<?= set_value('nama_kebutuhan', $detail_anggaran_proposal['nama_kebutuhan']); ?>" name="nama_kebutuhan" id="nama_kebutuhan" type="text" class="form-control" ></td>
<td><input value="<?= set_value('harga', number_format($detail_anggaran_proposal['harga'],'0',',','.')); ?>" name="harga" id="harga" type="text" class="form-control" ></td>
<td><input value="<?= set_value('jumlah', $detail_anggaran_proposal['jumlah']); ?>" name="jumlah" id="jumlah" type="text" class="form-control" ></td>
<?php $total=0; ?>
<td>Rp. <?= number_format($subtotal=$detail_anggaran_proposal['harga'] * $detail_anggaran_proposal['jumlah'],'0',',','.'); $total += $subtotal; ?> </td>
</tr>
<tr>
<td colspan="3" class="text-center"><h5><b>Total Anggaran </b></h5></td>
<td>Rp. <?= number_format($total,'0',',','.') ?></td>
</tr>
</tbody>
</table>
<div class="row form-group">
<div class="col-md-9 offset-md-3">
<button type="submit" class="btn btn-primary" style="float: right;">Simpan</button>
</div>
</div>
</div>
</div>
<?= form_close(); ?>
</div>

How to Save an array index data to database in separate row?

I have a featureds table (foreign key= product_id) that belongsto products table, Now i want to save some products id to my featured table,its give me a array reasult but i couldnot save it to database
Here is my Controller -->
public function featuredProduct(Request $request)
{
if($request->isMethod('POST')){
$product_id=$request->all();
foreach ($product_id as $product) {
$products[]=$product;
}
//dd($products);
Featured::create($products);
}
return view('admin.products.featured');
}
<form action="{{ route('featuredProduct') }}" method="POST" multiple>
<table id="datatable-responsive" class="table table-striped table-bordered dt-responsive nowrap verticle_middle">
<thead>
<tr>
<th>Product</th>
<th>Category</th>
<th>Image</th>
<th>Status</th>
</tr>
</thead>
<tbody>
#foreach ($products as $product)
<tr>
<td>
<input id="{{ $product->id }}" value="{{ $product->id }}" type="checkbox" name="product[]">
<label for=id={{ $product->id }}>{{ $product->product_name }}</label>
</td>
<td> {{ $product->category['cat_name'] }} </td>
<td> <img src="{{asset($product->pro_img) }}" alt="" width="40"> </td>
<td class="center">
#if ($product->status === 1)
<span class="btn btn-primary btn-xs">Published</span>
#else
<span class="btn btn-warning btn-xs">Unpublish</span>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
<div class="modal-footer">
<button type="button"class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-primary waves-effect waves-light">Submit</button>
</div>
</form>
You can create each feature inside the for loop.
public function featuredProduct(Request $request)
{
if($request->isMethod('POST')) {
foreach($request->all() as $productId) {
Featured::create([
'product_id' => $productId,
... other data fields.
]);
}
}
}
Or if you want to save all the features at once.
public function featuredProduct(Request $request)
{
if($request->isMethod('POST')) {
$featureds = [];
foreach($request->all() as $productId) {
$featureds[] = [
'product_id' => $productId,
... other data fields.
]
}
DB::table('featureds')->insert($featureds);
}
}

Batch Process not inserted to the table

I have following tables that used to store purchase & issue of items.
store_update_stock Table
+-----------------+----------+-------------------+-----------------+--------+
| update_stock_id | supplier | user order_status | transfer_status | status |
+-----------------+----------+-------------------+-----------------+--------+
store_update_stock_details Table
+-------------------------+-----------------+------+-----+------------+--------+
| update+stock_details_id | update_stock_id | item | qty | unit_price | status |
+-------------------------+-----------------+------+-----+------------+--------+
02) I used Codeigniter for the project and files as follows :
Controller
public function verifyItemReqFromHD()
{
$this->checkPermissions('edit', 'issueApprovedItem');
$bc = array(array('link' => '#', 'page' => 'Item Request From HD'));
$meta = array('page_title' => 'Item Request From HD', 'bc' => $bc);
$this->data['products'] = $this->Item_model->getProducts();
if ($this->form_validation->run() == true) {
$count = count($this->input->post('item'));
$items = $this->input->post('item');
$qts = $this->input->post('qty');
$up = $this->input->post('unit_price');
$total = 0;
for ($x = 0; $x < $count; $x++) {
$details[$x]['update_stock_id'] = null;
$details[$x]['item'] = $items[$x];
$details[$x]['qty'] = $qts[$x];
$details[$x]['unit_price'] = $up[$x];
$details[$x]['status'] = 1;
}
$stock = array(
'supplier' => $this->session->userdata('id_user'),
'user' => ucfirst($this->session->userdata('name')),
'order_status' => 'verifyIssue',
'transfer_status' => 'Verified',
'status' => '1'
);
if ($this->Item_model->addItemReqFromHD($stock, $details)) {
$this->session->set_flashdata('message', 'Successfully Sent Your Request..!!');
redirect('item/verifyItemReqFromHD');
}
} else {
$this->session->set_flashdata('error', validation_errors());
$this->render('item/viewItemtoIssued', $meta, $this->data);
}
}
Model
function addItemReqFromHD($data,$details)
{
$this->db->trans_start();
if ($this->db->insert('store_update_stock', $data)) {
$id = $this->db->insert_id();
foreach ($details as $detail) {
$detail['update_stock_id'] = $id;
$this->db->insert('store_update_stock_details', $detail);
}
}
$this->db->trans_complete();
if ($this->db->trans_status() === true) {
return true;
}
return false;
}
View
<?php
if(!empty($issueData)){
$common=$issueData[0];
}
?>
<script type="text/javascript">
$(document).on("change", "#item", function () {
$.ajax({
'url': '<?=site_url("item/isExistProduct/?q=")?>' + $('#item').val(),
'method': 'GET',
'success': function (data) {
var jData = JSON.parse(data);
if (jData.status == true) {
jData.data.forEach(data => {
$('#request_table').append('<tr>' +
'<td ><span id="product" >' + data.item_name + '</span>' +
'<input type="hidden" id="item[]" name="item[]" value="' + data.item_id + '">' +
'</td>' +
'<td class="text-center">' + data.qty + '</td>' +
'<td class="text-center"><input class="form-control text-right" disabled id="sales_price[]" name="sales_price[]" value="' + data.up+ '"></td>' +
'<td class="text-center"><input class="form-control text-center rquantity" data-qty-bal="' + data.qty + '" autofocus required type="number" step="any" id="qty[]" name="qty[]" ></td>' +
'<td class="text-center" ><i class="fa fa-remove remove" style="cursor: pointer"></i></td>' +
'</tr>');
})
}
},
'error': function () {
}
});
});
$(document).on("click", ".remove", function () {
$(this).closest('tr').remove();
});
var old_row_qty;
$(document).on("focus", '.rquantity', function () {
old_row_qty = $(this).val();
}).on("change", '.rquantity', function () {
var row = $(this).closest('tr');
var issue_q = parseFloat($(this).val());
var available_q = parseFloat($(this).data('qty-bal'));
if (issue_q > available_q) {
console.log("ssss");
$(row).addClass('danger');
$('#add_sale').attr('disabled', true);
alert("Can not proceed your request ..!!. Issue quantity is higher than the available quantity..");
} else {
console.log("remove");
$(row).removeClass('danger');
$('#add_sale').attr('disabled', false);
}
});
</script>
<!-- Main content -->
<section class="invoice">
<!-- title row -->
<div class="row">
<div class="col-xs-12">
</div>
<!-- /.col -->
</div>
<!-- Table row -->
<div class="row" style="margin-top: 2%">
<div class="col-xs-12 table-responsive">
<table class="table table-striped">
<thead>
<tr class="" style="background-color: #33ff99 !important;">
<th>Item</th>
<th class="text-right">Requested Qty</th>
<th class="text-right">Approved Qty</th>
</tr>
</thead>
<tbody>
<?php
if (!empty($issueData)) {
foreach ($issueData as $rows){
?>
<tr>
<td style="width: 40%"><?=$rows->item_name?></td>
<td style="width: 15%" class="text-right"><?=$rows->r_qty+0?></td>
<td style="width: 15%" class="text-right"><?=$rows->ap_qty+0?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
</div>
<!-- /.col -->
</div>
<!-- /.row -->
<form action="<?= site_url('item/verifyItemReqFromHD') ?>" method="post">
<div class="col-md-5">
<div class="form-group"><label>Select Item</label>
<select name="item" id="item" class="form-control select2" required>
<option value="">Select Item</option>
<?php
if (!empty($products)) {
foreach ($products as $row) {
?>
<option value="<?= $row->item_id ?>"><?= $row->item_name ?></option>
<?php
}
}
?>
</select>
</div>
</div>
<div class="col-md-12 column">
<div class="col-md-12">
<div class="control-group table-group">
<label class="table-label">Issue Items *</label>
<div class="controls table-controls">
<table id="request_table"
class="table items table-striped table-bordered table-condensed table-hover">
<thead>
<tr class="" style="background-color: #ff66a3 !important;">
<th class="col-md-5">Item Name</th>
<th class="text-center col-md-2">Available Qty</th>
<th class="text-center col-md-2">Unit Price</th>
<th class="text-center col-md-2">Issuing Qty</th>
</th>
<th class="col-md-2" style="width: 30px !important; text-align: center;">
<i class="fa fa-trash-o" style="opacity:0.5; filter:alpha(opacity=50);"></i>
</th>
</tr>
</thead>
<tbody></tbody>
<tfoot>
<tr id="tfoot" class="tfoot active">
<th colspan="2">Total</th>
<th class="text-right"></th>
<th class="text-center">0</th>
<th class="text-center"><i class="fa fa-trash-o"
style="opacity:0.5; filter:alpha(opacity=50);"></i>
</th>
</tr>
</tfoot>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-8"></div>
<div class="col-md-4">
<button type="submit" id="add_sale" class="btn btn-primary btn-block">Issue</button>
</div>
</div>
</form>
</section>
Desired Output
03) Then I need to insert data to the both tables using above codes.
When press "Issue" button in the view the relevant values didn't insert to the tables. What can be going wrong ? Can anyone help me ?
Try
$this->db->trans_commit()
I added the following validation to the controller.
$this->form_validation->set_rules('item', 'Item', 'required');
And also changed the following line in my view.
'<input type="hidden" id="item_id[]" name="item_id[]" value="' + data.item_id + '">' +
Solved the problem .....

Deleting selected rows from checkbox in laravel

I have a table with its data are retrieved from database here: https://imgur.com/Sv4Suo7 . My problem is, I want to delete the data that are selected in the checkboxes.
I have tried putting name="ids[]" in my checkbox, but the data is still not sent to my controller. I have read somewhere that I need to use Javascript, but I don't know how to.
Views:
<div class="box-header with-border">
<div class="box-header-tools pull-left" >
<a href="{{ url('tasks/create/')}}" class="tips text-green" title="{{ Lang::get('core.btn_create') }} ">
<i class="fa fa-plus-square-o fa-2x"></i></a>
<a href="{{ url('tasks/massDelete')}}" onclick="" class="tips text-red" title="{{ Lang::get('core.btn_remove') }}">
<i class="fa fa-trash-o fa-2x delete_all" data-toggle="confirmation" data-title="{{Lang::get('core.rusure')}}" data-content="{{ Lang::get('core.rusuredelete') }}" ></i></a>
</div>
</div>
<div class="box-body" >
<div class="table-responsive" style="min-height:300px; padding-bottom:60px; border: none !important">
<table class="table table-striped table-bordered " id="{{ $pageModule }}Table">
<thead>
<tr>
<th align="center" class="number"> No </th>
<th align="center"> <input type="checkbox" class="checkall" id="master" /></th>
<th align="center">Task</th>
<th align="center">Due Date</th>
<th align="center">Assigned To</th>
<th align="center">Assigned By</th>
<th align="center">Status</th>
<th align="center">{{ Lang::get('core.btn_action') }}</th>
</tr>
</thead>
<tbody> #foreach($tasks as $task)
<tr>
<td width="30"> {{ ++$i }} </td>
<td width="50"><input type="checkbox" class="checkbox" name="ids[]" value="{{$task->id}}" /></td>
<td>{{$task->task_name}} </td>
<td>{{$task->due_date}}</td>
#foreach($users as $user)
#if($user->id == $task->assigned_id)<td>{{$user->username}}</td>#endif
#endforeach
#foreach($users as $user)
#if($user->id == $task->assigner_id)<td>{{$user->username}}</td>#endif
#endforeach
#if($task->status == 0)<td width="90">
<span class="label label-block label-info label-sm">Ongoing</span>
</td>#endif
#if($task->status == 1)<td width="90">
<span class="label label-block label-danger label-sm">Cancelled</span>
</td>#endif
#if($task->status == 2)<td width="90">
<span class="label label-block label-success label-sm">Completed</span>
</td>#endif
<td>
#if($task->status == 0)
{!! Form::open(array('url'=>'tasks/completeStatus/'.$task->id, 'class'=>'form-horizontal')) !!}
<button type="submit" name="markcomplete" class="btn" ><i class="fa fa-check-circle-o fa-2x"></i></button>
{!! Form::close() !!}
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
<input type="hidden" name="md" value="" />
</div>
</div>
</div>
</div>
Controller:
public function massDelete(Request $request)
{
$gotids = $request->input('ids');
if($gotids){
foreach($gotids as $id){
$task = Tasks::findOrFail($id);
$task->delete();
}
}
return redirect('tasks');
}
Route:
Route::get('/tasks/massDelete/', 'TasksController#massDelete');
I wanted the data to be in controller, when I tried dd($gotids); it displays null. Hope anyone can help.
Here is the code if you want to use javascript
Route::delete('delete-multiple-category', ['as'=>'category.multiple-delete','uses'=>'CategoryController#deleteMultiple']);
public function deleteMultiple(Request $request){
$ids = $request->ids;
Category::whereIn('id',explode(",",$ids))->delete();
return response()->json(['status'=>true,'message'=>"Category deleted successfully."]);
}
blade file
<div class="container">
<h3>PHP Laravel 5.6 - How to delete multiple row with checkbox using Ajax? - HDTuto.com</h3>
#if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
#endif
<button style="margin: 5px;" class="btn btn-danger btn-xs delete-all" data-url="">Delete All</button>
<table class="table table-bordered">
<tr>
<th><input type="checkbox" id="check_all"></th>
<th>S.No.</th>
<th>Category Name</th>
<th>Category Details</th>
<th width="100px">Action</th>
</tr>
#if($categories->count())
#foreach($categories as $key => $category)
<tr id="tr_{{$category->id}}">
<td><input type="checkbox" class="checkbox" data-id="{{$category->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $category->category_name }}</td>
<td>{{ $category->category_details }}</td>
<td>
{!! Form::open(['method' => 'DELETE','route' => ['category.destroy', $category->id],'style'=>'display:inline']) !!}
{!! Form::button('Delete', ['class' => 'btn btn-danger btn-xs','data-toggle'=>'confirmation','data-placement'=>'left']) !!}
{!! Form::close() !!}
</td>
</tr>
#endforeach
#endif
</table>
<script type="text/javascript">
$(document).ready(function () {
$('#check_all').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".checkbox").prop('checked', true);
} else {
$(".checkbox").prop('checked',false);
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#check_all').prop('checked',true);
}else{
$('#check_all').prop('checked',false);
}
});
$('.delete-all').on('click', function(e) {
var idsArr = [];
$(".checkbox:checked").each(function() {
idsArr.push($(this).attr('data-id'));
});
if(idsArr.length <=0)
{
alert("Please select atleast one record to delete.");
} else {
if(confirm("Are you sure, you want to delete the selected categories?")){
var strIds = idsArr.join(",");
$.ajax({
url: "{{ route('category.multiple-delete') }}",
type: 'DELETE',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+strIds,
success: function (data) {
if (data['status']==true) {
$(".checkbox:checked").each(function() {
$(this).parents("tr").remove();
});
alert(data['message']);
} else {
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.closest('form').submit();
}
});
});
</script>

Data not fetching of current user in laravel

I am trying to get the data of current log in user but i am getting the result of all users in database. While in all views same problem is accure please help.
My code is given
My view is personal.blade.php
#extends('layouts.app')
#section('content')
<div class="container"><br>
<h1 class="text-success text-center">Profile</h1><br>
<table class="table table-bordered">
#foreach($data as $value)
<tr>
<th>Name</th>
<td>{{ $value ->tname}}</td>
</tr>
<tr>
<td>Father Name</td>
<td>{{ $value ->fname}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $value ->email}}</td>
</tr>
<tr>
<td>Official Email</td>
<td>{{ $value ->off_email}}</td>
</tr>
#endforeach
</table>
<div class="form-group">
<label>Generate Report</label>
<div class="radio form-control">
<label class="col-md-4"><input type="radio" name="status" value="conf" >Personal</label>
<label class="col-md-4"><input type="radio" name="status" value="general">Publications</label>
</div>
</div>
<button class="btn btn-info" data-toggle="collapse" data-target="#demo"> Generate PDF</button>
<button class="btn btn-info" data-toggle="collapse" data-target="#demo"> Generate CSV</button>
<button class="btn btn primary">Go to Home</button><br>
<div id="demo" class="collapse">
<h3 class="text-success text-center">Complete your publication's detail</h3><br>
<div class="col-md-offset-3 col-md-6 m-auto d-block">
<form action="pub" method="post">
<input type="hidden" name="_token" value="{{csrf_token()}}">
<div>
#endsection
My controller is EducationController.php and its code is given.
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\education;
use DB;
class EducationController extends Controller
{
public function show()
{
//
$data['data'] = DB::table('users')->get();
if(count ($data)>0){
return view('personal',$data);
}
else
{
return view('personal');
}
}
}
My route code is given here.
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/personal','EducationController#personal');
Please help me. I dont know how to use the current user in all views. I am login while in result I am getting the result of all users which is stored in database. thanks in advance.
You use a #foreach which implies you expect multiple users in your view.
If you only want to show details for the logged in user you should do:
<?php
class EducationController extends Controller
{
public function show()
{
if(\Auth::check()){
$user = \Auth::user();
return view('personal',compact('user'));
}
else
{
return view('personal');
}
}
}
And in your view:
#extends('layouts.app')
#section('content')
<div class="container"><br>
<h1 class="text-success text-center">Profile</h1><br>
<table class="table table-bordered">
#if (isset($user))
<tr>
<th>Name</th>
<td>{{ $user->tname}}</td>
</tr>
<tr>
<td>Father Name</td>
<td>{{ $user->fname}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $user->email}}</td>
</tr>
<tr>
<td>Official Email</td>
<td>{{ $user->off_email}}</td>
</tr>
#endif
</table>
// Rest of view
It is because your code is actually for getting all users. You should do it like this :
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
use App\education;
use DB;
class EducationController extends Controller
{
public function show()
{
$user = Auth::user();
return view('personal',compact('user'));
}
}
}
then in your view:
<tr>
<th>Name</th>
<td>{{ $user->tname}}</td>
</tr>
<tr>
<td>Father Name</td>
<td>{{ $user->fname}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{ $user->email}}</td>
</tr>
<tr>
<td>Official Email</td>
<td>{{ $user->off_email}}</td>
</tr>
Note that if you have multiple auth, you must specify your guard :
Auth::guard('yourguard')->user();
otherwise, your user will return a null.

Categories