Laravel Variable Not Passing Through - php

I'm an absolute beginner and I'm trying to do a CRUD in Laravel, but I can not figure it out why my variables aren't being passed over to the view so I can have a dynamic display of them in the table.
My "routes" work fine.
Then my controller
public function getHome()
{
$results = Crud::index();
return view('pages/home', ['results' => $results]);
}
Calls my "Crud" model
class Crud extends Model
{
public static function index()
{
return $results = DB::table('data')
->whereNotNull('id')
->get();
}
}
And goes to my view as seen in the controller
#extends('main')
#section('title', '| Home')
#section('content')
<div class="container">
#include ('partials/_jumbotron')
<table class="table table-inverse">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody>
#if(!empty($results))
#foreach($results as $result)
<tr>
<td scope="row">$result->$id</th>
<td>$result->$first_name</td>
<td>$result->$last_name</td>
<td>$result->$username</td>
</tr>
#endforeach
#endif
</tbody>
</table>
</div>
#endsection
Thanks for the help in advance...I'm losing my mind
And sorry If I wasn't specific enough..
Edit1: I did as you say, but I'm still not outputing data to my table? Is there anything else wrong in the stated code or is the bug somewhere deeper?
Edit2: Thanks everyone for the pointed out mistakes - blade {{ }} and object properties
$object->propertie not $object->$propertie
When I fixed those mistakes which were obviously denying the output I remembered that I have an empty database.. Case Closed - Thanks everyone for the help

You're not printing the variables. You're printing literals.
If you want to print the variables (echo them) in blade files, you need to wrap them in curly brackets. Also there's not $ when you want to display an object attribute. Like that:
#foreach($results as $result)
<tr>
<td scope="row">{{ $result->id }}</th>
<td>{{ $result->first_name }}</td>
<td>{{ $result->last_name }}</td>
<td>{{ $result->username }}</td>
</tr>
#endforeach

I am a beginner too, I thought maybe you might want to try this as well
public function getHome()
{
$results = Crud::index();
return view('pages/home', compact('results'));
}
But before anything else make sure if your code is actually returning your data from DB using
dd($results)

The first of all cleaner will be using laravel with function for example
return view('pages/home')->with('results', $results);
Next you try to get $result->$first_name it didint working becouse first_name is not variable, laravel return object so you can get first_name like that:
{{$result->first_name}}

Related

Attempt to read property "Nombre" on bool

I'm trying to make a show view with Laravel 8 but i can't show the detail, this is the code from the controller:
public function show($id)
{
$accesorios=DB::table('accesorio as acc')
->join('detalle_aparato as da','acc.idAccesorio','=','da.idAccesorio')
->select('acc.Nombre')
->where('da.idAparato','=',$id);
return view("almacen.aparato.show",["accesorio"=>Accesorio::findOrFail($id)]);
}
And this is the code from the view:
#foreach ($accesorio as $acc)
<tr>
<td>{{ $acc->Nombre}}</td>
</tr>
#endforeach
Error message
When I use:
#foreach ($accesorio as $acc)
<tr>
<td>{{ $acc}}</td>
</tr>
#endforeach
It prints: 1 for each record
Hope you can help me
In you're controller you're using DB::Table to set the $accesorios variable, but never using it.
You then are setting accesorio in your view to Accesorio::findOrFail($id) which will only return one instance of the object.
Either pass $accessorios into your view
return view("almacen.aparato.show",["accesorios"=>$accessorios]);
then loop through it
#foreach ($accesorios as $acc)
<tr>
<td>{{ $acc->Nombre}}</td>
</tr>
#endforeach
or since you're just sending one instance of the object to the view, remove the loop and you can render it like this.
<tr>
<td>{{ $accesorio->Nombre }}</td>
</tr>

Fetching data from Database in Laravel

I want to fetch data from database table named 'users' and display the output in a table.
I have written below code but it's not working.
I am using Laravel 5.5
#extends('layouts.app')
#section('content')
<div class="container">
<h2>Admin Panel</h2>
<p>Data of the Registered Users.</p>
<table class="table table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
</tr>
</thead>
<tbody>
$users = DB::table('users')->select('id','name','email')->get();
#foreach($users as $value)
<tr>
<td>{{ $value->id }}</td>
<td>{{ $value->name }}</td>
<td>{{ $value->email }}</td>
</tr>
#endforeach
</tbody>
</table>
</div>
#endsection
Error: Undefined Variable: users
The problem is that you're trying to mix PHP within your (Blade) template. Although it is possible to do so with #php directives, this is bad practice: your view should not contain any business logic.
Ideally you want to pass this data from your controller. It should look something like this:
use Illuminate\Support\Facades\DB;
class UserController extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
return view('some-view')->with('users', $users);
}
}
Read more on passing data to views here.
You are doing it all wrong, the point of MVC design is to have your controllers do the application logic, your views to represent a representation of that data and models to contain the data you need, in your case you are missing the point completely by using DB::table inside of your view, so here is an example code which you might need to correct a bit:
The example below doesn't show MVC pattern since the data is passed from inside a closure of a route
web.php
Route::get('/', function () {
$users = DB::table('users')->select('id','name','email')->get();
return view('VIEW-NAME-HERE', compact('users'));
});
view.blade.php
#foreach($users as $user)
{{ $user->id }} {{ $user->name }} {{ $user->email }}
#endforeach
Change VIEW-NAME-HERE with the name of your view file, for example index or users.index
You Are using php in blade file
first make controller
for controller run a command in terminal
php artisan make:controller usercontroller
then write this:
class usercontroller extends Controller
{
public function index()
{
$users = DB::table('users')->select('id','name','email')->get();
$data = compact('users')
return view('your-view-name')->with('$data');
}
}

How to get data from database to view page in laravel?

I am using Laravel 5.4 and I want to view my data in database from my view page (listpetani.blade.php).
Here is the code of my project:
HTML:
<div class="table-responsive">
<table class="table table-striped table-hover table-condensed">
<thead>
<tr>
<th><strong>No</strong></th>
<th><strong>Nama Petani</strong></th>
<th><strong>Alamat</strong></th>
<th><strong>No. Handphone</strong></th>
<th><strong>Lokasi</strong></th>
</tr>
</thead>
<tbody>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</tbody>
</table>
</div>
PHP:
In my listpetani.blade.php I have an empty table and I want to show data from database tbl_user:
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
});
And the table in my page: view in browser
I want to show all the data from database into my view in laravel 5.4. Can anybody help me?
[SOLVE]
Thank you guys, I already solve this problem
This is the solved code
web.php (routes)
Route::get('listpetani', function () {
$petani = DB::table('tbl_user')->get();
return view('listpetani', ['petani' => $petani]);
});
and in my listpetani.blade.php
#foreach($petani as $key => $data)
<tr>
<th>{{$data->id_user}}</th>
<th>{{$data->nama_user}}</th>
<th>{{$data->alamat}}</th>
<th>{{$data->no_telp}}</th>
<th>{{$data->id_lokasi}}</th>
</tr>
#endforeach
You can get data from database in view also
#php( $contacts = \App\Contact::all() )
#php( $owners = \App\User::all())
<select class="form-control" name="owner_name" id="owner_name">
#foreach($contacts as $contact)
<option value="{{ $contact->contact_owner_id }}">{{ $contact->contact_owner }}</option>
#endforeach
</select>
It would be better if you pass data from controller to view.
return view('greetings', ['name' => 'Victoria']);
Checkout the docs:
https://laravel.com/docs/8.x/views#passing-data-to-views
Alternatively you can use #forelse loop inside laravel blade
#forelse($name as $data)
<tr>
<th>{{ $data->id}}</th>
<th>{{ $data->name}}</th>
<th>{{ $data->age}}</th>
<th>{{ $data->address}}</th>
</tr>
#empty
<tr><td colspan="4">No record found</td></tr>
#endforelse
In your controller:
$select = DB::select('select * from student');
return view ('index')->with('name',$select);
In Your view:
#foreach($name as $data)
<tr>
<th>{{ $data->id}}</th> <br>
<th>{{ $data->name}}</th> <br>
<th>{{ $data->age}}</th> <br>
<th>{{ $data->address}}</th>
</tr>
#endforeach
I hope this can help you.
#foreach($petani as $p)
<tr>
<td>{{ $p['id_user'] }}</td>
<td>{{ $p['username'] }}</td>
<td>{{ $p['alamat'] }}</td>
<td>{{ $p['no_telp'] }}</td>
<td>{{ $p['id_lokasi'] }}</td>
</tr>
#endforeach
**In side controller you pass this **:
$petanidetail = DB::table('tb1_user')->get()->toArray();
return view('listpetani', compact('petanidetail'));
and Inside view you use petanidetail variable as follow:
foreach($petanidetail as $data)
{
echo $data;
}
I hope you already know this, but try use Model and Controller as well,
Let the route take the request, and pass it to controller
and use Eloquent so your code can be this short:
$petani = PetaniModel::all();
return view('listpetani', compact('petani));
and instead using foreach, use forelse with #empty statement incase your 'listpetani' is empty and give some information to the view like 'The List is Empty'.
Try this:
$petani = DB::table('tbl_user')->pluck('id_user', 'username', 'alamat', 'no_telp', 'id_lokasi');
return view('listpetani', ['petani' => $petani]);
on your view iterate $petani using foreach() like:
foreach($petani as $data)
{
echo $data->id_user; // $petani is a Std Class Object here
echo $data->username;
}
Other answers are correct, I just want to add one more thing, if your database field has html tags then system will print html tags like < p > for paragraph tag. To remove this issue you can use below solution:
You may need to apply html_entity_decode to your data.
This works fine for Laravel 4
{{html_entity_decode($post->body)}}
For Laravel 5 you may need to use this instead
{!!html_entity_decode($post->body)!!}

Laravel - paginated model sort link in blade view

In laravel 5.2 I have a paginated table of a model.
#CityController
public function index(Request $request){
$cities = City::orderBy('name');
return view('pages.city.index', ["cities" => $cities ->paginate(25)]);
}
This works fine, but when I try to sort the results inside the blade view does not work.
#index.blade.php
<table>
<thead>
<tr class="sui-columnheader">
<th class="sui-headercell" data-field="Id">
Id
</th>
</thead>
<tbody class="list">
#foreach ($cities as $city)
<tr class="sui-row">
<td class="sui-cell id">{!! $city->id !!}</td>
</tr>
</tbody>
</table>
When I click the sort button just reloads the page but no sort is applied.
Is because of the "orderBy" clause?
How can I make it work and defaults to order by name?
Am I missing something?
Something like this perhaps. You would want to make sure you limit what can be passed to that orderBy. A URL like "...something?sort=blah" would cause orderBy('blah'), which your table doesn't have, which will cause a DB error.
public function index(Request $request)
{
$cities = City::orderBy($request->input('sort', 'name'))->paginate(25);
return view('pages.city.index', ['cities' => $cities]);
}
{{ $cities->appends(Request::query())->render() }}
Just giving you a functional example, though you will have to adjust based on your own rules.
The appends is just allowing you to continue to paginate based on the current sorting, by passing the sort option via the query string of the pagination links.
Update:
Using your example where there is a default, but imagining there can be more than just 1 other field to sort by:
$sort = trim($request->input('sort'));
// if it is in the acceptable array use it, otherwise default to 'name'
$sort = in_array($sort, ['id', ...]) ? $sort : 'name';
$cities = City::orderBy($sort)->paginate(25);
<table>
<tr>
<th>ID</th>
<th>NAME</th>
...
</tr>
#foreach ($cities as $city)
<tr>
<td>{{ $city->id }}</td>
<td>{{ $city->name }}</td>
...
</tr>
#endforeach
...
{{ $cities->appends(Request::query())->render() }}
Just an example, you can do this how you would like.

Best way to fill a roster schedule

Fellow programmers,
I got a roster application build in PHP with the framework : Laravel. And i have the following issue:
My application has : Users, Taskdate's, and TaskdateTime. Each user can get a TaskdateTime assigned to them. That TaskdateTime is a child of Taskdate. I want to populate a schedule where each user can see all their times. The schedule looks like this :
What i do in my application is : Fetch all users, Fetch all Taskdate's and according to the Taskdate's, fetch the TaskdateTime's for the right Taskdate. I do this in the following way :
$taskdates = Taskdate::with('users')->where_date($date)->get();
$employees = Usergroup::with(array('users', 'users.workdates'))->where('usergroup_title', '=', 'Employees')->first();
You can see that i fetch usergroups, with the relationship : Users and with the User->workdates relationship. Where the workdates returns the TaskdateTime objects as mentioned above.
Now in my view, i do this to populate it with data. And this seems like a lot of extra hassle and i think it could me much easier but i can't wrap my head around it. Anyway, this is the code :
<table id="plan" class="table table-bordered">
<thead>
<th></th>
#foreach($taskdates as $taskdate)
<th id="{{ $taskdate->id }}">{{ $taskdate->subject }}</th>
#endforeach
</thead>
<tbody>
#foreach($employees as $employee)
<tr id="{{ $employee->id }}">
<td>{{ $employee->name }}</td>
#foreach($taskdates as $taskdate)
<?php
$result = array_filter($employee->workdates, function($user) use ($taskdate){
return $user->id === $taskdate->id;
});
?>
#if( empty($result) )
<td></td>
#else
<td id="{{$result[key($result)]->pivot->id }}" style="{{ ($result[key($result)]->pivot->taskdate_isread) ? '' : 'font-weight:bold;'}}">
{{date('H:i', strtotime($result[key($result)]->pivot->taskdate_time))}}
</td>
#endif
#endforeach
</tr>
#endforeach
</tbody>
</table>
So i am filtering the whole workdates relationship of each user, if its hold the Taskdate id. And if it is empty, then don't echo anything.
The syntax of the HTML/PHP is in BLADE, so it might not seem correct PHP parsing, but it is.
Edit :
Question :
My code feels bloated. I don't think this is the most efficient way to achieve the result. What is your opinion on this? I like to be as efficient as possible.

Categories