How to load multiple number of pages dynamically in laravel? - laravel

I have this table instruction_title and this table instruction_body. One instruction title can have one or many instruction body. In my resource controller instController the index funtion is showing the list of instruction title, onclick it is going to the show function and showing which bodies it has.
If the instruction id is 25, it is going to /instructions/25.
But I need something like /instructions/25/Body1 with a next button if it has body2 and on next it will go to /instructions/25/Body2 and go on.

You can do something like this :
in your routes :
Route::get('/instructions/{titleId}/{bodyName}', 'instController#index')->name('titleIndex');
And in your blade :
#php
$currentBodyId = $next = \DB::table('instruction_body')
->orderBy('id', 'asc')->select('id')
->first();
$next = \DB::table('instruction_body')
->where('titleId', $YOUR_TITLE_ID)
->where('id', '>', $currentBodyId)
->sortBy('id')
->first();
$nextUrl = ($next !== null) ? $next->YOUR_BODY_NAME : '#' ;
#endphp
And in your next button in blade:
#if ($nextUrl != '#')
<a href="{{ route('titleIndex', ['bodyName' => $nextUrl]) }}">
Next
</a>
#endif

#behnam's has some bad practice. Never have logic to query data in the presentation layer! That was the reason why MVC architecture was built.
But what you could do is attach a relationship one-to-many for both Models:
Read here
Then you can fetch bodies that belongs to a specific title like:
//in your controller
$datas = Title::find(25)->with('bodies');
Then you can loop through it to get the id.

Related

Undefined variable error when I tried to display count in the dashboard page

I try to display count for pending applicants in my dashboard page. However, it shows error like below.
the undefined variable $pending is my another function called applicantPending() to display the info of pending applicants and it run smoothly. It is also shown in my dashboard page.
However after I try to display count in the other function called applicantTotal() , it is undefined.
The functions in ApplicantController;
public function applicantPending()
{
$pending = DB::table('applicants')
->where ('status', 'like', 'Pending')
->get();
return view('admin.admin-home', ["pending" => $pending]);
}
//to display count
public function applicantTotal()
{
$count = DB::table('applicants')
->where ('status', 'like', 'Pending')
->count();
return view('admin.admin-home', compact('count'));
}
web.php
Route::get('index', [ApplicantController::class, 'applicantPending']);
Route::get('index', [ApplicantController::class, 'applicantTotal']);
To display count in the admin-home.blade.php (dashboard),
<div class="h5 mb-0 mr-3 font-weight-bold text-gray-800">{{$count}}</div>
To display info' of each applicant in the admin-home.blade.php (dashboard).
#foreach ($pending as $item)
<table class="table">
<tbody>
<tr>
<td>{{$item->nama}}</td>
<td>{{$item->noPhone}}</td>
<td>{{$item->email}}</td>
<td style="color: crimson">{{$item->status}} </td>
</tr>
</tbody>
</table>
#endforeach
I think there's something wrong in my web.php.
You have two routes with the same name going to two different methods in your controller. Laravel is only going to send the request to one of those routes. What this means is that only one of the methods is called to supply information back to the admin.admin-home view.
So, because you reference BOTH variables, $count and $pending on the admin-home view, and it is only getting one method called (thus supplying only $count and NOT $pending), the view looks for both variables, but it only has one. Thus, the error $pending is undefined -- it never gets to the applicantPending() method to supply the variable to the view.
To Fix, remove the bottom route from web.php. Then, combine the methods into one, and supply both variables back to the view.
Something like this:
public function applicantPending(){
$pending=DB::table('applicants')
-> where ('status', 'like', 'Pending')
-> get();
$count=DB::table('applicants')
-> where ('status', 'like', 'Pending')
-> count();
return view('admin.admin-home', compact('pending', 'count'));
}

Retrieving data from table with multiple row

I am currently having trouble retrieving the data from a table based on their id. Here the $content will pluck multiple ids from the table. When retrieving the ModuleDevelopment table, it retrieves all of the data without organizing by their id. What should I do to separate the status based on their id?
$content = ModuleListing::where('sme_role', $selectedRole)
->get()->pluck('mit_id');
$stats = ModuleDevelopment::whereIn('mdev_mit_id', $content)
->orderBY('mdev_mit_id','desc')->get()->pluck('mdev_status');
result of $stats
result of $content
Just an update of the coding I previously had trouble with, the main issue was to organize the status of each module development based on their ID,
therefore, the code I had was
this was at my controller:
$moduleDev = ModuleDevelopment::select('mdev_mit_id','mdv_sts')
->whereIn('mdev_mit_id', $content)
->orderBY('mdev_mit_id', 'asc')
->get();
and this is what was on my blade.php
#foreach($moduleDev as $modDev)
#if($listing->mit_id == $modDev->mdev_mit_id)
#if($modDev->mdv_sts == 'complete' )
{{'Complete'}}
#elseif($modDev->mdv_sts == 'incomplete')
{{'Incomplete'}}
#endif
#endif
#endforeach
I hope it is right and helpful for other people.

Only display selected fields to the view using Laravel Query Builder

I have quotes I am displaying to the screen one at a time upon each page refresh. The data is displaying fine from the DB; the issue is that I am getting the (id) display on the screen as well when I only need the quote and author name. How do I "exclude" the id field from displaying in my view?
Controller
public function index()
{
$quotes = DB::table('quotes')->inRandomOrder()->first();
return view('home', compact('quotes'));
}
Blade/View
#foreach($quotes as $quote)
<p>{{$quote}}</p>
#endforeach
Edit based on the comment of #devk:
Generally answers OPs question, but the code here (and in OPs post)
doesn't exactly make sense. The ->first() will return null or a single
quote, but the #foreach(..) is used like it's a collection of quotes
you can do the query like this:
$quote = DB::table('quotes')->select('quote', 'author')->inRandomOrder()->first();
replacing 'quote' and 'author' by the fields names in your table.
And return te quote:
return view('home', compact('quote'));
And in blade show the object:
<p>{{$quote}}</p>
or show the fields:
#isset($quote)
// $quote is defined and is not null...
<p>{{$quote->quote}}</p>
<small>{{$quote->author}}</small>
#endisset
If you want to show multiple quotes, do the query like this:
$quotes = DB::table('quotes')->select('quote', 'author')->inRandomOrder()->get();
or
$quotes = DB::table('quotes')->select('quote', 'author')->inRandomOrder()->take(5)->get();
And in blade you can loop through the collection:
#foreach($quotes as $quote)
<p>{{$quote}}</p>
#endforeach
or
#foreach($quotes as $quote)
<p>{{$quote->quote}}</p>
<small>{{$quote->author}}</small>
#endforeach

How to write for Each Loop in Laravel

Laravel Code to connect with Database
In $response i have array of items. These items may or may not be present in dishOrder table.
I have to Count the no of orders of each item which is under itemQuantity Column in dishOrder Table.
How to write For Loop for this.?
Do you want to loop in blade or in the backend? This is how you generally do loops on arrays / collections.
In backend:
foreach( $response as $item ) {
// do stuff with $item
}
If you want to display the count in the frontend
#foreach( $response as $item )
<h1>{{ $item->title }}</h1> <!-- if you have a title -->
<h2>{{ count( $item->innerArray ) }}</h2>
<h3>{{ $item->itemQuantity }}</h3>
#endforeach
However to be more specific regarding your problem you will need to provide more information or even better the code of what you already tried
As far as I understand you want to create an SQL-Query which looks like this in MySQL:
SELECT sum(itemQuantity), itemName FROM dishOrder where itemName in ('soup','pizza','burger');
Laravel has the whereIn method to create such a query. Example from the manual (https://laravel.com/docs/5.2/queries):
$users = DB::table('users')
->whereIn('id', [1, 2, 3])
->get();

htmlentities() expects parameter 1 to be string, array given? Laravel

I've found many question realated to my problem but couldn't found an answer yet. It's about my foreach loop in my blade.
I want to print all product-names in my blade but I couln't figure out how to do that.
thats how I'm getting the products:
--- current code:
// controller
$id_array = Input::get('id');
$products= Products::whereIn('id', $id_array)->get();
$product_name = [];
foreach($products as $arr)
{
$product_name= $arr->lists('name');
}
returning $product_name gives me this as a output:
["football","cola","idontknow","freshunicorn","dummy-data"]
In my blade is just a simple:
#foreach($products as $product)
{{ $product}}
#endforeach
Error: htmlentities() expects parameter 1 to be string, array given
Thanks for your help and time.
It seems you are getting an object in an array in an array.
Like this:
array(
array(
object
)
)
It happens because you use the get() function to retrieve you model. The get() function always "wants" to retrieve multiple models. Instead you will have to use the first() function.
Like this:
foreach($id_array as $arr)
{
$want2editarray[] = Product::where('id', $arr)->first();
}
Hope it helps :)
Edit after #Wellno comment
That's probably because Product::where('id', $arr)->first(); returns null because it did not find anything.
I forgot to add a check after the retrieving of the product.
This can be done like this:
foreach($id_array as $arr)
{
// First try to get model from database
$product = Product::where('id', $arr)->first();
// If $product insert into array
if ($product) $want2editarray[] = $product;
}
Why do you use loop with IDs? You can find all products by IDs:
$products = Product::whereIn('id', $id_array)->get();
And then use $products in the blade template
#foreach($products as $product)
{{ $product->name }}
#endforeach
try to use Model/Eloquent to fetch data.
View should only display the data and not fetching directly from DB or do heavy calculations.

Resources