Show function at controller not getting value from index - laravel

I really get here to bother you only when I can't find an answer.
I don't know Why I get a null at show function at productoservicioevento. It's the same code that I use at grupo and there I get the id...
index at module productoservicioevento
#foreach($productoservicioeventos as $productoservicioevento)
<tr>
<td> {{ $productoservicioevento->idProductoServicioEvento }}></td>
<!--<td> {{ $productoservicioevento->strConcepto }}></td>-->
<td>{{ $productoservicioevento->dcmPrecio }}</td>
<td>{{ $productoservicioevento->evento->strNombreEvento }}</td>
</tr>
#endforeach
show function at productoservicioeventocontroller
public function show(ProductoServicioEvento $productoServicioEvento)
{
//
//$productoServicioEvento = ProductoServicioEvento::all();
dd($productoServicioEvento);
dd($productoServicioEvento->idProductoServicioEvento);
$productoServicioEvento = ProductoServicioEvento::find($productoServicioEvento->idProductoServicioEvento);
I get null when click at index
The module from productoservicioevento was actually copied from
index at grupo
#foreach($productoservicioeventos as $productoservicioevento)
<tr>
<td> {{ $productoservicioevento->idProductoServicioEvento }}></td>
<!--<td> {{ $productoservicioevento->strConcepto }}></td>-->
<td>{{ $productoservicioevento->dcmPrecio }}</td>
<td>{{ $productoservicioevento->evento->strNombreEvento }}</td>
</tr>
#endforeach
Everything is Ok at gruposcontroller, show function
public function show(grupo $grupo)
{
//
dd($grupo);
$grupo = grupo::find($grupo->idGrupo);
Everything goes fine there...
Te routes, Totally basic.
Route::resource('lockers','LockersController');
Route::resource('escuelas','EscuelasController');
Route::resource('grupos','GruposController');
Route::resource('productoservicioeventos','ProductoServicioEventosController');
Route::resource('horarioperiodicos','HorarioPeriodicosController');
Route::resource('eventos','EventosController');
I changed this.
public function show(ProductoServicioEvento $productoServicioEvento)
{
//
//$productoServicioEvento = ProductoServicioEvento::all();
dd($productoServicioEvento);
dd($productoServicioEvento->idProductoServicioEvento);
$productoServicioEvento = ProductoServicioEvento::find($productoServicioEvento->idProductoServicioEvento);
For this
public function show( $producto)
{
//
//dd($producto);
/*dd($productoServicioEvento->idProductoServicioEvento);*/
$productoServicioEvento = null;
$productoServicioEvento = ProductoServicioEvento::find($producto);
Now I'm able to work but don't know the reason why I had to change model to id...
So I'm totally stuck, please help.
Thanks in advance.

Related

How to get the list of client related through the HasManyThrough relationship

I have these 3 tables:
clients
id - integer
name - string
projects
id - integer
client_id - integer
name - string
tasks
id - integer
project_id - integer
name - string
related through the HasManyThrough relationship.
In the client table I have a column relating to the number of tasks relating to the projects of that specific client.
I want that when I click on the number of tasks, I am redirected to the view of the client related tasks. While when I click it shows me all the tasks, but I want, as already specified, the tasks related to the projects of that specific client.
How can I solve this problem?
VIEW:
<tr>
<th class="id">ID</th>
<th class="">Name</th>
<th class="">Task</th>
</tr>
#foreach ($clients as $client)
<tr>
<td>{{ $client->id }}</td>
<td>{{ $client->name }}</td>
<td>
<a href="{{route('task.index'}" class="link-primary">{{
$client->tasks_count }}
</a>
</td>
#endforeach
TaskController:
public function index()
{
$tasks = Task::all();
//dd($tasks);
return view('task.index', compact('tasks'));
}
Create new route:
Route::get('/client/{client}/tasks', ['as' => 'client.tasks', 'uses' => 'ClientController#tasks'])->name('client.tasks');
Add something like this to your view:
//Not sure if that is a right syntax to bind the id in the route, need to verify
<a href="{{ route('client.tasks', [$client->id]) }}" class="link-primary">
{{ $client->tasks_count }}
</a>
Or:
//Route
Route::get('/client/{client}/tasks', [ClientController::class, 'tasks'])->name('client.tasks');
//and view
<a href="{{ URL::to('/client/' . $client->id . '/tasks') }}" class="link-primary">
{{ $client->tasks_count }}
</a>
And controller:
public function tasks(Client $client)
{
$tasks = $client->tasks;
//return your view with tasks associated with this client
}
As you have written
$tasks = Task::all();
All tasks!
You need to pass along the id of the client with the request, preferably with route model binding so that you get a client instance in the controller. Then you can load the tasks or the projects with tasks below them
public function index(Client $client)
{
$tasks = $client->tasks()->get();
//dd($tasks);
return view('task.index', compact('tasks'));
}
or with projects
{
$projects = $client->projects()->with('tasks')->get();
return view('task.index', compact('projects'));
}
In this second example, you get a collection of projects with the tasks inside, so you can then show a list of projects and a list of tasks for that project

How to count rows in another table which contains foreign key and loop it foreach collection instance?

I have two tables which are connected each other.
their structures look like this.
modul_table
id | user_id | title | slug | platform
lecture_table
id | user_id | modul_id | title | content
I want to count how many rows in lecture_table where its modul_id = $id.
So this $id are the ids of my collection which retrieved from controller.
here's my controller:
public function index()
{
$modul = Modul::get();
$arr_lecture = [];
foreach ($modul as $key) {
$lecture = Lecture::where('modul_id', $key->id)->count();
array_push($arr_lecture, $lecture);
}
return view('func.lihatModul', compact('modul', 'arr_lecture'));
}
and in my view :
#php $i = 0 #endphp
#foreach($modul as $key)
<tr>
<td>{{$key->id}}</td>
<td>{{$key->title}}</td>
<td>{{substr($key->desc, 0, 75)}}</td>
<td>{{ $arr_lecture[$i++] }}</td>
#endforeach
and the result:
all my codes are working well, but is there any way just by using query builder or a function to do the same approach?
If you have defined the lectures relationship in your Modul model like so:
# Modul.php
public function lectures()
{
return $this->hasMany(Lecture::class);
}
Then, you could simple do this in your ModulController:
public function index()
{
$moduls = Modul::withCount('lectures')->get();
// ^^^^^^^^^^^^^^^^^^^^
return view('func.lihatModul')->withModuls($moduls);
} ^^^^^^^^^^^^^^^^^^^^^
This will add the lectures_count attribute to each $modul, so you can access it in your Blade view like this:
#foreach($moduls as $modul)
<tr>
<td>{{ $modul->id }}</td>
<td>{{ $modul->title }}</td>
<td>{{ substr($modul->desc, 0, 75) }}</td>
<td>{{ $modul->lectures_count }}</td> // <-----
#endforeach
Check the docs regarding this section: Counting related models.
If you have the one-to-many relationships set up properly as it explains in the docs https://laravel.com/docs/master/eloquent-relationships#one-to-many
So in your Modul.php model
public function lectures()
{
return $this->hasMany('App\Lecture');
}
and in your Lecture.php model
public function modul()
{
return $this->belongsTo('App\Modul');
}
then you should just be able to do
$modul = Modul::with('lectures')->get();
Then in blade
#foreach($modul as $key)
<tr>
<td>{{$key->id}}</td>
<td>{{$key->title}}</td>
<td>{{substr($key->desc, 0, 75)}}</td>
<td>{{ $key->lectures->count() }}</td>
#endforeach
If u want to leave your variant u don't need to use array_push better store value in array with $key
public function index()
{
$modul = Modul::get();
$arr_lecture = [];
foreach ($modul as $key) {
$lecture = Lecture::where('modul_id', $key->id)->count();
$arr_lecture[$key->id] = $lecture;
}
return view('func.lihatModul', compact('modul', 'arr_lecture'));
}
now $arr_lecture will have correct keys. Next in view
#foreach($modul as $key)
<tr>
<td>{{$key->id}}</td>
<td>{{$key->title}}</td>
<td>{{substr($key->desc, 0, 75)}}</td>
<td>{{ count($arr_lecture[key->id]) }}</td>
#endforeach
but Kennys version is really good

Unexpected data \r\n with Carbon laravel

I'm trying to get all of the students from a table using "Student::all()". I don't even have carbon in this function. It's not getting students by date or anything. When i try to run the function, I get the error shown in the picture. It's pointing to a carbon file in the vendor folder but I don't know what to change. The data from the database pulls fine in every other function of the program, just not this one exact thing. When I die/dump my function call,I get the students list just fine. Something is simply irritating Carbon for no apparent reason. If I use a carbon parameter, it works, the function doesn't stall, but it does not return the correct data even though the field in the database holds that info. Why would a line break be causing this issue?
This function does not produce the error, but it does not result in the correct data.
public function exportRoster(){
$students = Student::whereDate('updated_at', Carbon::today())->get();
$pdf = PDF::loadView('printRoster', compact('students'), [], ['orientation' => 'L']);
return $pdf->stream('roster'.Carbon::today().'.pdf');
}
This function would obviously have the right data, but it produces the error of "Unexpected data".
public function exportRoster(){
$students = Student::all();
$pdf = PDF::loadView('printRoster', compact('students'), [], ['orientation' => 'L']);
return $pdf->stream('roster.pdf');
}
Just in case it helps, i've also included a screen shot of my database
Here is the table i'm using with my students variable in the printRoster view. If I remove this table, all queries work.
<table style="width:100%;">
<tr>
<th align = "left">Student Name</th>
<th align = "left">Student ID</th>
<th align = "left">District</th>
<th align = "left">School</th>
<th align = "left">Test Date/Time</th>
<th align = "left">Vision</th>
<th align = "left">Color</th>
<th>Nurse</th>
</tr>
#foreach($students as $student)
#php
$grade = array('20/40', '20/50', '20/60', '20/80', '20/100', '20/200', '20/400');
#endphp
<tr>
<td>{{$student->fname.' '.$student->lname}}</td>
<td>{{$student->student_number}}</td>
<td>{{$student->district}}</td>
<td>{{$student->school}}</td>
<td>{{$student->updated_at}}</td>
#if(in_array($student->od_dist, $grade) || in_array($student->os_dist, $grade) || in_array($student->ou_dist, $grade))
<td>Failed</td>
#else
<td>
Passed
</td>
#endif
<td>{{$student->ou_color}}</td>
<td>{{$student->nurse}}</td>
</tr>
#endforeach
</table>
The updated_at column is a timestamp so maybe you need to convert it in a raw date in order to show it. Please try if it works
#foreach($students as $student)
#php
$grade = array('20/40', '20/50', '20/60', '20/80', '20/100', '20/200', '20/400');
#endphp
<tr>
<td>{{$student->fname.' '.$student->lname}}</td>
<td>{{$student->student_number}}</td>
<td>{{$student->district}}</td>
<td>{{$student->school}}</td>
<td>{{date('Y-m-d H:i:s', strtotime($student->updated_at))}}</td>
#if(in_array($student->od_dist, $grade) || in_array($student->os_dist, $grade) || in_array($student->ou_dist, $grade))
<td>Failed</td>
#else
<td>
Passed
</td>
#endif
<td>{{$student->ou_color}}</td>
<td>{{$student->nurse}}</td>
</tr>
#endforeach
Edit
public function exportRoster(){
$students = Student::all();
$pdf = PDF::loadView('printRoster', $students);
$pdf->setPaper('A4', 'landscape');
return $pdf->stream('roster.pdf');
}

how to display search result in laravel

i can not show search result using laravel. below is the code for route, controller and views:
route:
Route::resource('search', 'SearchController');
controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Order;
use Redirect;
use Auth;
use DB;
class SearchController extends Controller
{
public function index(Request $request)
{
$order = Order::all();
return view(search.index', compact(search));
}
public function search(Request $request)
{
$search = $request->search;
$order = DB::table('order')
->where('custName','like',"%".$search."%");
return view('search.index',compact('search'));
}
}
view
<form action="search" method="GET">
<input type="text" name="custName" class="form-control" <br>
<button type="submit" class="btn btn-primary">SEARCH</button>
</div>
</div>
<table class="table table-bordered" width="500">
<tr>
<td><font color="white">RESULT :</font></td>
</tr>
#foreach($order as $order)
<tr>
<td>{{ $order->custName }}</td>
<td>{{ $order->orderStatus }}</td>
</tr>
#endforeach
</table>
directory location
c:/xampp/htdocs/web/resources/views/search/index.blade.php
show error
Undefined variable: order (View: c:\xampp\htdocs\web\resources\views\search\index.blade.php)
above is my code to search record in the database. but the result always undefined variable.
how to display the searched result using code above. thank you
In your Controller search method, assign search result to $orders
$orders = DB::table('order')
->where('custName','like',"%".$search."%");
then send it to the view:
return view('search.index',compact('orders'));
and in the view do this:
#foreach($orders as $order)
<tr>
<td>{{ $order->custName }}</td>
<td>{{ $order->orderStatus }}</td>
</tr>
#endforeach
It will solve your problem.
There are some issues with the code you have shared, I try to tell the ones I see.
there is a misspelling in Route::resource where instead of search you coded seearch
as for search method it is not used anywhere by the route you provided. You can see more details on Route::resource for methods and views at this question
now considering that you are loading index.blade.php from the public function index method, the usage of compact is troubled. At this page, you can see how compact and with are different and how to use it. The main problem here is that you are not actually passing the order to your view at all.
The last but not least, it is good practice to name items having a collection of values plurally. For example here the order should change to orders. This would prevent the misuse of it in foreach. In your foreach, the name of the iterating array and the temp variable keeping the data should be different, or otherwise, they would have conflict. Here you have 2 variables called order in the same scope.
for instance i have records :
a
aa
aaa
b
c
d
e
the code show all record no1 until no7.
but now its solved i fixed the code in my controller in index() section as below
public function index()
{
return view('search.index', compact('order'));
}
public function search(Request $request)
{
$search = $request->search;
$order = DB::table('order')->where('custName', 'like', "%".$search."%")->get();
return view('search.result', compact('order'));
}

Laravel 5.1 - compare Carbon dates

Here I need to check does auction for article in my app is live so I write in Article model:
public function scopeCloseauction($query){
$query->where(Carbon::parse('to')->subDays('auction_end'),'>',Carbon::now());
}
and view I have:
#if ($article->Closeauction())
<td>
auction is live
</td>
#else
<td>
auction is closed
</td>
#endif
but I have a problem becouse I got error:
UPDATE:
I also try:
in model to add function:
public function isLive($to,$auction_end) {
$first = Carbon::create($to).subDays($auction_end);
$second = Carbon::now();
return ($first->lte($second));
}
and in view:
#if ($article->isLive($article->to,$article->auction_end))
<td>
live
</td>
#else
<td>
closed
</td>
#endif
but now give me this error:
ErrorException in Carbon.php line 425: Unexpected data found.
Unexpected data found. Unexpected data found. Trailing data (View:
C:\wamp\www\project\resources\views\articles\index.blade.php)
You can do something add such function into your Article model:
public function isLive()
{
$first = Carbon::parse($this->to)->subDays($this->auction_end);
$second = Carbon::now();
return $first->lte($second);
}
and now in your view you can use:
#if ($article->isLive())
<td>
live
</td>
#else
<td>
closed
</td>
#endif
I think your problem is here : Carbon::parse('to'). What do you want to do here ? the Carbon::parse method try to convert a string date into a Carbon date. See the doc. I dont think that Carbon can parse the string 'to'. If you want to check the diff between dates, you should have a look to the appropriated methods like diffInDays.

Resources