Fetching and Printing data from Database in Laravel 8 - php

Hi I just started working in laravel 8 and I would like to know how to fetch data in database and print data
I have a template of a table with a search bar to see and find user in our database
Here is our controller for the table
DashboardController
<?php
namespace App\Http\Controllers;
use Auth;
use Illuminate\Http\Request;
class DashboardController extends Controller
{
public function dashboard()
{
$dashboardTitle = "Dashboard";
$isCurrent = "dashboard";
return view('dashboard.index', [
'dashboardTitle' => $dashboardTitle,
'isCurrent' => $isCurrent
]
);
}
public function profile()
{
$dashboardTitle = "Profile";
$isCurrent = "Profile";
return view('dashboard.profile', [
'dashboardTitle' => $dashboardTitle,
'isCurrent' => $isCurrent
]
);
}
public function directory()
{
$dashboardTitle = "Directory";
$isCurrent = "Directory";
return view('dashboard.directory', [
'dashboardTitle' => $dashboardTitle,
'isCurrent' => $isCurrent
]
);
}
public function journal()
{
$dashboardTitle = "Journal";
$isCurrent = "Journal";
return view('dashboard.journal', [
'dashboardTitle' => $dashboardTitle,
'isCurrent' => $isCurrent
]
);
}
public function files()
{
$dashboardTitle = "Files";
$isCurrent = "Files";
return view('dashboard.files', [
'dashboardTitle' => $dashboardTitle,
'isCurrent' => $isCurrent
]
);
}
}
Here is the view
directory
#extends('dashboard.layouts.dashboard-layout')
#push('css')
<!-- Custom styles for this page -->
<link href="{{asset('dashboards/vendor/datatables/dataTables.bootstrap4.min.css')}}" rel="stylesheet">
#endpush
#section('content')
<!-- Page Heading -->
<h1 class="h3 mb-2 text-gray-800">Tables</h1>
<p class="mb-4">DataTables is a third party plugin that is used to generate the demo table below.
For more information about DataTables, please visit the <a target="_blank"
href="https://datatables.net">official DataTables documentation</a>.</p>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-primary">DataTables Example</h6>
</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<td></td>
<td></td>
<td></td>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid -->
</div>
<!-- End of Main Content -->
</div>
<a class="scroll-to-top rounded" href="#page-top">
<i class="fas fa-angle-up"></i>
</a>
#endsection
#push('script')
<!-- Page level plugins -->
<script src="{{asset('dashboards/vendor/datatables/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('dashboards/vendor/datatables/dataTables.bootstrap4.min.js')}}"></script>
<!-- Page level custom scripts -->
<script src="{{asset('dashboards/js/demo/datatables-demo.js')}}"></script>
#endpush
Our table name is users and I want to print it in the table using a loop

Database
Add new rows in database if you haven't (position, office ...)
Controler
...
$users = User::all();
return view('dashboard.directory', [
'users' => $users
]
...
Blade
#foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->postion }}</td>
<td>{{ $user->office }}</td>
<td>{{ $user->age }}</td>
<td>{{ $user->start_date }}</td>
<td>{{ $user->salary }}</td>
</tr>
#endforeach

To retrieve all users in your db, you have to :
Dashboard Controller
public function directory(){
$dashboardTitle = "Directory";
$isCurrent = "Directory";
$users = User::all();
return view('dashboard.directory', [
'dashboardTitle' => $dashboardTitle,
'isCurrent' => $isCurrent,
'users' => $users
]);
}
In Blade
#foreach($users as $user)
<tr>
<td>{{ $user->name }}</td>
<td>{{ $user->postion }}</td>
<td>{{ $user->office }}</td>
<td>{{ $user->age }}</td>
<td>{{ $user->start_date }}</td>
<td>{{ $user->salary }}</td>
</tr>
#endforeach

Related

How to pass a Static value with search results in a Laravel Controller

I have the following method defined in my controller. I want to pass the value of $title along with the search results so that it can be displayed at the top of the blade page, but I am unsure how to do it.
public function index_sog(Request $request)
{
$title = 'Standard Operating Guideline';
return view('knowledgebase.index', [
'kbase' => Knowledgebase::orderBy('category', 'asc')
->filter(request(['tags', 'search']))
->where('type','SOG')
->paginate(20),
'search' => $request->input('search')
]);
}
My output...
<h4>{{//TITLE SHOULD GO HERE//}}</h4>
<div class="panel-container show">
<div class="panel-content">
#foreach ($kbase->groupBy('category') as $category => $group)
<table class="table">
<tr>
<th colspan="3" class="text-center bg-fusion-50"><strong>{{ $category }} <strong></th>
</tr>
#foreach ($group as $kb)
<tr>
<td>{{ $kb->title }}</td>
<td></td>
<td></td>
</tr>
#endforeach
</table>
#endforeach
</div>
</div>
ADD on return variables. And you can use on blade like {{ $title }}
> return view('knowledgebase.index', [
> 'kbase' => Knowledgebase::orderBy('category', 'asc')
> ->filter(request(['tags', 'search']))
> ->where('type','SOG')
> ->paginate(20),
> 'search' => $request->input('search'),
> 'title' => $title
> ]);
For example you can do this way:
return view('knowledgebase.index', [
'kbase' => Knowledgebase::orderBy('category', 'asc')
->filter(request(['tags', 'search']))
->where('type','SOG')
->paginate(20),
'search' => $request->input('search')
])->with('title', $title);
By adding the ->with() method to the return.
You can also put it inside the array of variables that you already have in return.
And then in your view:
<h4>{{ $title }}</h4>

Laravel 5.4 change user role

I trying make changing role in my panel admin. But when i made it my form dont sending post request. Now only working showing user role. I cant fix it becouse when i click button to switch i dont get any error and role is not changing.
I use HttpRequester when i use url /admin/change its showing this error:
MethodNotAllowedHttpException in RouteCollection.php line 233
There is my code:
View:
#extends('layouts.app')
#section('content')
<h2>Panel Admina</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Imię</th>
<th>Nazwisko </th>
<th>E-mail </th>
<th>Nr.tele </th>
<th>Użytkownik </th>
<th>Moderator </th>
<th>Admin </th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<form action="{{route('change')}}" method="post">
{{ csrf_field() }}
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->lastname }}</td>
<td>{{ $user->email }}<input type="hidden" name="email" value="{{ $user->email }}"></td>
<td>{{ $user->phonenumber }}</td>
<td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"/></td>
<td><input type="checkbox" {{ $user->hasRole('Moderator') ? 'checked' : '' }} name="role_moderator"/></td>
<td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"/></td>
<td><input type="submit" class="btn btn-default btn-sm" value="Przydziel rolę"></td>
</form>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
Controller:
public function change(Request $request)
{
$user = User::where('email', $request['email'])->first();
$user->roles()->detach();
if ($request['role_user']) {
$user->roles()->attach(Role::where('name', 'User')->first());
}
if ($request['role_moderator']) {
$user->roles()->attach(Role::where('name', 'Moderator')->first());
}
if ($request['role_admin']) {
$user->roles()->attach(Role::where('name', 'Admin')->first());
}
return redirect()->back();
}
Routing:
Route::get('/admin', [
'uses' => 'AdminController#index',
'middleware' => 'roles',
'roles' => ['Admin']
]);
Route::post('/admin/change', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
I really dont know how i can resolve my problem.
try to pass the user id to your route and your form action and instead of post make it put for example:
<form action="{{route('change', $user->id)}}" method="post">
and in your route:
Route::put('/admin/change/{id}', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
and in your controller:
public function change(Request $request, $id)

how to write php code to convert latitude longitude value to address in laravel 5.2

i am fetching values from the database and displaying it into a table using php laravel. Latitude logitude value am fetching and displaying in my table. there is another column address, so in that column i need to display the address by converting corresponding lat long value from the database. Can anyone tell how i can write the code for that?
my view blade is giving below
#extends('app')
#section('content')
</br></br></br></br></br></br></br></br>
<div class="templatemo-content-wrapper">
<div class="templatemo-content">
<ol class="breadcrumb">
<li><font color="green">Home</font></li>
<li class="active">Vehicle Report</li>
</ol>
<h1>Vehicle Report</h1>
<p></p>
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="example" class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Date</th>
<th>Time</th>
<th>Status</th>
<th>Lat/Long</th>
<th>Speed</th>
<th>Altitude</th>
<th>Odometer</th>
<th>Fuel</th>
<th>Address</th>
</tr>
</thead>
<tbody>
#foreach($devices as $device)
<tr>
<td>{{ date('Y/m/d H:i:s',($device->timestamp)) }}</td>
<td>{{ date('H:i:s',($device->timestamp)) }}</td>
<td>{{--}}{{ $device->statusCode }}--}}
#if($device->statusCode == '61715')
Stop
#elseif($device->statusCode=='62465')
Ignition_On
#elseif($device->statusCode=='61713')
Start
#elseif($device->statusCode=='61714')
InMotion
#elseif($device->statusCode=='62467')
Ignition_Off
#else
Speeding
#endif
</td>
<td>{{ round($device->latitude,5).'/'.round($device->longitude,5) }}</td>
<td>{{ $device->speed }}</td>
<td>{{ round($device->altitude) }}</td>
<td>{{ round($device->odometer) }}</td>
<td>{{ ($device->fuelLevel*100).'%' }}</td>
<td>{{ ?????????? }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</br>
</br></br></br></br>
Controller page is
class ReportController extends Controller
{
public $type = 'Device';
public function getAdd()
{
$vehicles = DB::table('device')->get();
return view('reports.vehicleDetail')->with('vehicles', $vehicles);
}
public function get(Request $request)
{
$account = Account::select('accountID')->where('accountID','=','gts')->get();
foreach ($account as $acc) {
$abc = $acc->accountID;
}
try {
$device_id = $request['deviceID'];
$from = strtotime($request['Fdate']);
$to = strtotime($request['Tdate']);
$devices=DB::table('device as b')
->join('eventdata as a', 'a.deviceID', '=', 'b.deviceID')
->where('a.deviceID', '=', $device_id)
->where('a.accountID', '=', $abc)
->where('a.creationTime', '>=', $from)
->where('a.creationTime', '<=', $to)
->select('a.accountID', 'a.deviceID', 'b.description', 'a.timestamp','a.statusCode',
'a.latitude', 'a.longitude', 'a.speedKPH as speed', 'a.heading', 'a.altitude', 'a.address', 'a.distanceKM as distance', 'a.odometerKM as odometer', 'a.IbatVolts', 'a.EbatVolts', 'a.ITempr', 'a.fuelLevel', 'a.inputState', 'a.IgnRuntime', 'GPSFixType', 'a.GPSPDOP', 'a.isTollRoad')->get();
// $devices = DB::table('eventdata')->get();
return view('reports.vehicleReport')->with('devices', $devices);
} catch (ModelNotFoundException $err) {
//Show error page
}
}
}
Thanks in advance.
You need to use Reverese Geocoding. Google maps API would be the best choice.
<?php
if(isset($_POST['latitude'])){
$lat=$_POST['latitude'];
$long=$_POST['longitude'];
$address=file_get_contents("https://maps.googleapis.com/maps/api/geocode/json?latlng=$lat,$long&key=YOUR_API_KEY");
$json_data=json_decode($address);
$full_address=$json_data->results[0]->formatted_address;
}
?>

What's the cause Undefined property: stdClass?

I don't know what this error cause. I didn't change anything in my codes. But when I go to my search view. It always returns me the undefined property error. This error cause when I tried to foreach all my columns in my table data. I already solve this error not once. Because it cannot find the $id of selected options. But this time I can't fix it.
Error:
Undefined property: stdClass::$id (View: C:\Users\JohnFrancis\LaravelFrancis\resources\views\document\show.blade.php)
View
show.blade.php - This view will list all the values in my tables.
#section ('content')
<div class = "col-md-12">
<table class = "table">
<thead>
<tr>
<th>Title</th>
<th>Content</th>
<th>Category</th>
<th>Sender</th>
<th>Date Received</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach ($documentLists as $list)
<tr class = "info">
<td>{{ $list->title }}</td>
<td>{{ strip_tags(substr($list->content, 0, 50)) }} {{ strlen($list->content) > 50 ? "..." : '' }}</td>
<td>{{ $list->category_type }}</td>
<td>{{ $list->username }}</td>
<td>{{ date('M j, Y', strtotime($list->dateReceived)) }}</td>
<td>
<button type = "submit" class = "btn btn-info">Read</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
read.blade.php - This where it will redirect to the current view that selected.
<!--DOCUMENT CONTROLLER-->
<div class = "col-md-6">
<form class = "vertical">
<div class = "form-group">
<textarea id = "content">{{ $documentLists->content }}</textarea>
</div>
<div class = "form-group">
<button type = "submit" class = "btn btn-success">Approve</button>
</div>
</form>
</div>
Controller
//SHOW
public function showDocuments()
{
$documentLists = DB::table('document_user')->select('documents.title', 'documents.content', 'categories.category_type', 'users.username', 'document_user.dateReceived')
//Table name //PK //FK
->join('users', 'users.id', '=', 'document_user.sender_id')
->join('documents', 'documents.id', '=', 'document_user.document_id')
->join('categories', 'categories.id', '=', 'documents.category_id')
->where('sender_id', '!=', Auth::id())
->where('user_id', '!=', Auth::id())->get();
//VIEW
return view ('document.show')->with('documentLists', $documentLists);
}
//READ
public function readDocuments($id)
{
//Find the document in the database and save as var.
$documentLists = Document::find($id);
return view ('document.read')->with('documentLists', $documentLists);
}
routes
Route::get('/show',
[
'uses' => '\App\Http\Controllers\DocumentController#showDocuments',
'as' => 'document.show',
'middleware' => 'auth',
]);
Route::get('/receive/documents/{id}',
[
'uses' => '\App\Http\Controllers\DocumentController#readDocuments',
'as' => 'document.read',
'middleware' => 'auth',
]);
In below you are not selecting id
$documentLists = DB::table('document_user')->select('documents.title', 'documents.
but calling in your blade {{ route ('document.read', $list->id) }}
$documentLists = DB::table('document_user')->select('documents.id','documents.title', 'documents.content', 'categories.category_type', 'users.username', 'document_user.dateReceived');
You need to select the column documents.id.But you have missed it

"Paginator could not be converted to string" when trying to sort

i am trying to create sorting and pagination list..but it dosent work good..
so i see this error in laravel
Object of class Illuminate\Pagination\Paginator could not be converted to string
and this is my code
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index() {
// CACHE SORTING INPUTS
$allowed = array('ID', 'NAME', 'EMAIL'); // add allowable columns to search on
$sort = in_array(Input::get('sort'), $allowed) ? Input::get('sort') : 'id'; // if user type in the url a column that doesnt exist app will default to id
$order = Input::get('order') === 'asc' ? 'asc' : 'desc'; // default desc
$nerds = Nerd::order_by($sort, $order);
// PAGINATION
$nerds = $nerds->paginate(5);
$pagination = $nerds->appends(
array(
'ID' => Input::get('ID'),
'NAME' => Input::get('NAME'),
'EMAIL' => Input::get('EMAIL'),
'sort' => Input::get('sort'),
'order' => Input::get('order')
))->links();
// load the view and pass the nerds
return View::make('nerds.index')->with(
array(
'nerds' => $nerds,
'pagination' => $pagination,
'querystr' => '&order=' . (Input::get('order') == 'asc' || null ? 'desc' : 'asc').$nerds
));
}
index.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Look! I'm CRUDding</title>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<nav class="navbar navbar-inverse">
<div class="navbar-header">
<a class="navbar-brand" href="{{ URL::to('nerds') }}">Nerd Alert</a>
</div>
<ul class="nav navbar-nav">
<li>View All Nerds</li>
<li>Create a Nerd
</ul>
</nav>
<h1>All the Nerds</h1>
<!-- will be used to show any messages -->
#if (Session::has('message'))
<div class="alert alert-info">{{ Session::get('message') }}</div>
#endif
<table class="table table-striped table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
<td>Nerd Level</td>
<td>Actions</td>
</tr>
</thead>
<tbody>
#foreach($nerds as $key => $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
<td>{{ $value->nerd_level }}</td>
<!-- we will also add show, edit, and delete buttons -->
<td>
<!-- delete the nerd (uses the destroy method DESTROY /nerds/{id} -->
<!-- we will add this later since its a little more complicated than the first two buttons -->
{{ Form::open(array('url' => 'nerds/' . $value->id, 'class' => 'pull-right')) }}
{{ Form::hidden('_method', 'DELETE') }}
{{ Form::submit('Delete this Nerd', array('class' => 'btn btn-warning')) }}
{{ Form::close() }}
<!-- show the nerd (uses the show method found at GET /nerds/{id} -->
<a class="btn btn-small btn-success" href="{{ URL::to('nerds/' . $value->id) }}">Show this Nerd</a>
<!-- edit this nerd (uses the edit method found at GET /nerds/{id}/edit -->
<a class="btn btn-small btn-info" href="{{ URL::to('nerds/' . $value->id . '/edit') }}">Edit this Nerd</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $nerds->links() }}
</div>
</body>
</html>
Try with View Composer. Store the below in your routes file or whatever.
View::composer(Paginator::getViewName(), function($view) {
$queryString = array_except(Input::query(), Paginator::getPageName());
$view->paginator->appends($queryString);
});
This will automatically add query strings to your pagination links in all pagination. You dont have to append it in all your controllers.
In your view file, you just have to call {{ $nerds->links() }}
UPDATE
Problem is with this line: 'querystr' => '&order=' . (Input::get('order') == 'asc' || null ? 'desc' : 'asc').$nerds
You are appending an object $nerds to a string. i.e $querystr

Categories