invalid argument supplied for foreach() laravel relationship - php

I'm trying to show a book's comments by ISBN (book table's PK) and I get the following error:
Invalid argument supplied for foreach
I'm using Laravel relationship and a foreach to get the records from the following query, in a Helper class:
function getCommentsByISBN($data)
{
foreach (Book::where("ISBN", $data)->get() as $comments) {
return $comments->comments;
}
}
And here's my Book model, comment relationship:
public function comments()
{
return $this->hasMany(Comment::class, "ISBN", "ISBN");
}
And here's the view where I show the comments:
#foreach(getCommentsByISBN(session("isbn")) as $comment)
<div class="form-group">
<h3>
{{ getUserWhoPostedComment($comment->email) }}
</h3>
<p>
{{ $comment->commentary }}
</p>
#if(Session::has("username") && isAdmin(session("username")))
<button type="button" onclick="openModal('{{$comment->commentary}}')"
name="warningButton" class="btn btn-warning" data-toggle="modal"
data-target="#modalWarning">
<i class="fas fa-exclamation-circle"></i>
</button>
#endif
<hr>
<span>
Hace: {{ getTimeWherePostedComment($comment->publicated_at) }}
</span>
</div>
#endforeach
Thanks in advance!

I think you helper returns void because no book was found with that ISBN.
I think it should look like this btw
function getCommentsByISBN($isbn)
{
if ($book = Book::where("ISBN", $isbn)->first()) {
return $book->comments;
}
}
and in your blade your top should look like
#php
$comments = getCommentsByISBN(session("isbn")) ?: [];
#endphp
#foreach($comments as $comment)
<div class="form-group">
/// Rest of the code

Related

How can a voyager link for downloading the file uploaded by voyager be defined in a cutome view?

I have tried to code a cutome view in which i would be able to code an html tag to directly download the file which was uploaded before with voyager admin panel. here is my route
Route::get('/download/{research}',[App\Http\Controllers\ResearchController::class, 'download'])->name('download');
here is the html tag:
Download
help me in the controller bellow
public function download(Research $research)
{
}
I've worked through this question all night long and found out this
helpful.
Then I solved it like this:
Controller
public function home()
{
$researches = Research::all();
foreach ($researches as $research){
$download_links[] = json_decode($research->attachment);
}
$departments = Department::all();
$role_id = \TCG\Voyager\Models\Role::all()->where('name','=','student')->first()->id;
$students = User::all()->where('role_id','=',$role_id);
return view('Research.home', compact('researches','departments','students','download_links'));
}
View
{{ $i=0 }}
#foreach($researches as $research)
<div class="row">
<div class="col-md-10">
<button data-toggle="collapse" data-target="#demo{{ $research->id }}" class="btn border text-start form-control" title="click to read abstract">[ {{ ucwords($research->title) }} ] By: {{ $research->user->name }} #if($research->user->student != null) {{ $research->user->student->last_name }} #else {{ $research->user->employee->last_name }}#endif</button>
</div>
<div class="col">
Download
</div>
</div>
<div id="demo{{ $research->id }}" class="collapse row border">
<div class="col-md-12 ">{!! $research->description !!}</div>
</div>
#endforeach
and now is working properly.
public function download($id) {
$research= Research::where('id', $id)->firstOrFail();
$pathToFile = storage_path('fileName' . $research->file);
return response()->download($pathToFile);
}

Trying to get property of non-object error in laravel 5.4

I'm trying register in my app but this Error happened and I don't know why.
and my post.blade.php file has this code:
<div class="blog-post">
<h2 class="blog-post-title">
<a href="/posts/{{$post->id}}">
{{$post->title}}
</a>
</h2>
<p class="blog-post-meta">
{{$post->user->name }}
{{$post->created_at->toFormattedDateString()}}
</p>
{{$post->body}}
postcontroller has this code:
public function index()
{
$posts=Post::latest()->get();
return view('posts.index',compact('posts'));
}
and index file is:
#foreach($posts as $post)
#include('posts.post')
#endforeach
<nav class="blog-pagination">
<a class="btn btn-outline-primary" href="#">Older</a>
<a class="btn btn-outline-secondary disabled" href="#">Newer</a>
</nav>
</div><!-- /.blog-main -->
I think your code need to update like:
public function index()
{
$posts=Post::with('users')->latest()->get();
return view('posts.index',compact('posts'));
}
<p class="blog-post-meta">
{{$post->users->name }}
{{$post->created_at->toFormattedDateString()}}
</p>
Hope this work for you!
assume that you are including post.blade.php in index.blade.php file.
In above case you are not passing $post to post.blade.php. Your foreach loop will be like :
#foreach($posts as $post)
#include('posts.post', ['post' => $post])
#endforeach
I assume that you are including post.blade.php in index.blade.php file.
In above case you are not passing $post to post.blade.php. Your foreach loop will be like :
#foreach($posts as $post)
#include('posts.post', ['post' => $post])
#endforeach

Update multible rows in laravel 4

I wanted to update multiple rows in the database and have found a way to do it. but it does not seem like the best way to do it, since it is doing it in multiple calls at the moment.
I wanted to now if there is a better way to do this.
The homecontroller with the updatePersons function:
<?php
class HomeController extends BaseController {
public function index()
{
$persons = Person::get();
return View::make('hello')
->with(compact('persons'));
}
public function updatePersons()
{
$persons = Person::get();
foreach ($persons as $person) {
$person->fname = Input::get('fname'.$person->id);
$person->lname = Input::get('lname'.$person->id);
$person->save();
}
return Redirect::route('home')->with('succes', 'Siden er opdateret');
}
}
the view with the form
#extends('layouts.master')
#section('content')
<div class="container">
<ul class="list-group">
{{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
#foreach ($persons as $person)
<li class="list-group-item">
{{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
{{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
</li>
#endforeach
<li class="list-group-item">
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</li>
{{ Form::close() }}
</ul>
</div>
</div>
#stop
The routes:
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#index'));
Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController#updatePersons'));
I have tried to use the savemany() function on $persons after the foreach loop in updatePersons() but with no results.
If you're updating many rows with each with different values, there's no easier way to do it.
Could you think of how you'd write this in SQL?

model function call in blade view laravel

My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
Although its no good Practice Accessing the DB in Blade (better do this in the controller and pass the data) you can do:
<div class="price"><strong>Products</strong>
<span>
{{ BasicModel::where('sub_id', $row->sub_id)->count() }}
</span>
</div>
Its not tested, but have a look at the Eloquent docs, the count() method is explained there.
Update: I am not shure if laravel will find the class BasicModel (I never would access Models directly in blade, as stated do this in the controller and pass the data.) So maybe you need to write it with the full Namespace most likely {{ \App\BasicModel::where() }}.

In category counts his item from database table

My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
I think you are closing the PHP tag in the wrong place. Change to this:
<?php print_r($count);
$data = $this->BasicController->count {{ ($row->sub_id) }}
echo $data['count'];//here is the rightplace to close your PHP ?>
</span></div>
All PHP code needs to stay between the <?php and ?>
Looking to your image, apparently, it's printing the $count and then it's printing the plain text , so you have 80$data = ...
If you counted your rows in controller by the code below
$count = DB::table('products')->where('sub_id', $id)->count();
then why wrote so many code in html for counting?
Remove all code form counting form your html and just use this {{ $count }}

Categories