Laravel eloquent relationship between two table - laravel

I have a table notices. Model for this table is Notice.php
In this table I have notice and id column.
I have fetched all notices from notices table and viewed in my view. Here is my controller code for fetching all notices.
public function index()
{
$notice = Notice::orderBy('id','desc')->paginate(5);
return view('teacher.notice')->withNotices($notice));
}
Here is my view code to show all notices.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
#endforeach
Now I want to put two button inside this foreach loop. One is to confirm and another is remove confirmation.
To store this confirmation data I have created another table named notice_confirmed_student and model for this table is noticeConfirmedStudent.php. In this table have three column:
id
student_id
notice_id
If a student click confirm then his id and notice id will be stored in this table. I have done this perfect. But my problem is, in the foreach loop it shows both two button (confirm and remove confirm) at a time. I want to show confirm button if user already not confirmed for this notice. If user already confirmed for that notice then it should show remove confirmation button.
Here I am giving my blade foreach loop again with button for better understanding. Bellow code is not perfect, I have just written those code to understand my question.
#foreach($notices as $notice)
{{$notice->id}}
{{ $notice->notices }}
<?php $student_id= "select student_id from notice_confirmed_student where notice_id=$notice->id"; ?>
#if ($student_id == $auth::user()->id)
<button>confirm</button>
#else
<button>Remove Confirmation</button>
#endif
#endforeach
Thanks in advance.

Few things are wrong/incorrect here, to make it clear,
Notice <> User relation is Many-Many and notice_confirmed_student is a pivot table. so user model should have relation,
public function confirmedNotices()
{
return $this->belongsToMany(Notice::class, 'notice_confirmed_student')
}
Then in for each loop you can check like,
if(in_array($notice-id, Auth::user()->confirmedNotices->pluck('id')->all())) {
// user confirmed
} else {
// user not confirmed.
}

if I correctly understand your issue, you need to check if record with given id exists notice_confirmed_student table, and then check in your loop. retrieve the confirmed students with your notices.
$notice = Notice::with('notice_confirmed_student_or_whatever_your_relation_method_called)')->orderBy('id','desc')->paginate(5);
then check in loop, if related attribute is not empty like you do in your view
#if($notice->my_attr && $notice->my_attr->user_id == \Auth::user()->id)
// do stuff
#else
// it doesn't has record
#endif

Related

ManytoMany relations in Laravel, retrieve data from related tables and display in blade

I have two tables related by many to many relation in Laravel Framework. I can display data from each table separately, but not through relation by taking one record from the 1st table and checking related records in the 2nd table. In tinker it accesses data fine.
Relations:
public function underperformances() {
return $this->belongsToMany(Underperformance::Class);
}
...
public function procedures() {
return $this->belongsToMany(Procedure::class);
}
My resource controller part:
...
use App\Underperformance;
use App\Procedure;
...
public function index()
{
$books = Underperformance::orderBy('id','desc')->paginate(9);
$procedures = Procedure::all();
return view('underpcon.underps', compact('books', 'procedures'));
}
Route:
Route::get('/underps', 'UnderpsController#index');
If I try to display data like this:
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances}}</li>
#endforeach
I get such format to the browser:
[{"id":1,"title":"Spare part not taken before service","description":"tekstas","level":"1","costs":600 ...
This is correct data from related table, but I cannot select further the specific column from that table. For example this does not work:
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances->id}}</li>
#endforeach
Nor this one:
#foreach ($procedures->underperformances as $underperformance)
<li>{{$underperformance->id}}</li>
#endforeach
How do I select records of the related table and display specific data from that table?
What would be a conventional way to do this?
#foreach($procedures as $procedure)
<li>{{$procedure->underperformances->id}}</li>
#endforeach
^ This right there $procedure->underperformances will return a collection, not a single item, so you need to treat it as array, you will not be able to access the id directly, you can either #foreach that, or use the pluck method in Laravel Collections.

How to check and get the result if the table contain user id in laravel

I have create a relationship between user and table column, I want show the table list which is belongs to particular user. For example if user_id 1 is logged in the system, the system will only show the information belong to him which is Table 1.
This is my controller code :
public function show(Request $request){
$user_id=Auth::user()->id;
$table= Roundtable::findOrFail($user_id);
return view('users.tables.show')->withTables($table);
}
I know that $table= Roundtable::findOrFail($user_id); is incorrect but I had no idea how to do because I am new for laravel.
If user has just one table and if Roundtable model has user_id you can use this query:
Roundtable::where('user_id', $id)->first();
It will give you user's table or null if table doesn't exist.
Another way to get table is to use relation:
auth()->user()->roundTable;
Well i found the solution, just need to change the code into
$id=Auth::user()->id;
$table= Roundtable::where('user_id',$id)->get();
return view('users.tables.show')->withTables($table);
then the result will return correctly.

Accessing relationship of a relationship

I am adding in an announcements feature to my application.
I have an announcements table which stores the announcement and an announcement_active table which stores the undismissed announcements for each user.
When an announcement is created, a record is generated in the announcements table to store this and a record entered in to the announcement_active table for every user for that announcement.
My user model holds a relationship for the active announcements:
public function activeAnnouncements()
{
return $this->hasMany('App\ActiveAnnouncements');
}
I am then accessing this in my view to check for any undismissed announcements like this:
#if (Auth::user()->activeAnnouncements()->count() > 0)
//code
#endif
The above works fine, it is when I am trying to do a for each loop on the announcements that I am having trouble:
#if (Auth::user()->activeAnnouncements()->count() > 0)
#foreach(Auth::user()->activeAnnouncements()->announcement as $announcement)
//code to display announcement
#endforeach
#endif
It is when I am chaining ->announcement that I run in to trouble. I have defined the relationship like so:
public function announcement()
{
return $this->belongsTo('\App\Announcements');
}
However I get the error:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$announcement
When using Tinker and running \App\User::find(1)->activeAnnouncements()->first()->announcement the correct announcement shows.
Where am I going wrong when trying to load these in to my foreach loop?
You're never actually retrieving the data in your foreach. Instead, Laravel thinks you're saying "build this query, don't execute it, then look for a property called 'announcement' on it". If you just change it to a get() call, it should work:
#foreach(Auth::user()->activeAnnouncements()->get() as $announcement)
Or better yet, use the automatic property version:
#foreach(Auth::user()->activeAnnouncements as $announcement)
By the way, it looks like you might want to check out Blade's #each functionality: https://laravel.com/docs/5.3/blade#rendering-views-for-collections
In your class User, definine a announcements relation like this :
public function announcements() {
return $this->hasManyThrough(Announcement::class,ActiveAnnouncement::class);
}
You can then access user's announcement with announcement :
#if (Auth::user()->announcements()->count() > 0)
#foreach(Auth::user()->announcements as $announcement)
//code to display announcement
#endforeach
#endif
Nota :
Maybe you could simply add a column is_active in announcement and drop ActiveAnnouncement model. This way, define announcements relation in your class User :
In your class User, definine a announcements relation like this :
public function announcements() {
return $this->hasMany(Announcement::class);
}
and access active announcements via :
$activeAnnouncements = $user->announcements()->whereIsActive(true)->get()
Hope this will help

Laravel 4 Eloquent Problems Select with hasMany Relation

I have 2 models : Album & Photo.
Album hasMany Photo and photo belongsTo('album','id');
Just Like:
class Photo extends Eloquent {
protected $table = 'photo';
public function album(){
return $this->belongsTo('album','id');
}}
and
class Album extends Eloquent {
protected $table = 'album';
public function photo()
{
return $this->hasMany('photo');
}}
i have no problem until i want to try select Album Name and show first photo on an Album.
I am trying this code:
<?php $albums= Album::get();?>
#foreach($albums as $album)
<pre>{{$photo = $album->photo->first()}}</pre>
#endforeach
and output :
{"id":1,"images":"1.png","album_id":1,"created_at":"2014-09-08 03:54:36","updated_at":"2014-09-08 03:54:36"}
{"id":3,"images":"3.jpg","album_id":3,"created_at":"2014-09-08 04:30:35","updated_at":"2014-09-08 04:30:35"}
it's mean i have 2 album and i already select first photo of each album.
and when i trying to call images attributes it's error:
echo "$album->photo->first()->images";
error :
It is likely that you have an Album in your database which does not have a Photo associated with it. So when you loop over your albums and echo {{ $album->photo->first() }}, it simply outputs null for any album that does not have a photo (because there is, obviously, no first()) without throwing an error. However, when you try to access the image property of the album that doesn't have a photo, you are trying to get a property of a non-object, i.e. you are asking for the image property of null. Hence an error is thrown.
You can resolve this by wrapping your output in an #if statement that checks to make sure a photo exists, before trying to access its image property:
#foreach($albums as $album)
#if (count($album->photo))
{{ $album->photo->first()->image }}
#endif
#endforeach
There is a shortcut for this, using blade's or syntax, which checks for existence before trying to echo the result. This allows you to remove the #if statement:
#foreach($albums as $album)
{{ $album->photo->first()->id or null }}
#endforeach
First of all, I would recommend when using Eloquent to retrieve all entries in a table, use ::all() instead of ::get(), as shown in Basic Usage. Not sure if it's causing the problem, but you may want to follow the docs.
Secondly, in relationship, the first parameter to hasMany and belongsTo should be the model class name. So it should be 'Album' and 'Photo', first letter capitalized.
Judging from you output, album_id seems to be the foreign key name. So in your Photo class, change the relationship into the following:
public function album(){
return $this->belongsTo('Album','album_id');
}
Just ran your code, the issue is that you did not define the primary key for you models. Laravel will assume you are using 'id' as the primary key, and if that's not the case, your relationship will break. And it's always better to explicitly define what the primary key is, so as to avoid confusion when foreign keys are involved. So please add to the model class:
protected $primaryKey = 'album_id';
You can revise your code and see if the error persists. It's not showing up in my end now.

how to insert multiple data into a single column into the database

Am learning laravel and I encountered a problem saving data into my database from my form.
My instance
when a user tries to make a multiple purchase of products ie.when a user purchases more than one product,i wanted to save the names of products that belongs to the purchase user made into my 'PURCHASES' table having an 'ID' of '1'.
Names of product to be save;
1.productA
2.productB
3.productC
Codes
FORM IN MY VIEW
<input type='hidden' name='product_name'
#foreach($order as $order)
value='{{$order->product_name}}'
#endforeach >
MY purchase CONTROLLER
Saving the names;
$purchase = new Purchase;
$purchase->product_name = $posted['product_name'];
$purchase->save();
When i initiate the function i get an error exception reading 'Trying to get property of non-object' from my view from the line;
#foreach($order as $order)
value='{{$order- >product_name}}'
#endforeach >
How do i go about this problem?
There are a lot of strange things in your code unless I'm reading it wrong, but most likely when you're seeing that error in a view it's because you didn't pass that data into the view. Take this example:
Controller
public function showProducts() {
// assuming $order_array is a set of product IDs that is part of an order
$orders = array('products' => Products::whereIn('id', $order_array);
return View::make('your/view' compact('orders'));
}
I don't quite understand what you're trying to do but passing the object array 'orders' to the view allows you to then call your line:
#foreach($orders as $order)
code here
#endforeach

Resources