Invalid argument supplied for foreach() - php

Newbie here. I've been working on a one to many relationship in Laravel 5.4. I'm working on reading the relationship between User and State. I keep getting this error. I have data in the tables. Here is the view:
#foreach ($user->states as $note)
<li>{{ $note->name }}</li>
#endforeach
Here is the User model:
class User extends Model
{
use SoftDeletes;
public function state(){
return $this->belongsTo(State::class);
}
public function role(){
return $this->belongsTo(Role::class);
}
public function district(){
return $this->belongsTo(District::class);
}
Here is the State model:
class State extends Model
{
protected $fillable = [
'name'
];
public function users(){
return $this->hasMany(User::class);
}
}

Check array or object count before applying foreach loop. It is really a bad practice of using loop without checking the array count.
#if(isset($user->states) && count($user->states) > 0)
#foreach ($user->states as $state)
<li>{{ $state->name }}</li>
#endforeach
#else
No Records Found
#endif

Check get results is not a blank $results != FALSE You can convert this snippet in laravel way
<?php
if($user->states != FALSE){
foreach ($user->states as $note){
echo '<li>'.$note->name.'</li>';
}
}else{
echo 'No Results Found!';
}
?>

Related

get items from 'with' in eloquent query and display to blade

So i have this eloquent query
$categories = categories::all();
foreach($categories as $c):
$c->items = item_categories::where('cat_id',$c->cat_id)->with('item')->with('item.item_images')->get();
endforeach;
and in my blade, I can display this part
with('item')
like doing
#foreach($categories as $c)
#foreach($c->items as $i)
{{ $i->item->item_name }}
#endforeach
#endforeach
How about retrieving data from this part?
with('item.item_images')
I tried
#foreach($categories as $c)
#foreach($c->items as $i)
{{ $i->item->item->item_images->image_name }}
#endforeach
#endforeach
but it gives me error
Trying to get property of non-object
Any ideas, help please?
here's the 'categories' model
class categories extends Model
{
protected $table = 'categories';
protected $primaryKey = 'cat_id';
public function item_category(){
return $this->belongsTo('App\item_categories','cat_id','cat_id');
}
}
and the 'item_categories' model
class item_categories extends Model{
protected $table = "item_categories";
public function item(){
return $this->belongsTo('App\items','item_id','item_id');
}
public function category(){
return $this->hasOne('App\categories','cat_id','cat_id');
}
}
and the 'items' model
class items extends Model
{
protected $table = 'items';
protected $primaryKey = 'item_id';
public function item_images(){
return $this->hasMany('App\item_images','item_id','item_id');
}
public function item_categories(){
return $this->hasMany('App\item_categories','item_id','item_id');
}
}
You're going too deep. It looks like item_categories has an item, which has an item_image, so you just need to access it like this:
{{ $i->item->item_images->image_name }}
Since each item has many item_images, you need to iterate through it.
#foreach($i->item->item_images as $image)
{{$image->image_name}}
#endforeach
My guess is that your code is okay but item doesn't have item_image. Try checking if checking if $i->item->item->item_images is empty before trying to use the value

Showing related table information in blade template laravel

I have the following relationship between my tables
In my Models i have the following code:
Location Model:
public function member() {
return $this->belongsTo('App\Member','member_id');
}
Member Model:
public function locations(){
return $this->hasMany('App\Location','member_id');
}
Now in my Location controller I created the following function.
public function getFinalData(){
$locations = Location::with('member')->whereNotNull('member_id')->get();
return view('locations.final-list',['locations'=>$locations]);
}
In my blade template however, I am unable to iterate through the member properties
<ul>
#foreach($locations as $location)
<li>{{$location->id}}</li>
<li>
#foreach($location->member as $member)
{{$member->id}}
#endforeach
</li>
#endforeach
</ul>
This gives me the following error:
Trying to get property of non-object (View:locations/final-list.blade.php)
update: The result i'm trying to achieve corresponds to this query
SELECT locations.location_id,locations.name,members.first_name, members.last_name , locations.meters
FROM locations,members
WHERE locations.member_id = members.id
Update 2:
So i tried to access a single location with a single attached to it and that works perfectly
public function getFinalData(){
//$locations = Location::with('member')->whereNotNull('member_id')->get();
$location = Location::find(0);
return view('locations.final-list',['location'=>$location]);
}
in final-list
$location->member->first_name
**Update 3 **
Tinker Output for one record :
In your Location model, rewrite below function:-
public function member()
{
return $this->belongsTo('App\Member', 'id');
}
Get all locations with member detail as below:-
$locations = Location::with('member')->get();
Hope it will work for you :-)
For showing related tables information in blade is as shown:
Model Relations
Location Model:
public function member() {
return $this->belongsTo('App\Member','member_id');
}
Member Model:
public function locations(){
return $this->hasMany('App\Location','member_id');
}
Get all locations in your controller
$locations = Location::all();
return view('locations.final-list', compact('locations'));
Or
$locations = Location::orderBy('id')->get();
return view('locations.final-list', compact('locations'));
Inside your view(blade) write the following code:
<div>
#if($locations)
#foreach($locations AS $location)
<div>{{ $location->id }}</div>
#if($location->member)
#foreach($location->member AS $member)
<div>
{{ $member->id }}
</div>
#endforeach
#endif
#endforeach
#endif
</div>

Show Duplicate Error Message in Error list in View : Laravel 5

Below is my code to check if the record is duplicate or not.
$Category = \App\Models\Category_Model
::where("Category", "=", $request->input('Category'))->first();
if($Category != null) {
return 'Duplicate';
}
Is there any way to inject this error message in the validation rule in such a way that this error message appears in View the error list in below section?
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
Solution:1
Reference : unique:Name of the Table:
Make sure the database table contains Unique Constraint.
$v = Validator::make($request->all(), [
'Category' => 'required|unique:tblcategory|max:100|min:5'
]);
Solution:2
$Category = \App\Models\Category_Model
::where("Category", "=", $request->input('Category'))->first();
if($Category != null) {
$v->errors()->add('Duplicate', 'Duplicate Category found!');
return redirect('Create-Category')
->withErrors($v)
->withInput();
}
Try it
Create CategoryFormRequest class
namespace App\Http\Requests;
use App\Http\Requests\Request;
use Illuminate\Support\Facades\Input;
class CategoryFormRequest extends Request {
public function authorize() {
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules() {
$rules = [
'Category' => ' required|unique:categories,Category',
];
if ($this->method() == 'PUT') {
$rules['Category'] = 'required|unique:categories,Category,' . $this->category;
}
return $rules;
}
}
Your controller code
use App\Http\Requests\CategoryFormRequest as CategoryFormRequest;
......
......
public function store(CategoryFormRequest $request) {
.......
.......
}
Ref:- Request class in laravel
You could return a view with errors like this:
return view('my_view')->withErrors(['Duplicate Record.']);

laravel eloquent repository query foreign key tables

hi i am using a custom repository and I am getting comfortable with querying one table to retrieve data like so:
public function getAll()
{
// get all logged in users projects order by project name asc and paginate 9 per page
return \Auth::user()->projects()->orderBy('project_name', 'ASC')->paginate(9);
}
and in my controller I simply call
public function __construct(ProjectRepositoryInterface $project) {
$this->project = $project;
}
public function index()
{
$projects = $this->project->getAll();
echo View::make('projects.index', compact('projects'));
}
and my view is as so:
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
{{ $project->project_name }}
#endforeach
#else
<p>No records, would you like to create some...</p>
#endif
{{ $projects->links; }}
#endif
However within my projects table I have a status_id and a client_id and I want to retrieve records of this these tables with the logged in user but I am not sure how to structure my query, does anyone have any guidance?
According to the laravel documentation, In your project model you can add the following function:
class Project extends Eloquent
{
public function clients()
{
return $this->hasMany(Client::class);
}
}
In your client model you can then add the inverse of the relationship with the function:
class Client extends Eloquent
{
public function project()
{
return $this->belongsTo(Project::class);
}
}
Then you can retrieve the data with a function like:
$clients = Project::find(1)->clients;

Retrieve Related Models using Laravel 4

I have 3 tables: Users, Projects, Items and Friends. I want to get all the items for a project and list each item with related friends. Am I missing something in my model? Ultimately I want to get all the friends which are related to the items.
// CONTROLLER
public function show($id)
{
$uid = Auth::user()->id;
$projects = Project::find($id)->with('item.friend')->get();
return View::make('projects.show', compact('projects'));
}
//VIEW
#foreach ($projects as $project)
#foreach ($project->friend as $friend)
<li>
<a href="#" class='itemLink' >{{$friend->email}}</a>
<a href="#" class='itemLink' >{{$projects->item->name}}</a>
</li>
#endforeach
#endforeach
// MODELS
class User extends Eloquent {
public function project()
{
return $this->hasMany('Project');
}
public function item()
{
return $this->hasMany('Item');
}
public function friend()
{
return $this->hasMany('Friend');
}
class Project extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function item()
{
return $this->hasMany('Item');
}
public function friend()
{
return $this->hasMany('Friend');
}
class Item extends Eloquent {
protected $guarded = array();
public static $rules = array();
public function friend()
{
return $this->hasMany('Friend');
}
class Friend extends Eloquent {
protected $guarded = array();
public static $rules = array();
You are missing a loop. I recommend that when setting up a many to many relationship, make sure your method is plural. It makes a lot more sense when trying to read the code. You'd then send up with #foreach $project->items as $item or $item->friends as $friend.
#foreach ($projects as $project)
#foreach ($project->item as $item)
#foreach($item->friend as $friend)
<li>
<a href="#" class='itemLink' >{{$friend->email}}</a>
<a href="#" class='itemLink' >{{$item->name}}</a>
</li>
#endforeach
#endforeach
#endforeach
Your models seems OK at first look. I think since you are pulling item.friend relationship, this line
#foreach ($project->friend as $friend)
should be,
#foreach ($project->item->friend as $friend)

Categories