View in laravel error undefined variable - php

I am a newbie in laravel and php. I cannot show the results of query in laravel. I wrote this in my program.
routes.php
Route::get('books/see', function()
{
return View::make('books.absen');
});
Route::post('books/absen','BookController#absen');
BookController.php
public function absen()
{
$ruang = Input::get('ruangn');
$results = DB::select( DB::raw("SELECT id, name, isbn, ta, tb FROM book WHERE ta = '$ruang'"));
return Redirect::to('books/see');
}
absen.blade.php
<select name="ruangn" class="form-control" method="post" action="{{URL::to('books/absen')}}">
<?php
for( $i=1; $i<19; $i++ )
{
?>
<option>
<?php echo $i;
}
?>
</option>
</select>
<input type="submit" name="submit" value="Oke" class="btn btn-info">
<table class="table table-bordered table-striped">
<thead>
<th>No</th>
<th>Name</th>
<th>ISBN</th>
<th>TA</th>
<th>TB</th>
</thead>
<tbody>
#foreach ($results as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->name}}</td>
<td>{{$value->isbn}}</td>
<td>{{$value->ta}}</td>
<td>{{$value->tb}}</td>
</tr>
#endforeach
</tbody>
</table>
And error is Undefined variable: results (View: ...\absen.blade.php) I very tired with this. Help please

Instead of redirecting, you should render the view in the absen() action. When doing the redirect the data you just selected from the db is all gone.
Try this:
public function absen()
{
$ruang = Input::get('ruangn');
$results = DB::select( DB::raw("SELECT id, name, isbn, ta, tb FROM book WHERE ta = '$ruang'"));
return View::make('books/see')->with('results', $results);
}
Also you need to check if $results exists in your view, since you also want to display it when no results are available
#if(isset($results))
<table class="table table-bordered table-striped">
<thead>
<th>No</th>
<th>Name</th>
<th>ISBN</th>
<th>TA</th>
<th>TB</th>
</thead>
<tbody>
#foreach ($results as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->name}}</td>
<td>{{$value->isbn}}</td>
<td>{{$value->ta}}</td>
<td>{{$value->tb}}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
Attention
André Daniel is very right with his comment. Your code is prone to SQL injection. You should really take a look at Laravels ORM Eloquent or the query builder. At the very minimum, use bindings for parameters:
DB::select(DB::raw("SELECT id, name, isbn, ta, tb FROM book WHERE ta = ?"), array($ruang));
Here's an example with the query builder (Thanks #AndréDaniel)
DB::table("book")->where("ta", $ruang)->get()

You have to make your view with your variable.
Here is what you should do :
routes.php
Route::get('books/see', function()
{
return View::make('books.absen');
});
Route::post('books/absen','BookController#absen');
BookController.php
public function absen()
{
$ruang = Input::get('ruangn');
$results = DB::select( DB::raw("SELECT id, name, isbn, ta, tb FROM book WHERE ta = '$ruang'"));
return View::make('books.absen')->with(array('results' => $results));
}
absen.blade.php
<select name="ruangn" class="form-control" method="post" action="{{URL::to('books/absen')}}">
<?php
for( $i=1; $i<19; $i++ )
{
?>
<option>
<?php echo $i;
}
?>
</option>
</select>
<input type="submit" name="submit" value="Oke" class="btn btn-info">
#if(isset($results))
<table class="table table-bordered table-striped">
<thead>
<th>No</th>
<th>Name</th>
<th>ISBN</th>
<th>TA</th>
<th>TB</th>
</thead>
<tbody>
#foreach ($results as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->name}}</td>
<td>{{$value->isbn}}</td>
<td>{{$value->ta}}</td>
<td>{{$value->tb}}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
By the way, you should use Laravel form functions Forms & HTML

Related

How to get the name of user through relations in Laravel

I want to implement simple teaming option to my app. I have theese tables:
users/teams /team_members/
-----/---------/------------/
id /id /id /
name /user_id /user_id /
... /... /team_id /
I have 3 models where I have defined relations:
User model:
public function teams() {
return $this->hasOne(Team::class);
}
public function teamMembers() {
return $this->hasManyThrough(Team::class, TeamMembers::class);
}
Team model:
public function user() {
return $this->belongsTo(User::class);
}
public function members() {
return $this->hasMany(TeamMember::class);
}
TeamMember model:
public function user() {
return $this->belongsTo(User::class);
}
User can only create one team, but join many teams. The problem I have is with displaying data in the frontend.
This is the query I make in the controller:
public function index(User $user) {
$teams = Team::where('user_id', auth()->user()->id )->with('members')->get();
return view('teams.index')->with('teams', $teams);
}
I have a table with the members of the current autheticated user team. I want to display the names if each member but the only thing i can do is $team->member->id and I get the ids of the users but I want to get their names too. I can do it with simple query but I dont want to make new query for every row.
This is the blade file:
#if ( $teams->count() > 0 )
#foreach ($teams as $team)
<table class="table table-striped table-sm table-responsive-lg">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Members</th>
<th scope="col">Created</th>
<th scope="col" colspan="2"></th>
</tr>
</thead>
<tbody>
<tr>
<td>{{$team->name}}</td>
<td>{{ $team->members->count('members')}} {{ Str::plural('member', $team->id) }}</td>
<td>{{ $team->created_at->diffForHumans() }}</td>
<td>
Edit
</td>
<td>
<form action="" method="POST">
#method('DELETE')
#csrf
<button class="btn btn-sm btn-danger" type="submit">Delete</button>
</form>
</td>
</tr>
</tbody>
</table>
<br>
<h5>Team members:</h5>
<table class="table table-striped table-sm">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Added</th>
</tr>
</thead>
<tbody>
#foreach ($team->members as $member)
<tr>
<td>{{ $member->user->name }}</td>
<td>{{ $member->created_at->diffForHumans() }}</td>
</tr>
#endforeach
</tbody>
</table>
#endforeach
#else
<div class="container">
<h2>You do not own a team</h2>
<p class="lead text-muted">You can create your own team or join the team of other user.</p>
<p>
Create team
Join team
</p>
</div>
#endif
When I changed $team->member->id with $member->user->name it worked. It shows the names of the users but I get N+1 queries alert and I don't know how to fix it (i tried different queries and relations but it didnt work):
You are accessing the user relationship from each member. So lets eager load that relationship as well.
public function index(User $user)
{
$teams = Team::where('user_id', auth()->user()->id )->with('members.user')->get();
return view('teams.index')->with('teams', $teams);
}

Property [id] [details] [details] [amount] does not exist on this collection instance

On my controller take data via foreach where the $upcoming->order_id is same I am checked by dd($notes) data is show but i can't get on my view php. before I am tried $note->get('amount') method it is also not working
public function index()
{ $upcomings = Booking_informations::Upcoming();
$notes = [];
foreach ($upcomings as $upcoming) {
$notes[] = Notes :: where('order_id',$upcoming->order_id)-> orderBy('id', 'ASC')->get();
};
return View('upcoming',compact('upcomings','notes',));
}
upcoming.blade.php
<table class="table table-bordered mb-0">
<tbody>
#foreach($notes as $note )
<tr>
<th scope="row">1</th>
<td>{{date('d-M-Y', strtotime($note->created_at))}}</td>
<td>{{$note->details}} </td>
<td>{{$note->amount}} </td>
</tr>
#endforeach
</tbody>
</table>
I have got answer while wrote below method have any more simple way for get results..
<table class="table table-bordered mb-0">
<thead>
<tr>
<th>#</th>
<th>Date</th>
<th>Content</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
#foreach($notes as $note )
#foreach($note as $id )
<tr>
<td scope="row">1</td>
<td>{{$id->details}} </td>
<td>{{$id->amount}} </td>
</tr>
#endforeach
#endforeach
</tbody>
</table>
Try referencing $note instead of $notes in your foreach loop and see if that works.
I have also noticed that you have named your view file View.blade.php. Should this be upcoming.blade.php to match the name you have provided in the returned view? Just a thought.

How can I rearrange this table to another away laravel eloquent relation

I used laravel hasmany relationship in my user model. I just want to convert my table like below (row to column):
To:
Here is my User model:
public function meal(){
return $this->hasMany(Meal::class);
}
My controller:
public function index()
{
$members = User::all();
return view('admin.meal')->with([
'members' => $members,
]);
}
and #blade
<table class="table table-striped #if(count($members)>7) table-responsive #endif ">
<thead>
<tr class="text-uppercase">
{{--<th class="font-w700">Date</th>--}}
#foreach($members as $member)
<th class="font-w700">{{str_limit($member->fname,5,'...')}}</th>
#endforeach
</tr>
</thead>
<tbody>
#foreach($members as $member)
<tr>
#foreach($member->meal as $meal)
<td><span class="font-w600">{{$meal->user_id}}</span></td>
#endforeach
</tr>
#endforeach
</tbody>
</table>

POST data as array

Following is my form:
<form method="POST" action="../controller/assignsubteacher.php">
<table class="table table-bordered table-striped table-hover table-condensed" id="coursedetail" >
<thead>
<tr>
<th>Sub Id</th>
<th>Sub Name</th>
<th>Teacher Name</th>
</tr>
</thead>
<tbody id="table_ajax">
</tbody>
<tfoot>
<tr>
<th>Sub Id</th>
<th>Sub Name</th>
<th>Teacher Name</th>
</tr>
</tfoot>
</table>
<div class="col-md-2">
<button type="submit" class="btn btn-primary btn-block btn-flat">Submit</button>
</div>
</form>
and table in the form is populated by following response:
while($row=mysqli_fetch_array($result))
{
$list='<select id="teacher" name="teacher'.$COUNT.'" class="form-control">
<option value = "UNKNOWN" selected="select">-SELECT-</option>';
$get_teacher="select Regno,Name from Student_Registration inner join Login on Regno=Uname where Id=2;";
$teacher_list = mysqli_query($con,$get_teacher);
while($row_Teacher=mysqli_fetch_array($teacher_list))
{
$list.='<option value="'.$row_Teacher['Regno'].'">'.$row_Teacher['Name'].'</options>';
}
$list.='</select>';
$Subject_ID=$row["SubId"].'<input type="hidden" name="SubId'.$COUNT.'" value="'.$row["SubId"].'">';
//$Subject_Name=$row["Subject_Name"].'<input type="hidden" name="SubName'.$COUNT.'" value="'.$row["Subject_Name"].'">';
$Subject_Name=$row["Subject_Name"];
$tr.='<tr>
<td>'.$Subject_ID.'</td>
<td>'.$Subject_Name.'</td>
<td>'.$list.'</td>
</tr>';
$COUNT=$COUNT+1;
}
echo $tr;
I am not able to use the posted data to insert in to database. Is there any way i can send the data as Array and retrieve it.
following is the AJAX to populate the table body:
xhr.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
console.log(xhr.responseText);
Table.innerHTML=xhr.responseText;
}
};
I was thinking of using foreach to insert data in the POST controller, but have no idea how to achieve that.
any help would be appreciated.
Use SQL insert query to do so.
while($row=mysqli_fetch_array($result))
{
$list='<select id="teacher" name="teacher'.$COUNT.'" class="form-control">
<option value = "UNKNOWN" selected="select">-SELECT-</option>';
$get_teacher="select Regno,Name from Student_Registration inner join Login on Regno=Uname where Id=2;";
$teacher_list = mysqli_query($con,$get_teacher);
while($row_Teacher=mysqli_fetch_array($teacher_list))
{
$list.='<option value="'.$row_Teacher['Regno'].'">'.$row_Teacher['Name'].'</options>';
}
$list.='</select>';
$Subject_ID=$row["SubId"].'<input type="hidden" name="SubId'.$COUNT.'" value="'.$row["SubId"].'">';
//$Subject_Name=$row["Subject_Name"].'<input type="hidden" name="SubName'.$COUNT.'" value="'.$row["Subject_Name"].'">';
$Subject_Name=$row["Subject_Name"];
$tr.='<tr>
<td>'.$Subject_ID.'</td>
<td>'.$Subject_Name.'</td>
<td>'.$list.'</td>
</tr>';
$COUNT=$COUNT+1;
$sql = "INSERT INTO `table` (column1, column2, column3) VALUES ($list, $subject_name, $tr)";
//Replace columns & table name
if(mysqli_query($con, $sql)) {
echo "Inserted";
}
}
echo $tr;

Undefined property: Illuminate\Pagination\LengthAwarePaginator::$name

I am trying to get data from my table and show it in my view and paginate this data. I received this problem and couldn2t find any solution. I did the exactly same thing in my previous project and it worked well.
here is my Controller
public function hadiBirlikteCalisalimShow (){
$users =DB::table('birlikte_calisalim')->paginate(15);
return view('admin.birliktecalisalim',compact(['users']));
}
and this is my view
<table class="table table-bordered table-hover table-striped">
<thead>
<tr>
<th>İsim</th>
<th>Email</th>
<th>Tarih</th>
<th>İstek</th>
</tr>
</thead>
<tbody>
#foreach($users as $row)
<tr>
<td>{{$users->name}}</td>
<td>{{$users->email}}</td>
<td>{{$users->tarih}}</td>
<td>{{$users->message}}</td>
</tr>
#endforeach
</tbody>
</table>
{{$users->links()}}
#foreach($users as $row)
<tr>
<td>{{$row->name}}</td>
<td>{{$row->email}}</td>
<td>{{$row->tarih}}</td>
<td>{{$row->message}}</td>
</tr>
#endforeach
should be $row->name,$row->email, etc... not $users->name, and change {{$users->links()}} to {!! $users->render() !!}

Categories