Undefined index: id Laravel 5.8 - laravel

My Tables:
kategoris table
id | kode_kategori | kategori_name |
items table
id | kategori_id | item_name
In items table the kategori_id column has foreignkey.
My Controller:
public function edit($id)
{
// $item = Item::findOrFail($id);
$item = DB::table('items')
->join('kategoris', 'items.kategori_id', '=', 'kategoris.id')
->where('items.id', '=', $id)
->select('items.*', 'kategoris.*', 'items.id', 'items.kategori_id')
->get();
// dd($item);
return view('master-dev/item/edit', compact('item'));
}
My View:
<div class="card card-default">
{{ Form::model($item,['route'=>['item.update',$item['id']], 'files'=>true,'method'=>'PUT']) }}
<div class="card-header">
<h3 class="card-title"><b>Edit Data Item</b></h3>
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse"><i class="fas fa-minus"></i></button>
</div>
</div>
<!-- /.card-header -->
<div class="card-body">
#if(!empty($errors->all()))
<div class="alert alert-danger">
{{ Html::ul($errors->all())}}
</div>
#endif
<div class="row">
<div class="col-md-6">
<div class="form-group">
{{ Form::label('kode_kategori', 'Kode Kategori') }}
<select name="kode_kategori" id="kode_kategori" class="form-control">
#foreach ($item as $i)
<option valu="{{ $i['kode_kategori'] }}">{{ $i['kode_kategori'] }}</option>
#endforeach
</select>
</div>
</div>
..........
..........
{{ Form::close() }}
I've tried any solutions in stackoverflow such as adding (ifempty...) and other solution but still the result Undefined index: id in my edit blade. When I was trying using dd and vardump the results was shown. I need to loop the foreach in my dropdown menu to show the list of data from my categories table. And I need to join my items table and my categories table to get the name of the categories.

you are calling same id from items and kategoris try this
public function edit($id)
{
// $item = Item::findOrFail($id);
$item = DB::table('items')
->join('kategoris', 'items.kategori_id', '=', 'kategoris.id')
->where('items.id', '=', $id)
->select('items.*', 'kategoris.id as kategory_id', 'kategoris.kode_kategori', 'kategoris.kategori_name')
->get();
// dd($item);
return view('master-dev/item/edit', compact('item'));
}
if this answer doesnot work show your database relation i will give you solution

$item = ....->get() will return a Collection to only have one item you need to use $item = ....->first() instead
But since you have #foreach ($item as $i) I believe, you still want to have a collection, but in that case, your issue is here
{{ Form::model($item,['route'=>['item.update',$item['id']], 'files'=>true,'method'=>'PUT']) }}
Since you have a collection, we don't know what $item['id'] it's referring to. Perhaps $item->first()['id'] ?

I solved the problem, there's a conflict fetching data from items and kategoris tables. There are differences calling a value with array and object, mostly if its data looped. So in the controller I must declared one by one, the selected value id from kategoris table, and I have to join both tables to get the name of the kategoris, and then I have to declare once more to get the list of the kategoris data. So there are three (3) variables to declare each one of them. For this long time I was looking for the short code in my Controller but I cannot find it.
Thank you for all of you guys helping me this problem. Cheers.

Related

Laravel Mega Menu Loop

I am learning laravel and was trying to create a Megamenu. But I can call parent menu, I stacked at 1st child and 2nd child.
Same children coming under every parent.
<div class="navbar-mega">
<div class="dropdown-mega">
#php
$categories = App\Models\Category::where('parent_id', 0)->orderBy('order_level','ASC')->get();
#endphp
#foreach ($categories as $item)
<button class="dropbtn-mega"> {{$item->id}}</button>
#endforeach
<div class="dropdown-content-mega">
<div class="row-mega">
#php
$subcategories = App\Models\Category::where('parent_id',
$item->id)->orderBy('name','ASC')->get();
#endphp
#foreach ($subcategories as $subcategory)
<div class="column-mega">
<h3>{{$subcategories}}</h3>
</div>
#endforeach
</div>
</div>
</div>
</div>
Database Fields
Subcategory Query Output
This code :
$subcategories = App\Models\Category::where('parent_id',$item->id)->orderBy('name','ASC')->get();
is not within the loop through the $categories as $item. So when it is executed it will also return the same set of categories (as $item will always be the same value at that point in your code.
Put it within the loop :
#foreach ($categories as $item)
<button class="dropbtn-mega"> {{$item->id}}</button>
<div class="dropdown-content-mega">
<div class="row-mega">
#php
$subcategories = App\Models\Category::where('parent_id',
$item->id)->orderBy('name','ASC')->get();
#endphp
#foreach ($subcategories as $subcategory)
<div class="column-mega">
<h3>{{$subcategories}}</h3>
</div>
#endforeach
</div>
</div>
#endforeach
and it should work fine.
You can use append for fetch sub categories, in your category model use this,
protected $appends = [
'sub_categories'
];
public function getSubCategoriesAttribute()
{
return Category::where('parent_id', $this->id)->orderBy('name','ASC')->get();
}
<div class="navbar-mega">
<div class="dropdown-mega">
#php
$categories = App\Models\Category::where('parent_id', 0)->orderBy('order_level','ASC')->get();
#endphp
#foreach ($categories as $category)
<button class="dropbtn-mega"> {{ $category->id }}</button>
#endforeach
<div class="dropdown-content-mega">
<div class="row-mega">
#foreach ($category->sub_categories as $subCategory)
<div class="column-mega">
<h3>{{ $subCategory->name }}</h3>
</div>
#endforeach
</div>
</div>
</div>
</div>
The better way to use below code in controller. And create the relations in model.
$categories = App\Models\Category::where('parent_id', 0)->orderBy('order_level','ASC')->get();
Use child parent relation in your model:
public function children()
{
return $this->hasMany(Category:Class,'parent_id');
}
And use with to get as parent-child tree
$categories = App\Models\Category::with('children)->where('parent_id', 0)->orderBy('order_level','ASC')->get();
You can check it using
dd($categories);
and use loop on it easily.
I think your table structure is not appropriate. Maybe you are trying to create an infinity category, subcategory, and other staff. In that case, you may go through this.
Table columns name should be like
id parent_id level name .....
Brief :
id as primary key, parent_id will be foreign key of your db table primary id, and other columns will be as your expectation.
How to read all the staff?
You may follow the below steps.
$categories = Category::query()->where('parent_id',0)->get() // You may put order by something.
Note: What you will get from this query?
The answer is, you will get all the parent's categories.
Now read every single parents category and their childrens.
How to read parents' category and their children?
At First Read Parent category
foreach($categories as $key=>$category){
echo $category->name; // Your Parent Category is here.
}
Secondly, Read the Parent-Child category
foreach($categories as $key=>$category){
echo $category->name; // Your Parent Category is here.
// Must check is child category found or not. Otherwise your error can be arrise.
if($categories->subCategories->count()){
foreach($categories->subCategories as $k=>$subCategory){
echo $subCategory->name;
}
}
}
A question can be here $categories->subCategories->count() && foreach($categories->subCategories as $k=>$subCategory) ?
If you have a question like this.
The answer is below :
Note: You must add a relationship method inside Category Model like A Parent Category can be More Child SubCategory
add this method to your Category Model.
public function subCategories(){
return $this->hasMany(Category::class,'parent_id');
}
Now you will get smooth output.
Have fun.

How to check date validation with Carbon in Laravel 8.*

I've got index page on which I'm displaying events.
#foreach($events as $event)
<div class="row">
<div class="d-flex justify-content-center" style="margin: auto">
<a href="{!! route('eventView', ['id' => $event->id]) !!}" style="text-decoration: none;">
<div class="row" style="margin-top: 10 px">
<p style="display:block">{{$event->name}}</p>
</div>
#if($event->photo_patch)
<img src="{{ asset('storage/' . $event->photo_patch) }}">
#else
<img src="placeholder" alt="...">
#endif
</a>
</div>
</div>
</div>
#endforeach
But the problem is that its displaying all events, even those which took place in the past.
I would like to display events only with today's or future date
So I'm stuck now and I dont know what to do next.
I tried to do loop which shows me events that are today/in the future:
public function index()
{
$date = Carbon::today();
$events = Event::where('date_of_event' >= $date)->get();
foreach($events as $event){
if($event->date_of_event >= $date){
dump('Valid');
}
else{
dump('Invalid');
}
}
dump($events);
dump($date);
return view('frontend/index',['events'=>$events]);
}
But I dont know how to display them later inside of my view.
My second shot was to do it with this line:
$events = Event::where('date_of_event' >= $date)->get();
But then I've got error :
SQLSTATE[42S22]: Column not found: 1054 Unknown column '1' in 'where clause' (SQL: select * from `events` where `1` is null)
which isnt really accurate since column name should be valid.
How can I implement that properly?
The default operator for where is =. If you want to change this you'll use the second argument for the operator and the third for your value.
Event::where('date_of_event', '>=', $date)->get();
See Where Clauses for more details.
To make that code short you may use this code
Event::whereDateOfEvent('>=', $date)->get();

I can't retrieve data from the related table(model) in Laravel6

I can't retrieve data from the related table.
There are 3 models(tables).
User
Chirp (has 'user_id' as foreign key)
Click (has 'chirp_id' as foreign key)
then I want to retrieve User & Click's data from Chirp model.
So I wrote:
Chirp.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Chirp extends Model
{
public $timestamps = false;
protected $guarded = [];
public function user()
{
return $this->belongsTo('App\User');
}
public function clicks()
{
return $this->hasMany('App\Click');
}
}
HomeController.php
class HomeController extends Controller
{
public function index()
{
$chirps = Chirp::with(['user','clicks'])
->orderBy('posted_at', 'desc')
->get();
return view('home', ['chirps' => $chirps]);
}
}
home.blade.php
#foreach($chirps as $chirp)
<div>
<div>by
<b>{{ $chirp->user->name }}</b>
on
<small>{{ $chirp->posted_at }}</small>
</div>
<div>
<p>{{ $chirp->text }}</p>
<p>{{ $chirp->click->ip_address }}</p>
</div>
</div>
#endforeach
at home.blade.php, {{ $chirp->click->ip_address }} can't be retrieved and get error "Facade\Ignition\Exceptions\ViewException Trying to get property 'ip_address' of non-object"
However, if I delete it, I can retrieve {{ $chirp->user->name }} properly.
Why can't I retrieve Click model from Chirp model, While I can retrieve User model from Chirp model?
Thank you.
You need to loop over your clicks as well:
#foreach($chirps as $chirp)
<div>
<div>by
<b>{{ $chirp->user->name }}</b>
on
<small>{{ $chirp->posted_at }}</small>
</div>
#foreach($chirp->clicks as $click)
<div>
<p>{{ $chirp->text }}</p>
<p>{{ $click->ip_address }}</p>
</div>
#endforeach
</div>
#endforeach
Chirp has many clicks (not click). You have to foreach $chirp->clicks in your blade.
#foreach ($chirp->clicks as $click)
<p>This is click id {{ $click->id }}</p>
#endforeach
You've hasMany relation with Chirp and clicks
And here you're getting many clicks instead of click
#foreach($chirp->clicks as $click)
<p>{{ $click->ip_address }}</p>
#endforeach
To debug this problem you can take the following steps:
Check if the chirps variable has any data within the controller.
dd($chirps);
If you know you have the data you can take the steps to make your blade better.
Becasue its a many to many relation you should loop trough the data.
#foreach($chirps as $chirp)
#foreach($chirp->clicks as $click)
<div>
<p>{{ $chirp->text }}</p>
<p>{{ $click->ip_address }}</p>
</div>
#endforeach
#endforeach

Retrieve unique entries from DB using Eloquent Laravel 4

I am using Laravel-4 to build an application. I am trying to make the best use of Eloquent ORM. Currently I am displaying a list of db entries which all have a number of tags associated with them
To the right I display a grid of all the tags however it is showing duplicate tags. I would only like to show unique tags
This is my code:
<div class="tags-panel">
<div class="tags-title"><h1>Tags</h1></div>
<div class="tags-cloud">
#foreach(Tag::distinct()->get() as $tag)
<span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}}
#endforeach
</div>
</div>
Does Eloquent provide a way of only retrieving distinct entries from the db?
Try using Tag::groupBy('field_name')->get()
<div class="tags-panel">
<div class="tags-title"><h1>Tags</h1></div>
<div class="tags-cloud">
#foreach(Tag::groupBy('field_name')->get() as $tag)
<span class="num"> {{ Tag::getAmount($tag->id) }} </span> {{$tag->name}}
#endforeach
</div>
</div>
To use the distinct()-function you have either have a select() in your chain, or use a field as an argument in your get()-function. For example:
$tags = Tag::distinct()->get(array('field'));
or
$tags = Tag::select('field')->distinct()->get();
You could also instead use groupBy('field') if you don't want to supply field names:
$tags = Tag::groupBy('field')->get();

How can I solve issue with One to One relationship using foreign keys

I've been using eloquent in my models. I've got the following two tables:
Singlecard
->id
->card_id
Card
->id
->card_id
My Singlecard Model has the following function:
public function info()
{
return $this->hasOne('Card', 'card_id', 'card_id');
}
I used this to get the card (there's only one card in the deck for my test).
$cards = Singlecard::where('deck_id', '=', $deck)->get();
foreach ($cards as $card)
{
$cards_array[] = $card;
}
It got the correct card and using var_dump I verified that. However, here's the problem:
<div class="row singlecard">
<a class="" href="{{ $single->id }}">
<div class="large-2 columns">
<img src="{{ $single->info->card_image }}">
</div>
<div class="large-10 columns">
<div class="row">
<div class="large-12 columns">
<p>{{ $single->info->name }}</p>
</div>
</div>
<div class="row">
<div class="large-12 columns">
#foreach ($single->attributes as $attribute)
<p>{{ $attribute->alias }}</p>
#endforeach
</div>
</div>
</div>
</a>
</div>
Here's the twist: The attributes code works correct. It grabbed the correct attributes from a one to many relationship I defined. But it's grabbing the wrong info from the Cards table. Even though I defined the keys to match on, it is matching based on the ID of the singlecard and the card_id in the Cards table.
I've tried removing the keys and that didn't do anything. I even removed the function all together just to verify that that was the function being called. I'm not sure what's wrong?
UPDATE:
I figured it out, I did two things. One, I used id from the Cards table as the record to match with Singlecards. I also changed my function in the Singlecards model like so:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
This allowed me to properly query the relationship.
I needed to update how my models were related and better form the relationship. I also needed to change the model so that Singlecards belonged to Cards. I assumed it should be the opposite.
Cards contains all the info about the various cards and Singlecards is what is in each individuals hands/decks. I assumed that would make Singlecards the parent but that was a mistake. Once I changed the function in the model to be like this:
public function info()
{
return $this->belongsTo('Card', 'card_id');
}
Then it worked.

Resources