Cannot retrive data from the database with first() Laravel - php

My controller:
public function getNotificationApplication($user_id, $notification_id)
{
$userdetails = Notification::with('user')->where(['user_id'=>$user_id])->first();
$dataList = [];
$dataList['notify'] = NotificationTypeA::with('notification')->where(['notification_id'=>$notification_id])->get();
return view('Notification.notification_application', $userdetails, $dataList);
}
My route:
Route::get('/notification_application/{user_id}/{notification_id}', 'NotificationController#getNotificationApplication')->name('show.notification_application');
my view:
#foreach ($userdetails as $userdetail)
{{$userdetail->storage_location}}
#endforeach
When I am retrieving data from the database, I get a
Undefined variable: userdetails
I can retrieve other variable ($data) that I am passing as an array, I can display them like this
#foreach ($notify as $notification)
<tr>
<td>{{ $notification->item_name }} </td>
<td>{{ $notification->risk_level }}</td>
<td>{{ $notification->quantity }}</td>
<td>{{ $notification->volume }}</td>
<td></td>
</tr>
#endforeach
When I use
`dd($userdetails);`
in the controller I get the correct data.
i have no clue how to do this.

Change it:
return view('Notification.notification_application', $userdetails, $dataList);
to
return view('Notification.notification_application', array('userdetails' => $userdetails, 'dataList' => $dataList));
and try again.
Explanation: The second parameter of view() is an array in which we can pass the key => value pair. And on view, we can get the data using the key passed in the array of second parameter of view()
Reference

You have to pass an array to the blade.
For that, you can use syntax as Mayank Pandeyz said or alternatively you can usecompact() which will make code much cleaner.
return view('Notification.notification_application', compact('userdetails' ,'dataList'));

Thanks to Parth Vora and Mayank Pandeyz
i solved my problem combining both of their answers.
First of all i was passing 2 parameters one of which is an array the other is simply the first row of the table.
so i have to make a slight change in the controller
$userdetails['userdetails'] = Notification::with('user')->where(['user_id'=>$user_id])->first();
and then return
return view('Notification.notification_application', array('userdetails' => $userdetails), $dataList);
that did the trick..
thank you...

you can use the following methods
1) return view('Notification.notification_application', compact('userdetails' ,'dataList'));
2) return view('Notification.notification_application', ['userdetails' => $userdetails , 'dataList' => $dataList]);
3)
return view('Notification.notification_application')
->with('userdetails', $userdetails)
->with('dataList, $dataList);

You can pass data in return view have two way :
return view('Notification.notification_application', compact('userdetails','dataList'));
OR
return view('Notification.notification_application',
[
'userdetails'=>$userdetails,
'dataList'=>$dataList
]);

Related

Laravel 8 - htmlspecialchars() expects parameter 1 to be string, object given

I'm trying to access a Controller method from inside my view, but I'm getting this error:
htmlspecialchars() expects parameter 1 to be string, object given (View: D:\Programming\Php\Laravel\Laravel-Phone_Book\resources\views\contact_list.blade.php)
Here's my part of my view that's throwing the error:
<tbody id="tableBody">
#foreach ($data as $item)
<tr>
<!-- Test -->
<td>{{ $item->nome }}</td>
<td>{{ $item->numero_count }}</td>
<td>
<ul style="list-style: none;">
{{ $phones = app\Http\Controllers\ContactListController::get_telefones_by_usuario($item->u_id) }}
#foreach ($phones as $phone)
<li>{{ $phone }}</li>
#endforeach
</ul>
</td>
</tr>
#endforeach
</tbody>
Here's my controller function:
public function get_telefones_by_usuario($id)
{
$telefones = Telefone::join("usuarios", "usuarios.id", "=", "telefones.id_usuario")
->select("telefones.numero as numero")
->where("usuarios.id", "=", $id);
return $telefones;
}
Here's my Controller's function that injects data into my index view (that includes the view I'm trying to access the data from):
public function index()
{
// $usuarios = Usuario::all();
// $telefones = Telefone::all();
$data = Usuario::join("telefones", "usuarios.id", "=", "telefones.id_usuario")
->select(
"usuarios.id as u_id",
"usuarios.nome as nome",
"telefones.numero as numero",
DB::raw("COUNT(telefones.numero) AS numero_count")
)
->groupBy("usuarios.nome")
->orderBy("usuarios.nome")
->get();
return view("index", compact("data"));
}
What am I doing wrong? u_id is supposed to be an integer, not an array or anything. Why is htmlspecialchars() not parsing it?
Thank you.
Edit:
Tried placing the following at the top of my partial view:
#inject('ContactListController', app\Http\Controllers\ContactListController")
Then replacing the part where I call my Controller method above with the following:
<?php $phones = $ContactListController::get_telefones_by_usuario($item->u_id) ?>
Now the error went away but I'm not getting anything back from my query, which I should:
On the Phones column there should be a list of phones associated with each person.
What's going on?
I think you should edit the below line.
$telefones = Telefone::join("usuarios", "usuarios.id", "=", "telefones.id_usuario")
->select("telefones.numero as numero")
->where("usuarios.id", "=", $id)->get();
also when printing try to print the value using the right index.
<li>{{ $phone->numero }}</li>

How to return variable in Laravel controller to view properly?

What i want to achieve here is to return a string to my view in laravel, but i what i got is this error
"Undefined variable: tod (View:
C:\xampp\htdocs\blog\resources\views\opj_view.blade.php)"
and here is my controller look liked :
public function index()
{
$tod = 'test';
$user = DB::select('select * from tbluser where ID like ?',['%USER%']);
return view('opj_view',['user '=>$user ],['tod'=>$tod]);
}
and here is my view looked like :
<body>
<?php echo $tod; ?>
<div>User</div>
<table border = 1>
<tr>
<td>User ID</td>
<td>Username</td>
</tr>
#foreach ($user as $users)
<tr>
<td>{{ $users->ID }}</td>
<td>{{ $users->User_Name }}</td>
</tr>
#endforeach
</table>
</body>
How to print out $tod variable properly? Because when I delete my ['tod'=>$tod] it works, it just string but it said Undefined Variable, I am newbie in PHP, is there some way to declare variable? from what i read may way is true.. please need help guys
Change
return view('opj_view',['user '=>$user ],['tod'=>$tod]);
To
return view('opj_view',['user' => $user, 'tod' => $tod]);
You can read the documentation about Passing Data To Views
From the docs and experiance
return view('opj_view',compact('tod,'user'));
Or
return view('opj_view',['user '=>$user,'tod'=>$tod ]));
Or
return view('opj_view')->with(['user '=>$user,'tod'=>$tod]);
You're passing two arrays to the view, you just need to have tod as an index in the same array:
public function index()
{
$tod = 'test';
$user = DB::select('select * from tbluser where ID like ?',['%USER%']);
return view('opj_view',['user '=>$user, 'tod'=>$tod]);
}
You can simply use:
return view('opj_view')->with('user', 'tod');

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

query string not working in laravel 5

In the following code I used {!! URL::route('editCatForm',['id'=>$row->id]) !!} to go to named route editCatForm with query string ?id=5 or whatever that comes dynamically on $row->id
#foreach($categories as $row)
<tr>
<td>{{ $count++ }}</td>
<td>{{ $row->category_name }}</td>
<td>{{ $row->category_status }}</td>
<td>edit / delete</td>
</tr>
#endforeach
My route for this is
Route::get('editCatForm/{id?}',array('uses'=>'Categories#editCat','as'=>'editCatForm'));
but still it shows url like
http://localhost/projects/brainlaratest/editCatForm/2
instead of
http://localhost/projects/brainlaratest/editCatForm?id=2
The route points to function
public function editCat($id)
{
$catEdit = Category::find(Input::get('id'));
$categories = $this->getCat();
return view('categoriesAddForm',compact('categories','catEdit'));
}
What may be the issue that query string isn't working here?
Format of your url is editCatForm/{id?} so if you provided id it will try to replace {id} with your number and you will get editCatForm/5.
Problem is in your controller action. function editCat($id) already takes $id from route - you should replace Input::get('id') with just $id.
URL::route(...) can be replaced by just helper function route(...).
If you want get rid of /id you can remove {id} from your route and then route(...) will just add ?id=5 instead of /5. You would have to remove $id argument from function and get id by Request::input('id');.
This is how route() function is supposed to work.
If you insist on having the query string then you need to append the ?=2 to the URL manually and you cannot do routing based on this.
One way of building the query string is like this
$params = array('id' => 5);
$queryString = http_build_query($params);
URL::to('projects/brainlaratest/editCatForm?'.$queryString )
The Routing is correct. Your problem is to getting the $id in the action.
Since, you have passed $id in route parameter, you can capture the segment $id inside your action.
public function editCat($id)
{
$catEdit = Category::find($id); // edit this line.
$categories = $this->getCat();
return view('categoriesAddForm',compact('categories','catEdit'));
}
source: http://laravel.com/docs/5.0/routing#route-parameters

Categories