I'm working on a laravel project and i'm getting JSON error. I've try few options to solve the issue but did not come up with any solutions.
In this project I've to send multiple data into database onder one "ID". In that ID there are at list 10 data need to insert. So I used JSON format. It saves ok but getting error when I try to pull data.
Here is my code
Controller :
public function newExpenses(Request $request){
$Jexpenses = new Jexpenses;
$json = array(
'des' => $request->description,
'valu' => $request->expenses
);
$Jexpenses->voucher = $request->voucher_no;
$Jexpenses->date = $request->date;
$Jexpenses->description = json_encode($json);
$Jexpenses->expenses = $request->total;
$Jexpenses->remarks = $request->remark;
if($Jexpenses->save()){
$notification = array(
'message' => 'Expenses Saved',
'alert-type' => 'success'
);
}
return redirect()->back()->with($notification);
}
result :
{"des":["Jon","Sam","Pitter"],"valu":["20","30","15"]}
Return Controller:
public function expenses(){
$data = array(
'title' => 'Expenses',
'expenses' => Jexpenses::all()
);
return view('expenses.expenses')->with($data);
}
html :
#foreach ($expenses as $key => $getData)
{{ $array = #json( $getData->description ) }}
<tr>
<td>{{ ++$key }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($array->description as $k => $v)
<td>{{ $array->des['$k'] }}</td>
<td>{{ $array->valu['$k'] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach
it should be work fine but getting error
error:
syntax error, unexpected '<' (View: C:\xampp\htdocs\acSoft\resources\views\expenses\expenses.blade.php
Need some help. Thanks.
1) Use json_decode($getData->description) instead #json. The #json is shortly form of json_encode
2) $array->description not exists property. Should be $array->des
3) You use variable in ' quotes. You should use " quote or nothing round variables.
4) It is bad idea using reserved words as variable names. I am about variable $array
#foreach ($expenses as $key => $getData)
{{ $descriptionData = json_decode( $getData->description ) }}
<tr>
<td>{{ $key + 1 }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($descriptionData->des as $k => $v)
<td>{{ $descriptionData->des[$k] }}</td>
<td>{{ $descriptionData->valu[$k] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach
Related
When I'm going to add data an error appears "Call to a member function count() on null"
View
#foreach ($data as $row)
<tr>
<td>{{ $row->customer}}</td>
<td>{{ $row->vessel}}</td>
<td>{{ $row->scopejob}}</td>
<td>{{ $row->pergantian_sparepart}}</td>
<td>{{ $row->teknisi}}</td>
<td>{{ $row->tahun}}</td>
<td>{{ $row->keterangan}}</td>
<td>{{ $row->images->count()}}</td>
<td>{{ $row->files->count()}}</td>
<td>
FOTO
FILE
EDIT
<a href="#" class="btn btn-danger delete m-1" data-id="{{ $row->id}}" data-customer="{{ $row->customer}}" >DELETE</a>
</td>
</tr>
#endforeach
Controller rekap:
public function insert_rekap(Request $request) {
// dd($request->all());
$this -> validate($request,[
'customer'=>'required',
'vessel'=>'required',
'scopejob'=>'required',
'pergantian_sparepart'=>'required',
'teknisi'=>'required',
'tahun'=>'required',
'keterangan'=>'required'
]);
$data = rekap::create($request->all());
if($request->hasFile("images")){
$images=$request->file("images");
foreach($images as $image){
$imageName=time().'_'.$image->getClientOriginalName();
$request['rekap_id']=$data->id;
$request['image']=$imageName;
$image->move(public_path("/images_rekap"),$imageName);
Image_rekap::create($request->all());
}if($request->hasFile("files")){
$files=$request->file("files");
foreach($files as $file){
$fileName=time().'_'.$file->getClientOriginalName();
$request['rekap_file_id']=$data->id;
$request['file']=$fileName;
$file->move(\public_path("/rekap_file"),$fileName);
file_rekap::create($request->all());
}
}
}
return redirect()->route('rekap')->with('success','Data Berhasil Ditambahkan');
}
but the data is successfully entered into the database, and what steps should I take to correct the error
error tells you that images or files or both variables are null, looks like you don't use eager loading
quick and dirty way is to use optional helper
<td>{{ optional($row->images)->count()}}</td>
<td>{{ optional($row->files)->count()}}</td>
if you need only count then better approach is to use eloquent counting related models
// controller
$data = rekap::withCount(['images', 'files'])
// other selecting rules
//->where ...
->get();
return view('view_name', ['data'=>$data]);
now in every $row of $data you have fields images_count and files_count
<td>{{ $row->images_count }}</td>
<td>{{ $row->files_count }}</td>
also you can rename count variables like rekap::withCount(['images as imagesCount', 'files as filesCount'])
<td>{{ $row->imagesCount }}</td>
<td>{{ $row->filesCount }}</td>
Try
<td>{{ $row->images ? $row->images->count() : '' }}</td>
part of this data in store method decoded and i want to use this encoded data in blade template:
How is this possible?
public function store(VehiclesRequest $request)
{
$data = Vehicle::create([
'container_type' => $request->container_type,
'type' => $request->type,
'delivery_capacity' => $request->delivery_capacity,
'plate_number' => json_encode($request->plate_number),
'chasis_number' => $request->chasis_number,
'capacity_dimensions' => json_encode($request->capacity_dimensions),
'fuel_consumption_rate' => $request->fuel_consumption_rate,
'capacity_weight' => $request->capacity_weight,
'insurance_expire_date' => json_encode($request->insurance_expire_date),
'insurance_type' => $request->insurance_type,
'is_available' => $request->is_available,
]);
return redirect()->action('VehicleController#index');
}
VehicleController:
public function index()
{
$vehicles = Vehicle::all();
return view('vehicle.index', compact('vehicles'));
}
view:
<tbody>
#foreach(vehicles as $vehicle)
<tr>
<td>{{ $vehicles->plate_number }}</td>
<td>{{ $vehicles->delivery_capacity }}</td>
</tr>
#endforeach
</tbody>
i used from {{ json_decode($vehicles->plate_number) }} in blade template but an error occurred.
You can Decode json data in view.blade.php like this :
<tbody>
#foreach($vehicles as $vehicle)
<tr>
<td>
#foreach(json_decode($vehicles->plate_number) as $plate)
{{ $plate['variable_name'] }}
#endforeach
</td>
<td>{{ $vehicles->delivery_capacity }}</td>
</tr>
#endforeach
</tbody>
So I've been working with symfony for a while and I'm trying to understand how it works. So, I tried to count how many tasks do I have in my tasks array.
This is my homeController.php class:
public function succesfulLogin(Request $request)
{
$repository = $this->getDoctrine()->getRepository('AppBundle:Task');
$tasks = $repository->findByAuthor($this->getUser()->getUsername());
$points = 0;
foreach($tasks as $task){
$points++;
}
return $this->render(
'userpage.html.twig',array('username' => $username = $this->getUser()->getUsername(), 'tasks' => $tasks, 'points' => $points ));
$user->getTasks();
//as I understant I return '$tasks' array to twig with all my tasks
//so before returning '$tasks' array it should have 21 object in it?(not 13)
//am I wrong?
}
So I pass 'points' to twig and twig prints out number 13, but when I try to print out all tasks in twig, it says that I have 21 task.
There is some twig code:
{% for task in tasks %}//this foreach loop prints out 21 task
<tr>
<td id>{{ task.Id }}</td>
<td>{{ task.Status }}</td>
<td>{{ task.Name }}</td>
<td>{{ task.Description }}</td>
<td>{{ task.Category }}</td>
<td>{{ task.Author }}</td>
<td>{{ task.CreationDate|date("m/d/Y") }}</td>
<td><a id="myLink" href="/edit/{{ task.ID }}" > Edit </a></td>
<td><a id="myLink" href="/delete/{{ task.ID }}" >Delete</a></td>
<?php echo 2+2; ?> </tr>
{% endfor %}
Generally, you should use count() or sizeof() function in PHP for getting count of the objects. So you could just run $points = count($tasks) instead of iterations over $tasks and incrementing.
If you'd like to get array count in twig template, you could use built-in length filter.
{% set tasks_count = tasks|length %}
Compare two different columns from two different tables with if statement and show other column's data from either table in laravel 5.2
controller like:
public function labDetails(){
$users = DB::table('users')->lists('lab_name');
$labdetails = Labdetails2::paginate(20);
return View('labdetails')
->with('users', $users)
->with('labdetails', $labdetails);
}
here i want to match users table's 'lab_name' column with labdetails2 table's 'lab_name' column and if they matched show only the related data from labdetails table.
N.B. I am working with an old database where there's no relationship among tables.
views like:
<form action="" method="">
<select name="state" onchange="getValue(this)">
<option value="">Select Lab</option>
#foreach ($users as $key => $user)
<option value="{{ $user }}">{{ $user }}</option>
#endforeach
</select>
<input type="submit" value="Submit">
#foreach ($labdetails as $labdetail)
<tbody>
<tr>
<td>{{ $labdetail->sl }}</td>
<td>{{ $labdetail->lab_name }}</td>
<td>{{ $labdetail->pc_name }}</td>
<td>{{ $labdetail->pc_ip }}</td>
<td>{{ $labdetail->mac1 }}</td>
<td>{{ $labdetail->assetno }}</td>
<td>{{ $labdetail->pc_type }}</td>
<td>{{ $labdetail->processor }}</td>
<td>{{ $labdetail->motherboard }}</td>
<td>{{ $labdetail->ram }}</td>
<td>{{ $labdetail->hdd }}</td>
<td>{{ $labdetail->location }}</td>
<td>{{ $labdetail->department }}</td>
<td>{{ $labdetail->entrydate }}</td>
<td>{{ $labdetail->comment }}</td>
</tr>
</tbody>
#endforeach
Please help me what should I do with the controller & views...
You can retrieve only the matches record this way
$users = DB::table('users')->lists('lab_name'); // this retrieves all lab_name as array.
Then, to retrieve only the matches labdetails
$labdetails = Labdetails2::whereIn('lab_name',$users)->paginate(20);
DB::table('users')
->join('labdetails2', 'users.lab_name', '=', 'labdetails2.lab_name')
->select('labdetails2.lab_name', 'labdetails2.pc_name')
->get()
in select(), white down the fields you required.
Here, labdetails2 and users are the table name.
this code finally worked for me:
public function showLabDetails(Request $request){
$q = $request -> request -> all();
$labdetails = Labdetails2::whereIn('lab_name', $q)->get();
return View('showlabdetails')
->with('labdetails', $labdetails);
}
thanks to everyone for helping me.
I've got a table like below:
<tr>
<td>{{ item.wo_num_and_date }}</td>
<td>{{ item.comp_name_and_number }}</td>
<td>{{ item.finish_sizes }}</td>
<td>{{ item.material }}</td>
<td>{{ item.total_num_pieces }}</td>
<td>{{ item.workorder_num_one }}</td>
<td>{{ item.notes_one }}</td>
<td id='signoff_userone'><input type='button' id='signoff_user_one' data-rowid={{ item.id }} value='Signoff' /> {% if item.signoff_user_one is defined and item.signoff_date_one is defined %}{{ item.signoff_user_one.name|title }} {{ item.signoff_date_one }} {% endif %}</td>
<td>{{ item.workorder_num_two }}</td>
<td>{{ item.notes_two }}</td>
<td id='signoff_usertwo'><input type='button' id='signoff_user_two' data-rowid={{ item.id }} value='Signoff' /> {% if item.signoff_user_two is defined and item.signoff_date_two is defined %}{{ item.signoff_user_two.name|title }} {{ item.signoff_date_two }} {% endif %}</td>
<td>{{ item.workorder_num_three }}</td>
<td>{{ item.notes_three }}</td>
<td><input type='button' id='signoff_user_three' value='Signoff' /> {{ item.signoff_user_three.firstname }} {{ item.signoff_user_three.lastname }}</td>
</tr>
Fiddle: http://jsfiddle.net/qwUV4/1/
Here's my php code I call when a button is clicked, everything works well for the first "Sign Off" box but the other 2 don't work, obviously because of my Update statement below which is only set to update column "signoff_user_one".
<?php
require_once('../includes/config.php');
$user_id = getuserinfo($loggedin_id);
$row_id = (int)mysqli_escape_string($dbc3, $_POST['rowid']);
$sql = "UPDATE checklist_component_stock SET signoff_user_one = $loggedin_id, signoff_date_one = NOW() WHERE id = " . $row_id;
mysqli_query($dbc3, $sql);
$ret = array('rowid' => $row_id, 'user' => $user_id, 'date' => date('Y-m-d H:i:s')); //date('M d, Y')
echo json_encode($ret);
?>
My question is, would I need cases so the script checks whether its signoff_user_one, user_two, or user_three and executes the correct update statement? How would I do something like that? Is there another solution?
Are you using a loop? Because in such a case, it would probably not work very well.It should work well with the buttons and the specific ids which you have captured.You could use an isset function and use the name attribute for the button..