I have two different tables, answers table and question table, i need to get question ID and answer selected by a user which i have managed to retrieve, my problem is from the same form view i need to retrieve the correct answer and the point that i created in question table.From my view the first two column are retrieved from answers table, therefore i need the second two column from question table to be retrieved
please anyone who can help me, below is how i have tried to do
Here is my view:
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th scope="col">Question No</th>
<th scope="col">Answer</th>
<th scope="col">Correct Answer</th>
<th scope="col">Marks</th>
</tr>
</thead>
<tbody>
<?php $i = 1; ?>
#foreach($results as $data)
<tr>
<td>{{$i++}}</td>
<td>{{$data->question_id}}</td>
<td>{{$data->answer}}
<td>{{$data->qns_ans}}
<td>{{$data->qns_point}}
</tr>
#endforeach
</tbody>
</table>
Here is my controller
public function index()
{
$results = Answers::all();
$qns = Questions::all();
return view('test.result')
->with('results', $results)
->with('qns', $qns);
}
first you need to make relation one to many between questions and answers
check first that answers table has question_id column
then add this method to your Question Model to make relation
function answers(){
return $this->hasMany(\App\Answer::class);
}
So now you can easily from an instance of Question Model say that
$question = Question::first()->get();
dd($question->answer);
you will see now when you dump it, it will give you the answers that belongs to this question
Here is how I did to query my two tables data
This is my controller
public function index()
{
$results=Answers::all();
$qns = Questions::all();
return view('test.result')->with('results',$results)
->with('qns',$qns);
}
This is my view
<table class="table table-hover">
<thead class="thead-dark">
<tr>
<th>S/N</th>
<th scope="col">Question No</th>
<th scope="col">Answer</th>
<th scope="col">Correct Answer</th>
<th scope="col">Marks</th>
</tr>
</thead>
<tbody>
<?php $i=1; ?>
#foreach($results as $data)
<tr>
<td>{{$i++}}</td>
<td>{{$data->question_id}}</td>
<td>{{$data->answer}} </td>
<td>{{$data->question['ans']}} </td>
<td>{{$data->question['point']}}
</tr>
#endforeach
</tbody>
</table>
Here is my model
class Answers extends Model
{
protected $fillable = ['question_id','answer'];
public function question(){
return $this->belongsTo(Questions::class);
}
}
class Questions extends Model
{
protected $fillable =
['question_name','opt1','opt2','opt3',
'opt4','ans','point'];
public function answer(){
return $this->hasOne(Answer::class);
}
}
Related
I'm working with Laravel 8 to develop my project, and in this project, I have a Controller named HomeController that his this method:
public function index()
{
$questions = Question::latest()->limit(5)->get();
return view('home', compact('questions'));
}
And then I get results like this on blade:
#php
if ($questions)
{
#endphp
<table class="table table-striped table-bordered table-responsive BKoodakBold">
<thead class="thead-light">
<tr>
<th scope="col" class="forum-col" style="text-align:right;">Question</th>
<th scope="col" style="text-align:right;">Answer</th>
<th scope="col" style="text-align:right;">Rate</th>
<th scope="col" style="text-align:right;">Views</th>
</tr>
</thead>
<tbody>
#foreach($questions as $question)
<tr>
<td style="text-align:right;">
<h3 class="h5 mb-0">{{ $question->title }}</h3>
</td>
</tr>
#endforeach
</tbody>
</table>
#php
}
#endphp
As you can see I set if ($questions) to check if this variable is not empty, do the for each loop next. And if it is empty, it should not show the table thead tags.
But now the problem is it does not work out... I mean even if I have no data at the DB, it still shows table thead completely.
So what is wrong with this code? How can I properly check if the table is empty or not?
I really appreciate it if you share your idea about this... Thanks.
You're returning collection, it's always true compact('questions')
Use
if (!$questions->isEmpty()) # Laravel(in-built) way
if (!$questions->isEmpty())
// show data
else
echo "No record found.";
check with this condition
#if (isset($questions) && count($questions) > 0)
Inside Code
#endif
Check additional condition as
&& count($questions) > 0
You retrieve an elocuent collection always, even if no data received. But collection is countable, so you can check it by
if(count($collection))
if count return zero then the sentence is assume like false
The admin of the application has access to list each projects of a user. Write now I am able to list the projects but they all are listed together no matter the unique id of the URL.
// Admin form case controller
public function adminforms (Project $project){
$users = User::get();
return view('smiledesign.adminforms', compact('users', 'project'));
}
///Records controller
public function records(user $users, project $project){
$project = project::get();
$users = user::get();
return view ('/smiledesign/records' , compact( 'users','project'));
}
<table class="table">
<thead>
<tr>
<th>Dr Name</th>
<th>User Id</th>
<th>Email</th>
</tr>
</thead>
<tbody>
#foreach ($users as $user)
<tr>
<td> {{$user->name}}</td>
<td> {{$user->id}}</td>
<td> {{$user->email}}</td>
</tr>
</tbody>
#endforeach
</table>
// Records view
<table class="table table-striped table-bordered" id="table_id">
<thead>
<tr>
<th>Case Number</th>
<th>Case Form</th>
<th>Patient Name</th>
<th>Date Created</th>
<th>Status</th>
</tr>
</thead>
#foreach ($project as $project)
<tbody>
<tr>
<td> {{$project->case_number}}</td>
#if ($project->services0)
<td> {{$project->services0}}</td>
#elseif ($project->services1)
<td> {{$project->services1}}</td>
#elseif ($project->services2)
{{-- <td> {{$project->services2 . ' ' . $project->mockup0}}</td> --}}
<td> {{$project->services2 . ' ' . $project->mockup0 . ' ' . $project->mockup1}}</td>
#endif
<td> {{$project->first_name . ' ' . $project->last_name}}</td>
<td> {{$project->created_at}}</td>
<td> {{$project->concerns}}</td>
</tr>
</tbody>
#endforeach
</table>
What I wanna see is each project of a specific user when I click The link from the adminforms user. Instead, every link I go I see all projects of all users
The relationship between the projects and users should be defined in the database and in the models themselves.
Database:
In my interpretation, a user can work on multiple projects and a project can have multiple users, this would be a many to many relationship. With this conclusion, I would go for an abstracted table setup like so:
table users has an id field.
table projects has an id field.
table project_users has an id field(always required for laravel), a user_id field(foreign key to users.id) and a project_id field(foreign key to projects.id). Do not forget to add a unique key which combines user_id and project id, there is no need for duplicate definitions.
Model relationships:
Project
function users()
{
$this->belongsToMany(User::class, 'project_users', 'project_id', 'user_id');
}
User
function projects()
{
$this->belongsToMany(Project::class, 'project_users', 'user_id', 'project_id');
}
If you read this piece of documentation, it will all make sense.
Query
$users = User::with('projects')->get();
or
$projects = Project:with('users')->get();
Now every user instance has a projects collection. If they do not, then you need to add a record to the database coupling a project to that user.
Showing results
foreach($users as $user)
{
foreach($user->projects as $project)
{
echo "$user->name works on project $project->name" . PHP_EOL;
}
}
or
foreach($projects as $project)
{
foreach($project->users as $user)
{
echo "$user->name works on project $project->name" . PHP_EOL;
}
}
Sidenote
My instructions are optimized for performance. You could also just call ->projects on the $user without using the with('projects') in the query, but that will mean that you will trigger a query on the spot. As this kind of code is prone to being used in foreach statements, you could be doing queries in foreach statements which is referred to a N+1 query problem.
I'm trying to make a dashboard and I want to display the last 5 users that are registered on the site, So the most recent 5 registered people. How can I accomplish this? I need to have access to all their attributes, for instance, Name, Lastname etc.
This is my route: Route::get('/adminpanel', 'AdminController#index')->name('adminpanel');
And this is the controller:
public function index()
{
Carbon::setLocale('nl');
$tijd = Carbon::today();
$posts = Post::count();
$users = User::count();
$replies = Reply::count();
return view('admin.dashboard', compact('posts', 'users', 'replies', 'tijd'));
}
They need to be displayed in a table like this:
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td>Rainier</td>
<td>Laan</td>
<td>rainier.laan#home.nl</td>
</tr>
</tbody>
</table>
Thanks in advance
You can use take() to get specific number of records.
$users = User::orderBy('id', 'desc')->take(5)->get();
And on your view-
#foreach($users as $user)
{{$user->name}}
#endforeach
Hope it helps :)
This one will take 5 latest users.
$users = User::latest()->take(5)->get();
Well that is my problem.
This is the public function in my model
public function traerDesc(){
return $this->hasManyThrough('App\modeloDescripcionVehiculos', 'App\modeloVehiculos', 'idDescripcion', 'id', 'idVehiculo');
}
This is the controller call
$data = [
'venta' => modeloAccion::where('accion', 'venta')->with('traerVehiculo', 'traerUsuario', 'traerCliente', 'traerTransaccion', 'traerVenta', 'traerDesc')->get(),
];
return view('modulos.general.informes')->with($data);
This is my table in the blade file
<table class="table table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="text-center">Vehiculo vendido</th>
<th class="text-center">Precio de compra</th>
<th class="text-center">Precio de venta</th>
<th class="text-center">Ganancia %</th>
<th class="text-center">Usuario</th>
<th class="text-center">Cliente</th>
<th class="text-center">Fecha venta</th>
</tr>
</thead>
<tbody>
#foreach($venta as $ventas)
<tr class="text-center">
#foreach($ventas->traerDesc as $descripcion)
<td>{{$descripcion->marca}}</td>
#endforeach
<td>{{$ventas->traerVehiculo->precioCompra}}</td>
<td>{{$ventas->traerVehiculo->precioVenta}}</td>
<td>asd</td>
<td>{{$ventas->traerUsuario->nombre.' '.$ventas->traerUsuario->apellidoPaterno.' '.$ventas->traerUsuario->apellidoMaterno}}</td>
<td>asd</td>
<td>{{date('d-m-Y', strtotime($ventas->traerVenta->fechaVenta))}}</td>
</tr>
#endforeach
</tbody>
</table>
This is my table accion. As you can see . It has 3 rows where accion = venta and all of them has the same info in all the tables. But it only brings the first row rejecting the others
And the view shows only 1 marca that would be like brand in english.
Hope can make myself clear enough. Thank you
Not sure it will help, but you use eager loading method with wrong way.
Right using is:
Model::with(relations)->where(condition)->get();
Or
Model::where(condition)->get()->load(relations);
I am retrieving data from two different tables - users and phones - and sending them to a view page. My code is pulling all the columns from the phone table:
Controller.php:
public function index()
{
$alluser=User::with('phone')->get();
return view('index',compact('alluser'));
}
view.blade.php:
<table class="table table-striped table-condensed">
<thead>
<tr>
<th>Name</th>
<th>Mobile</th>
</tr>
</thead>
<tbody>
#foreach($alluser as $user)
<tr>
<td>{{$user->name}}</td>
<td>{{$user->phone}}</td>
</tr>
#endforeach
</tbody>
</table>
result:
Using ->with("phone") will return an object attached to your user accessed via ->phone, which is why your mobile column has a json object with all the phone columns in it.
If you just want to show each user's name and their phone number, change
<td>{{$user->phone}}</td>
to
<td>{{$user->phone->phone}}</td>
You could specify an additional query to select the desired columns,
User::with(['phone' => function ($query) {
$query->select(['id', 'phone']);
}])->get();
And then,
$user->phone->phone //not $user->phone