How To use Database as a variable with blade template in laravel? - php

i'm new in laravel, i have some problem to make database as variable to be shown on blade template,
example i want to get any data from database :
{{$get = DB::table('perangkat')->get()}}
then:
#foreach ($get as $got)
{{$got->jabatan}}
#endforeach
if the result of the $got->jabatan is kepala, But i want the result is Change To "Kepala Desa", How can i do ??
Please Help Mee ...

Write database related stuff in model or controller in a method and pass that value to view. It will be very neat and clear
public function getData(){
$get = DB::table('perangkat')->get();
return view('myblade', ['data' => $get]);
}
In your view
#foreach ($data as $got)
{{$got->jabatan}} Desa
#endforeach
Also can you update where you get Desa .so i can update answer according to that.
Updated
you keep different roles in array and do some think like this
<?php
$role=['a'=>'operator','b'=>'admin'] ; ?>
#foreach ($data as $got)
<?php $result = isset($role[$got->jabatan]) ? $role[$got->jabatan] : null; ?>
{{$result}}
#endforeach

company.php
function showdata{
$sql= "this syntax sql";
}
//show data
$company = new company();
#foreach ($company->showdata() as $got)
{{$got->jabatan}}
#endforeach

Related

How to use each method to put result in view

Instead of creating a foreach loop I want to iterate over the results and
I am using the each() method:
$collection = Comment::all();
$comment = $collection->each(function ($comment){
dd($comment->comment);
});
when I dd() I get:
"Hatter; 'so I should think."
But when I pass to view:
return view('welcome')->with('comment',$comment);
I get
[{"id":1,"post_id":5,"comment":"Hatter; 'so I should think.","created_at":"2018-04-05 15:23:20","updated_at":"2018-04-05 15:23:20"},
{"id":2,"post_id":5,"comment":"Alice gently remarked;.","created_at":"2018-04-05 15:23:20","updated_at":"2018-04-05 15:23:20"},
and so on..
This is the view:
{{$comment}}
I want to iterate through the collection and put data into $comment and then show it in the view.
It is quite simple like this.
Iterate then -> following the property name
#foreach($comment as $row)
<li>{{ $row->id }}</li>
<li>{{ $row->post_id}}</li>
//AND SO ON
#endforeach

Laravel : Explode array with relation belongsTo to model

I want to explode array value and have successfully doing so by using this code :
#foreach(explode('.', $comment->topic_id) as $topic)
{{ $topic }}
#endforeach
This is the output
Topic : 1,2
The problem is, I want to implement relation belongsTo to the topic_id. When I add the relation and run the code, unfortunately only one of the value is shown.
#foreach(explode('.', $comment->getTopic->topic) as $topic)
{{ $topic }}
#endforeach
This is my model
public function getTopic()
{
return $this->belongsTo('App\Topic', 'topic_id', 'id');
}
Output :
Topic : Laravel
What is the right way to call this array? Please help me. Thank you.
You can't use relationship in this case. If you simply looking for solution then you could do something like the following:
<?php $topic_ids = explode('.', $comment->topic_id);
$topics = App\Topic::whereIn(id, $topic_ids)->get();
?>
#foreach($topics as $topic)
{{ $topic }}
#endforeach
BTW you should structure your database more efficiently.
#foreach(explode(',', $item->chapter_id) as $layer)
<?php
$chapters = DB::table('topic_types')->where('id', $layer)->get();
?>
#foreach ($chapters as $ch)
{{$ch->name}} <br>
#endforeach
#endforeach

unable to print table data on blade file in laravel

need print Task table task_name column values in index.blade.php file
this is index.blade.php
#if(isset($tasks))
#foreach ($tasks as $task)
<h1>{{ $task->task_name }}</h1>
#endforeach
#endif
TasksController.php is
public function index()
{
$tasks = Task::all();
return view('tasks.index')->withTasks($tasks);
}
No any error message but do not print data...how to fix
Change:
return view('tasks.index')->withTasks($tasks);
to
return view('tasks.index')->with('tasks', $tasks);
or
return view('tasks.index', array('tasks' => $tasks));
and try again.
Explanation:
The second parameter of the view function is the the array that contains the data in it on different indexes. As an alternative to passing a complete array of data to the view helper function, you may use the with method to add individual pieces of data to the view.
Reference
Just replace
return view('tasks.index')->withTasks($tasks);
with
return view('tasks.index',['tasks'=>$tasks]);
And try again.

Unique collection in Laravel

I need to find out unique value. So I tried bellow code. It is through undefined variable error.
Controller:
$employee = Employee::all();
Return view ('page', compact('employee'));
Page view:
$uniqueEmpLoc = $employee->unique('location')->values()->list('location')->toArray();
#Foreach($uniqueEmpLoc as $empLoc)
{{ $empLoc }}
//this is select box used for search
#endforeach
//Display Entire data
#foreach($employee as #employee)
//Display all value
#endforeach
But I got an uniqueEmpLoc is undefined error. I'm using LARAVEL 5.1. Please help me to solve this problem.
There are some errors in your code:
I don't think compact(employee) would work. Shouldn't that suppose to be compact('employee') ?
In Blade, there is no need of putting curly braces at all. Remove them.
Try out the following:
$employees = Employee::unique('locations')->values()->list('location')->toArray();
return view('page', compact('employees'));
And then in your view:
#foreach($employees as $employee)
{{ $employee }}
#endforeach
Use this query in controller
$employees = Employee::distinct()->list('location')->toArray();
return view('page', compact('employees'));
In view
#foreach($employees as $employee)
{{ $employee }}
#endforeach
I agree with the other answers here, this code should be in the controller. You shouldn't be doing logic in the views.
In the controller do:
$uniqueEmpLoc = $employee->unique('location')->values()->list('location')->toArray();
$employee = Employee::all();
Return view ('page', compact('employee', 'uniqueEmpLoc'));
The reason your code isn't working is the line that defines $uniqueEmpLoc is interpreted by blade as text, not code.
If you really want to do that in the view, you need to wrap it in #php tags.
#php
$uniqueEmpLoc = $employee->unique('location')->values()->list('location')->toArray();
#endphp
#Foreach($uniqueEmpLoc as $empLoc)
{{ $empLoc }}
//this is select box used for search
#endforeach

Showing a JSON with the following structure in Laravel

Good afternoon
I recieve this JSON
{"id":130,"nif":"47812480B","name":"Bernat","cognoms":"Fernandez","file":"uploads\/fondo.jpg","birthday":"0000-00-00","presentacion":"presentacion","email":"bernat#gmail.com","password":"$2y$10$GfP1DYkTqyohjVzRcuuxaeKBSu7iJUBWJK6UDj7p681307uI6Ersq","idempresa":1,"id_poblacion":889,"id_online":0,"remember_token":null,"created_at":"2015-05-28 15:25:04","updated_at":"2015-05-27 15:25:04","municipio":{"id":889,"idprovincia":33,"poblacion":"Art\u00e9s","poblacionseo":"artes","postal":8271,"latitud":"41.798479","longitud":"1.954828"},"subastas":[{"id":16,"nombre":"HTC Wildfire","descripcion":"Descripcion","precio_salida":125,"cant_actual":125,"id_estado":0,"id_metode_envio":1,"id_metodo_pago":1,"id_creador":130,"id_ganador":125,"id_categoria":33,"id_adquirido":1,"data_inici":"2015-06-13","data_final":"2015-06-13","durada":1,"created_at":"2015-06-06 09:09:54","updated_at":"2015-06-06 09:55:49"}]}<p>34.884533408812</p> {"id":131,"nif":"263","name":"Lalo","cognoms":"Lelo","file":"uploads\/count.png","birthday":"0000-00-00","presentacion":"jejjsjsj","email":"vsdfsfaf#aasa.com","password":"$2y$10$QtrolUS9emCS7bfirsly9.JXt9AsYfAc.\/vA0iJCs47\/3g\/ypc8d6","idempresa":1,"id_poblacion":175,"id_online":0,"remember_token":"B1vEqdX8w42i7sLNvG201EArwSTrODe0DDzkVmjzj48ahMMV8oOLmzYRM5Mp","created_at":"2015-05-20 06:52:59","updated_at":"2015-06-06 08:35:13","municipio":{"id":175,"idprovincia":9,"poblacion":"Benej\u00fazar","poblacionseo":"benejuzar","postal":3390,"latitud":"38.083525","longitud":"-0.836494"},"subastas":[{"id":15,"nombre":"Nombre","descripcion":"Descripcion","precio_salida":142,"cant_actual":142,"id_estado":1,"id_metode_envio":1,"id_metodo_pago":1,"id_creador":131,"id_ganador":131,"id_categoria":33,"id_adquirido":1,"data_inici":"2015-06-18","data_final":"2015-06-17","durada":1,"created_at":"2015-06-06 00:00:00","updated_at":"2015-06-06 10:00:57"}]}<p>475.51158492016</p>
When I use the following foreach I show the information
#foreach ($subastas as $subasta)
{{$subasta}}
#endforeach
Now I try to use the following code
#foreach ($subastas as $subasta)
#foreach ($subasta->subastas as $sub)
{{$sub}}
#endforeach
#endforeach
And I recieve this error
Trying to get property of non-object (View: C:\xampp3\htdocs\laravel\resources\views\prodcercanos.blade.php)
Any solution for this problem ?
The question is , how I can render the json in laravel ?
The controller to recieve the JSON
public function productoscercanos ($lat,$long){
$subastas = Subasta::all();
$categorias = Categoria::all();
$provincias = Provincia::all();
$cercanos = User::with(array('municipio', 'subastas'))->get();
$coordA = Geotools::coordinate([$lat,$long]);
$output = [];
foreach ($cercanos as $p) {
if(count($p->subastas)>0){
$coordB = Geotools::coordinate([$p->municipio->latitud,$p->municipio->longitud]);
$distance = Geotools::distance()->setFrom($coordA)->setTo($coordB);
$dis = $distance->in('km')->haversine();
$output[$dis] = $p."<p>$dis</p>";
}
}
ksort($output);
return view('prodcercanos')->with('categorias',$categorias)->with('provincias',$provincias)->with('subastas',$output);
}
$json = (your json file);
$subasta = json_decode($json);
then you should be able to use the json as a object now.
Try array syntax in the second foreach loop.
#foreach ($subasta['subastas'] as $sub)
{{$sub}}
#endforeach
Your code is outputting exactly what is defined. First look at how the controller is building the array.
$output[$dis] = $p."<p>$dis</p>";
$p is a User model from the variable $cercanos, appending it to $dis results in it being converted into JSON and added to your output array which your view iterates and outputs.
It looks like you are trying to add the distance to the user and pass it on.
Instead use an Accessor & Mutator to add an extra attribute to your model then pass on the $cercanos list to the view, from there you can render using a for each and grab the value.
#foreach($cercanos as $c)
{{ $c->username }} {{ $c->dis }}
#endforeach
Update
Once you have added your accessor and mutator you will be able to sort using Collections built in method.
$cercanos->sortBy('dis');

Categories