displaying an array but it return empty - laravel

Good day, i have a laravel 5.8 project and i'm having a little problem
i have this code
public function doctor_details($doctor_id){
$doctor = DB::table('doctors')->select('specification')->where('doctor_id', $doctor_id)->get>first();
$specs_data = explode(',', $doctor_specs);
$specs_array = [];
foreach ($specs_data as $doctor_spec) {
$doctor_spec_result = DB::table('specializations')->where { return explode('speciality_id'',', $doctor_spec)->get();
foreach ($doctor_spec_result as $doctor_spec_res) {
$specs_array[] = $doctor_spec_res->speciality_name;
}
}
return view ('doctor_details', compact('doctor', 'specs_array'));
}
now if i do dd($doctor_spec_result); the result is
as you can see i'm getting an empty array but if i do dd($specs_data); the result is
as you can see there's definitely a data but i can't make it work
this is my blade
<div class="row">
<div class="col-lg-12">
<h3>{{ $doctor->doctor_name }}</h3>
</div>
<div class="col-lg-12">
#foreach( $specs_array as $spec_output )
<p>{!! $spec_output !!}</p>
#endforeach
</div>
</div>

I think you are trying to get an list only containing the values of the specification field for the particular rows queried, so that you can then get the specialty_names. You can use the pluck method on the builder to do this for you. If a search by doctor_id could return more than one result:
$doctor_specs = DB::table('doctors')
->where('doctor_id', $doctor_id)
->pluck('specification')
->transform(function ($item) { return explode(',', $item); })
->flatten();
$specs_array = DB::table('specializations')
// use whereIn to find all the rows by 'specialty_id'
->whereIn('speciality_id', $doctor_specs)
->pluck('specialty_name')
->toArray();
return view ('doctor_details', compact('doctor', 'specs_array'));
Laravel 6.x Docs - Database - Query Builder - Retrieving Results pluck
Laravel 6.x Docs - Collections - Methods - transform
Laravel 6.x Docs - Collections - Methods - flatten
Update:
Though since doctor_id is a key there will only be one, we can remove the collection methods and deal with this simpler:
$doctor_specs = explode(
',',
DB::table('doctors')->where('doctor_id', $doctor_id)
->value('specification')
);
Ideally:
Or if $doctor was retrieved with all columns from the doctors table, including specification:
$doctor_specs = explode(',', $doctor->specification);

You can simplify your code using join
$doctor_spec_result = DB::table('doctors')
->select('specializations.speciality_name')
->join('specializations','specializations.speciality_id','doctors.specification')
->where('doctors.doctor_id', $doctor_id)
->get();
return view ('doctor_details', compact('doctor', 'doctor_spec_result '));

Change in this line.
$doctor_spec_result = DB::table('specializations')->where('speciality_id', $doctor_spec)->get();
you are checking the worng attribute. As you are getting specification in 0 index.
speciality_id to specification

Related

Getting Undefined property: projekti when trying to print field fetched from databse

i get this error Undefined property: projekti
when trying to print a field fetched from database
this is the code that causes the error
#foreach($dataOfProjects as $dp)
<div class="col-md-4 mt-2">
<h1 class="p-5 border border-3" >{{$dp->projekti}}</h1>
</div>
#endforeach
specifically the `{{$dp->projekti}}
this is the controller that is returning the dataOfProjects variable
public function specificClub(Request $request,$id){
$data = Clubs::find($id);
$dataOfProjects = DB::table('projektet') -> where('klubi', '=',$id);
$teachers = DB::table('mesuesit')->join('klubet','klubet.id','=','mesuesit.klubi_ne_kujdesari')->select('mesuesit.emri')->where('klubet.emri','=','rrobotike')->get();//Per te mare emrin e mesuesve te ketij klubi
return view('specificClub', compact('data','dataOfProjects','teachers'));
}
This is the table klubet
and this is the table projektet
Add ->get() for multiple results or ->first() for one result to this line:
$dataOfProjects = DB::table('projektet') -> where('klubi', '=',$id);
From:
$dataOfProjects = DB::table('projektet') -> where('klubi', '=',$id);
To (for multiple results):
$dataOfProjects = DB::table('projektet')->where('klubi', '=',$id)->get();
To (for one results):
$dataOfProjects = DB::table('projektet')->where('klubi', '=',$id)->first();

How to Mass Update(Edit) in Laravel Query Builder?

Hello guys I am trying to do a mass update for my application using a checkbox but when I try to update it will just update the 1st student id(I tried to select other students the update does not work). Could you give some insights or concrete examples I can follow?
This is what I have tried so far
public function changeSched()
{
DB::table('class_list')
->whereIn('id', $this->selectedStudents)
->update(['section' => $this->selectedSched]);
}
For my checkbox
#foreach($classlist as $stud)
<tr>
<th class="bg-white py-5 px-5">
<div class="items-center">
<input type="checkbox" wire:model="selectedStudents.{{ $stud->id }}"/>
</div>
</th>
I do not see any error in your update statement so it should update all the records provided by the query (mass updates are documented here).
I guess the error is before, when you set $this->selectedStudents. Are you sure that this variable contains a simple array (not an associative array) with all the selected IDs?
You should do the following:
Debug the $this->selectedStudents variable to ensure its content is correct
Temporarily replace it by a hardcoded value [1, 2, 3] to ensure that the rest of your code is appropriately working
UPDATE
To convert $this->selectedStudents in the right format, you can do the following:
$selectedIds = [];
foreach ($this->selectedStudents as $id => $isSelected){
if ($isSelected) {
$selectedIds[] = $id;
}
}
DB::table('class_list')
->whereIn('id', $selectedIds)
->update(['section' => $this->selectedSched]);

How to get Unique value in blade file laravel

I want to fetch unique value for filters of all products.
My db structure as follows
id Product category_id format attribute
1 demo1 5 HD test1
2 demmo2 4 SD test3
3 demmo3 4 HD test2
4 demmo4 3 HD test3
I want add filters of format and attribute in product page. But in that HD comming 3 times. I want to display that one only.
I am not getting how to display only single time.
Below is my controller code:
$item = Item::where('active_status', 1)->where('status', "1");
$data['item_count'] = $item;
$data['item'] = $item->paginate(20);
return view('frontend.pages.explore', compact('data'));
Below is blade file
<div class="filter-btn">
#foreach($data['item'] as $resolution)
<a class="btn btn-white-outline display-4" href="">{{array_unique($resolution->format)}}</a>
#endforeach
</div>
I am not getting how to display unique value only. Anyone have idea then let me know
since you are paginating your data, your "first page" might not have all the formats, so you have to do another query to your database:
$formats = DB::table('items')->select('format')->distinct()->get()
...
view(..., compact('data', 'formats'))
in the blade table:
#foreach($formats as $resolution)
<a class="btn btn-white-outline display-4" href="">{{$resolution->format}}</a>
#endforeach
If I am correct about your query, then you need to use groupby to list the items in your controller.
$items = Item::groupBy('format')->get();
The solution would be to create a sperate model for Formatand relationship between it and Product or whatever model that needs format , then fetch formats from its table and apply eager load .
this may look longer than your solution , but this is standards shoiuld be taken for vrious reasons :
less sql queries
more flexibility and options regarding our new table
better and less code to crud format
single source for change
less database data and faster load
...
Product.php
public function format(){
return $this->belongsTo(Format::class);
}
Format.php
public function products(){
return $this->hasMany(Product::class);
}
Usage
in controller
// get all formts eager loaded with products
$formats = Format::with('products')->get();
//get all products
$product = Format::latest()->paginate(20);
return view('frontend.pages.explore', compact( 'products' ,'formats'));
in your view
// all prodcuts
#foreach($formats as $format)
<a class="btn btn-white-outline display-4" href="">{{$format->name}}</a>
#endforeach
// in filter ( at clicking ) no additional query
#foreach($format->products as $product)
...
#endforeach

Laravel 5.3 Method currentpage does not exist

My Pagination is not working in latest version of laravel 5.3,
I have used Paginate Method and i just wanted to know why current page method is not exist.
public function getIndex($author =null)
{
if(!is_null($author)){
$quote_author = Author::where('name', $author)->first();
if($quote_author){
$quotes = $quote_author->quotes()->orderBy('created_at','desc')->paginate(6);
}
else{
$quotes = Quote::orderBy('created_at','desc')->paginate(6);
}
return view('index',['quotes' => $quotes]);
}
$quotes = Quote::all();
return view('index',['quotes' => $quotes]);
}
<div class="pagination">
#if($quotes->currentpage() !==1)
<span class="fa fa-caret-left"></span>
#endif
#if($quotes->currentpage() !== $quotes->lastpage() && $quotes->hasPages())
<span class="fa fa-caret-right"></span>
#endif
</div>
The method name is currentPage() with a capital P.
You can learn about the other paginator methods in the documentation.
Also, in the instance the $author is null, you fall back to Quote::all() which is not paginated. Convert that to Quote::paginate(6) so that $quotes will always be an instance of a paginator.
Method name currentPage() P must be in capital letter
currentPage() is a method on the Paginator class. When you use all(), you get an instance of Collection.
What I think you want is $quotes = Quote::paginate($n); where $n is the number of results you want per page.

Checking First Character of a String with Blade Template

Right now, in my controller, I'm passing some alphabetized data to my explore view.
public function browse()
{
return View::make('explore')
->with('artists', Artist::orderBy('artist', 'ASC')->get());
}
And then in the view, I'm using Blade to loop through that information.
<ul>
#foreach($artists as $artist)
<li>{{ $artist->artist }}</li>
#endforeach
</ul>
I want to run a conditional that checks the first letter of each artist so I can further group the data under the correct starting letter. How would you do that with Blade? I saw the helper "starts_with" but I'm not quite sure how to implement that into a conditional.
This logic really belongs somewhere other than the view/template layer. A View Composer could be a better location, or perhaps even a model method to return your data separated by starting letter - thus returning a hash of arrays containing artists under each letter.
Example code:
class Artist extends Eloquent
{
public static function allByFirstCharacter()
{
$artists = Artist::orderBy('artist', 'ASC')->get();
return $artists->reduce(function($sortedArtists, $artist) {
$firstChar = $artist->artist[0];
if (!isset($sortedArtists[$firstChar])) {
$sortedArtists[$firstChar] = [];
}
$sortedArtists[$firstChar][] = $artist;
return $sortedArtists;
}, []);
}
}
// Controller
$sortedArtists = Artist::allByFirstCharacter(); // Then pass it to the view
// In view
#foreach ($sortedArtists as $letter => $artists)
<!-- Some menu item or something similar here -->
#foreach ($artist as $artist)
<!-- Print out details of artist -->
#endforeach
#endforeach
Note that this example only fills in existing first characters. If you'd like to have all characters in the alphabet/numbers you'd need to prepopulate the hash and then reduce it.

Resources