How to do Query & show the result in Laravel - mysql

I want to dislpay all the data from table: room that has id = 1
but no result came out
here is my code:
public function show($id)
{
$room_list = Room::where('house_id','=','1');
return view('book.show', compact('room_list'));
}
in view
<?php foreach($room_list as $room): ?>
Room Number: {{room->house_id}}
<?php endforeach ?>
but no result appear, even the Room Number label is not appear meaning the query result is empty.
I already check the table room, it has data wih house_id = 1
Thank you for your help!

You should try this:
public function show($id)
{
$room_list = Room::where('house_id','=',$id)->get();
return view('book.show', compact('room_list'));
}
View
#foreach($room_list as $room)
Room Number: {{$room->house_id}}
#endforeach

Try this:
public function show($id)
{
$room_list = Room::where('house_id','=','1')->get();
// get() will return all the matching records that fulfill the condition criteria
return view('book.show', compact('room_list'));
// here compact('room_list') will pass the variable named $room_list to the view
}
View: You can use $room_list variable on view like:
#foreach($room_list as $room)
Room Number: {{$room->house_id}}
#endforeach

Related

How to count the number of users from a table through views in laravel?

I'm working on a laravel 5.5 and I'm trying to count the number of users from a table and display the result from a view.
But I'm getting an error
"Undefined Variable: count"
This is the function inside the controller:
public function admin(){
$count = DB::select('select count(*) as total from users');
return view('home',['count' => $count]);
}
This is the code inside the view 'home':
<tr>
<td> Total Users </td>
<td> Total Coaches </td>
<td> {{$count}} </td>
</tr>
You have given the variable in a string like this ['count => $count'], so it didn't work.
Try the code as below in your controller:
public function admin()
{
$count = DB::select('select count(*) as total from users');
return view('home', ['count' => $count[0]->total]);
}
The issue is here:
return view('home',['count => $count']);
// Single quotation is on wrong place, array key will be wrapped with single quotation not the variable
change it to:
return view('home',['count' => $count]);
and on your view try:
{{ $count[0]->total }}
it work for me
use Illuminate\Support\Carbon;
$users_count = User::count();
$users_today = User::where('created_at','>=',Carbon::now()->startOfDay())->count();
$users_this_week = User::where('created_at','>=',Carbon::now()->startOfWeek(\Carbon\Carbon::SATURDAY)->startOfDay())->count(); // default startOfWeek() is Monday
$users_this_month = User::where('created_at','>=',Carbon::now()->firstOfMonth()->startOfMonth()->startOfDay())->count();
$users_this_year = User::where('created_at','>=',Carbon::now()->firstOfMonth()->startOfMonth()->startOfDay())->count();

Retrieve and edit data on page using Laravel

I cant display my data, laravel's 404 page popping.
Here is my foreach codes.
#foreach($este as $row)
{{$row['価格']}}
{{$row['間取り']}}
{{$row['販売戸数']}}
{{$row['総戸数']}}
{{$row['専有面積']}}
{{$row['専有面積']}}
{{$row['その他面積']}}
{{$row['所在階/構造 階建']}}
{{$row['完成時期']}}
{{$row['住所']}}
#endforeach
What am I doing wrong here.
I want to edit table with css but data doesn't display.
My controller, and route is here:
public function sumos($id)
{
$este = estates::all();
return view('pages.sumo', ['este' => $este]);
}
Route::get("sumo/{id}", "PagesController#sumos");
Change your controller and route to the following
public function sumos()
{
$data['este'] = estates::all();
return view('pages.sumo', $data);
}
Route::get("sumo", "PagesController#sumos");
then your view to
#foreach($este as $row)
{{$row->価格}}
{{$row->間取り}}
{{$row->販売戸数}}
{{$row->総戸数}}
{{$row->専有面積}}
{{$row->専有面積}}
{{$row->その他面積}}
{{$row->所在階/構造 階建}}
{{$row->完成時期}}
{{$row->住所}}
#endforeach
Don't return the value from the controller . Instead send the values to the view as parameter and then use it in your view
Like
public function sumos()
{
$este = estates::get();
return view('viewName', ['este' => $este]);
}
And in your view
#foreach($este as $row)
write markup for your items here.
#endforeach
1.Actually get is for retrieve all the data from table ,
2.After getting related data pass it on view
public function sumos()
{
$este = estates::get();
return view("editPage" , compact('este'));
}
After View data in table using
#foreach($este as $est) //data here like html css #endforeach
add route to update data and pass it into controller
Then find related row using `
public function find($id){
$estates = estates::find($id);
//after changes
$estates->save();
return redirect()->back();
}
`
firs you have to create a view file
How to use views in Laravel?
then just use this construction:
public function sumos()
{
$este = estates::all();
return view('name_of_your_view_file', compact('este');
}
change your route to
Route::get("sumo/{id}", "PagesController#sumos");

Delete multiple records (Laravel)

I want to delete multiple records at one time using checkboxes. My code is not working.
my html
#foreach($userallergens as $aller)
<input type="hidden" name="ua_id" value="{{$aller->ua_id}}">
<input type="checkbox" class="allergies" name="allergen[]" value="{{$aller->ua_id}}">
{{ $aller->allergen_name}}</label>
<label>Tolerance Level:<b>{{$aller->tolerance_level}}</b></label><br>
#endforeach
my controller
public function destroy(Request $request){
$id=Auth::user()->id;
$uaid=UserAllergen::where('ua_id', $request['ua_id'])->get();
if (is_array($id))
{
UserAllergen::destroy($uaid);
}
else
{
UserAllergen::where('ua_id', $uaid)->delete();
}
return redirect()->route('user.profile', compact('user', 'id'));
}
ua_id should be ua_id[] so the form posts it as an array, you got it right for the allergens
There are a few mistakes first:
$id=Auth::user()->id;
and
if (is_array($id))
That's never going to work since the user id is always a non array value
Then you need to make a few changes to your code
Also change this
UserAllergen::where('ua_id', $uaid)->delete();
To this
UserAllergen::whereIn('ua_id', $uaid)->delete();
Also unless ua_id is your primary key i would avoid using destroy as it bases on the table primary key (id usually), you can instead use
UserAllergen::where('ua_id', $uaid)->delete();
However, if it's the PK of your table you can use destroy in the case of the array as well reducing your code to just
public function destroy(Request $request){
$uaid = $request->get('ua_id'); // array
UserAllergen::destroy($uaid);
return redirect()->route('user.profile', compact('user', 'id'));
}
or
public function destroy(Request $request){
$uaid = $request->get('ua_id'); // array
UserAllergen::whereIn('ua_id', $uaid)->delete();
return redirect()->route('user.profile', compact('user', 'id'));
}
Delete multiple Rows (record) in Laravel 5.8:
$rowIds = "1,3,5";
$Rowsdeleted = explode(",", $rowIds);
foreach($Rowsdeleted as $rowId) {
$response = YourModelName::where('id',"=",$rowId)->delete();
}
use in controller
public function destroy(Request $request){
$uaid = $request->get('ua_id'); // array
UserAllergen::whereIn('ua_id', $uaid)->delete();
return redirect()->route('user.profile', compact('user', 'id'));
}
when you comes with array of that id's

How to view data using junction table Yii2

I've got three tables
checkoutcounter {id, name}
user {id, username}
checkoutcounter_users { id, checkoutcounter_id, user_id}
I use gii and then add
in checkoutcounter model (I add and joinWith and find()->with but it still doesn't work):
public function getUser_display()
{
return $this->hasMany(User_display::className(), ['id' => 'user_id'])
->viaTable(CheckoutcounterUsers::tableName(), ['checkoutcounter_id' => 'id']
);
}
In checkoutcounter model search:
public function search($params)
{
$query = FinanceSettingsCheckoutcounter::find()->with('user_display');
$query->joinWith('user_display');
}
what should I add in checkoutcounter view to get usernames or user id's? Why when I add in gridview 'attribute'=>'user_display.id' it doesn't display any data?
echo yii\helpers\Json::encode($dataProvidercheckoutcounter);
shows
{"query":{"sql":null,"on":null,"joinWith":[[["user_display"],true,"LEFT JOIN"]],"select":null,"selectOption":null,"distinct":null,"from":null,"groupBy":null,"join":null,"having":null,"union":null,"params":[],"where":null,"limit":null,"offset":null,"orderBy":null,"indexBy":null,"modelClass":"app\\models\\FinanceSettingsCheckoutcounter","with":["user_display"],"asArray":null,"multiple":null,"primaryModel":null,"link":null,"via":null,"inverseOf":null},"key":null,"db":null,"id":null}
Im not sure how you're using your search() function, but you're not using $params.. And its not returning the results..
I belive the query should be like this:
public function search($params)
{
$result = FinanceSettingsCheckoutcounter::find()->with('user_display')->all();
echo yii\helpers\Json::encode($result);
}
if you are using this as part of a Search Model, returning a dataProvider, check out this link
http://www.ramirezcobos.com/2014/04/16/displaying-sorting-and-filtering-model-relations-on-a-gridview-yii2/

Query is returning empty arrays in CakePHP (model and controller are set up)

I'm using Cake's find('all') method in the controller to query a table I have, and the requestAction method to use the controller function (and so to output the data) within the view. The problem is that the find method is returning empty arrays(ouput is 'ArrayArrayArray'). The table is named 'users' (as per Cake conventions) and the code for all three files are below:
Code for the view (test.ctp)
<?php
$users = $this->requestAction('/users/read');
foreach($users as $user) {
echo $user;
}
?>
Code for the controller (users_controller.php)
<?php
class UsersController extends AppController {
var $name = 'Users';
function read(){
$users = $this->User->find('all');
if(isset($this->params['requested'])) {
return $users;
}
}
}
?>
Code for the model (user.php)
<?php
class User extends AppModel {
var $name = 'User';
}
?>
I've dwindled it down and discovered that $users is being set to NULL by the $this->User->find('all') statement because that statement is actually not returning any values. I know Cake is finding the table because of a typo I had earlier with the table name ('usres' instead of 'users'). I can't figure out what I'm missing or what I'm doing wrong. Would love some help. :)
The ouput is 'ArrayArrayArray' doen't means itz empty
try
foreach($users as $user) {
debug($user);
}
For me this code is meaningless.
if you want to use requestAction() use it in the proper way. It's used to call (and print) the parts of the application in the view.
Here is how to achieve the working and correct code:
Your Users class:
class Users extends AppController {
function read(){
$this->set('users', $this->User->find('all'));
$this->layout = "ajax";
$this->render();
}
}
Your read.ctp:
<ul><?php
if(isset($users)){
foreach($users as $user) {
echo '<li>'.$user.'</li>';
}
}
?></ul>
Now in your test.ctp you need to call:
<?php echo $this->requestAction(
array(
'controller'=>'users',
'action'=>'read'
)
);?>
And you will see the result in your test action as unsorted list.