I want to know how can I check if the current user has any order or not? if have show the list and if not show the message?
currently I'm using this but it doesn't work well:
#if (empty(Auth::user()->order))
<blockquote>
<h1>Sorry you have no order at the moment, would you like to check out our products?</h1>
<footer>Click here</footer>
</blockquote>
#else
.......
#endif
user model:
public function order(){
return $this->hasMany(Order::class);
}
order model:
public function user(){
return $this->belongsTo(User::class);
}
my controller that shows orders history view:
public function index()
{
$user = Auth::user();
$orders = Order::where("user_id", "=", $user->id)->orderby('id', 'desc')->paginate(10);
return view('users.orders', compact('user', 'orders'));
}
You can count the orders using:
Auth::user()->orders->count()
To get this working there are a few prerequisite:
Have a correct DB schema
Have relations setup (it seems you need one-to-many
If you have this and assuming your relation is setup as:
class User extends Model{
/**
* Get the orders for the user
*/
public function orders(){
return $this->hasMany('App\Order');
}
}
You could use the forelse blade syntax
#forelse (Auth::user()->orders as $order)
<li>{{ $order->title }}</li>
#empty
<blockquote>
<h1>Sorry you have no order at the moment, would you like to check out our products?</h1>
<footer>Click here</footer>
</blockquote>
#endforelse
This will create a for loop in which you could declare the html layout for your order. If there are no orders the empty block will instead be used.
Related
I have problem to get name from role_user table for each post. I have ACL, so i have 3 tables - users, roles, role_user.
My code looks like this:
Post model
public function user()
{
return $this->belongsTo(user::class);
}
User model.
public function posts()
{
return $this->hasMany(post::class);
}
Role model.
public function users()
{
return $this->hasmany(user::class);
}
PostController,
return view ('admin.posts',[
'posts' => Post::All()
]);
In blade I echo fx user name by:
#foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>{{$post->category->name}}</td>
**<td>{{$post->user->name}}</td>**
</tr>
#endforeach
But the problem is that i want to echo name of role ( from role_user table) for user who wrote post which i am looping.
update
Ok, i solved issue, but probaly there is a better wat. anyone?
I added to models:
User model:
public function roles()
{
return $this->belongsToMany(Role::class);
}
And changed role model:
public function users()
{
return $this->belongsToMany(user::class);
}
Post controller:
class PostController extends Controller
{
public function index()
{
return view ('admin.posts',[
'posts' => Post::with('user')->get(),
'roleUsers' => User::with('roles')->get()
]);
}
and in blade i am doing
#foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>
<p>
#foreach ($roleUsers as $roleUser)
#foreach($roleUser->roles as $role)
<p>
{{ $role->pivot->user_id === $post->user->id ? "Role: $role->name" : "" }}
</p>
#endforeach
#endforeach
I guess there could be a better solution.
Use withPivot() method on the relation. Instead of fetching it from the pivot attribute, it will be on the model, if fetched through the many to many relation.
public function users()
{
return $this->belongsToMany(user::class)->withPivot();
}
Then i would change the front end logic to something in the style of, assuming that all post would have a user with the given role, else you will need to do an if check.
#foreach ($roleUsers as $roleUser)
{{ $roleUser->roles->where('id', $post->user->id)->first()->name }}
#endforeach
You question has a lot of code, but this is the way i perceive it and hopefully it can get you closer to better understanding of it.
Ok i fix my problem, thank you for your help. I found many post's similar to my so I will show solution.
Realtion's:
User belongTo post.
Roles belongsToMany Users.
Users belongsToMany Roles.
DB structure:
users id|User_name
roles id|name
role_user id|user_id|role_id
And what I tried to achieve is while looping through all Post's in blade to display name of role which belongs to that post and solution is very simple.
#foreach ($posts as $post)
{{$post->user->roles->first()->name}}
#endforeach
I'm the beginner of laravel 6. I just want to ask. I want to display data but it doesn't show.
index.blade.php:
#if(isset($teachers))
#foreach($teachers->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
#endforeach
#endif
Controller:
public function index()
{
$teachers= DB::table('teachers')->first();
$qualifs = DB::table('qualifs')->find($teachers->id);
return view('teachers.index',compact('teachers','qualifs'));
}
qualif.php:
public function teachers()
{
return $this->belongsToMany('todolist\teacher', 'qualif_teachers');
}
teacher.php:
public function qualifs()
{
return $this->belongsToMany('todolist\qualif', 'qualif_teachers');
}
Note: Data is storing correctly, only displaying issue.
ERROR:Undefined property: stdClass::$qualifs
relationship belongs to a model instance that means to an eloquent object. when you are using query builder you will get stdObject instead of an eloquent object. and thus your relationship is not working. to make this work you have to use eloquent instead of query builder.
public function index()
{
$teachers= teacher::get();
return view('teachers.index',compact('teachers'));
}
and view will be like
#foreach($teachers as $teacher)
#foreach($teacher->qualifs as $qualif)
<li>{{ $qualif->qual }}</li>
#endforeach
#endforeach
I want to show the list of users who voted for specific link like list of users who voted for link 1..etc i get the count of votes on every link but i cant figure out how to fetch the users.
Link Model:
/**
*
*links votes with respect to users
*#return
*/
public function votes(){
return $this->hasMany(Communitylinkvotes::class,'community_links_id');
}
// practise
public function userss(){
return $this->hasMany(Communitylinkvotes::class,'user_id','community_links_id');
}
CommunityLinkVotes model or Pivot table model
class Communitylinkvotes extends Model
{
//
protected $table = 'community_links_votes';
}
Migration for votes
public function up()
{
Schema::create('community_links_votes', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->index();
$table->integer('community_links_id')->index();
$table->timestamps();
});
}
Are you specifically trying to get the list of users by starting with the Link model?
If not, do something like this:
User::whereHas('votes', function($query) use ($some_id) {
$query->where('community_links_id', $some_id);
})->get();
If so, I think your users relationship on the Link model needs to be a hasManyThrough.
Something like:
$this->hasManyThrough(User::class,Communitylinkvotes::class);
I would suggest you to use belongsToMany relationship. That will be easy to get what you are trying to get. Add relationship to your Communitylink Model.
public function users()
{
return $this->belongsToMany(User::class, 'community_links_votes','user_id', 'community_links_id');
//community_links_votes is the pivot table
}
Controller:
$link = Communitylink::find(1);
And now you can get the users for that link like below example in blade:
#foreach($link->users as $user)
{{ $user->name }}
#endforeach
Some improvements to controller and view compared to #emon...let me know either it is working or not..
public function users()
{
return $this->belongsToMany(User::class,
'community_links_votes','user_id', 'community_links_id');
//community_links_votes is the pivot table
}
Controller:
$link = Communitylink::with('users') - >first();
And now you can get the users for that link like below
example in blade:
#foreach($link->users as $user)
{{ $user->first() - >name }}
#endforeach
public static function get_voted_users($id){
$result = DB::select(
DB::raw('SELECT users.name FROM users join community_links_votes on community_links_votes.user_id = users.id
join community_links on community_links.id = community_links_votes.community_links_id
where community_links.id = '.$id.' ')
);
return $result;
}
I have relations like this
User->hasMany->reviews
Review->belongsTo->user
Review->hasMany->ReviewAnswer
ReviewAnswer->belongsTo->Review
Now I try to display answers for specific review. My reviewAnswer table looks like:
Id, review ID, text
But the problem is when I do that:
#foreach($user->reviews as $data)
#foreach($data->reviewAnswers->where('review_id', $data->id) as $answer)
{{$answer->text}}
#endforeach
#endforeach
Then reviews displays okay, but I get the same answers for every review. How to repair that?
Make sure to check if all the relationships are correct. In this example, I assume that your models are stored in your app folder.
First, your User model should have reviews
public function reviews() {
return $this->hasMany("App\Review", "user_id", "id");
}
Next, set up your Review model to have answers
public function answers() {
return $this->hasMany("App\ReviewAnswer", "review_id", "id");
}
Then this is how you'll get all users with their respective reviews and answers
$users = User::with("reviews.answers")->get();
Finally, peform the loop in your view
#foreach($users as $user)
#foreach($user->reviews as $review)
#foreach($review->answers as $answer)
#endforeach
#endforeach
#endforeach
Try using the hasManyThrough() option which the eloquent models provide you.
Link: Laravel Eloquent Relations
This means in your case you would add:
class User extends Model {
public function reviewAnswers(
return $this->hasManyThrough(ReviewAnswer::class,Review::class);
)
}
and then simply access it in blade as:
#foreach($user->reviewAnswers() as $reviewAnswer) {
{{$reviewAnswer->text}}
}
I have the following challenge, trying to join 3 tables in Laravel 5:
I have a many-to-many relation between 3 table: students, classrooms, terms. I would love to make a call like term->classroom->students.
I saw the Eloquent-triple-pivot package, but unfortunately, I cant get it working for Laravel 5.
Please, I would appreciate solution to bind this and make the call, eloquent or otherwise.
Thank you.
EDIT:
I have many-to-many relationship between 3 tables; classrooms, students, terms.
I have 3 pivot tables: classroom_term, classroom_student, student_term.
And 3 corresponding models: ClassroomTerm, ClassroomStudent, StudentTerm.
My Classroom model:
public function students()
{
return $this->belongsToMany('App\Student')->withTimestamps();
}
public function terms()
{
return $this->belongsToMany('App\Term')->withTimestamps();
}
My Term Model:
public function classrooms()
{
return $this->belongsToMany('App\Classroom')->withTimestamps();
}
public function students()
{
return $this->belongsToMany('App\Student')->withTimestamps();
}
My Student model:
public function terms()
{
return $this->belongsToMany('App\Term')->withTimestamps();
}
public function classrooms()
{
return $this->belongsToMany('App\Classroom')->withTimestamps();
}
What I am doing in my StudentsController is
$term = Term::findOrFail($id);
foreach($term->classrooms as $classroom) {
$studentids = ClassroomStudent::where('classroom_id', '=', $classroom->id)->get();
}
//to get the real student collection
foreach($studentids->student_id as $studentid){
$students = Student::findOrFail($studentid)
}
return view('students.list')->with(['students' => $students]);
In my students.list view, I would simply want to retrieve students:
#foreach($students as $student)
First Name: {{!!$student->first_name!!}}
#endforeach
The error is in this line:
foreach($studentids->student_id as $studentid){
$students = Student::findOrFail($studentid)
}
Undefined property: Illuminate\Database\Eloquent\Collection::$student_id'
However dd($studentids) returned an array and one of the attributes is student_id.
The code is cumbersome and not working.
Thanks for your help
The Goal:
To retrieve the students in the classroom in the term. With many-to-many relationship between classrooms, students and terms.
I think you could be setting the relations not well. Try thinking it well, for example, I think that probably a Student belongsTo a Classroom.
Classroom Model
public function students()
{
return $this->hasMany('App\Student')->withTimestamps();
}
public function terms()
{
return $this->belongsTo('App\Term')->withTimestamps();
}
Term Model:
public function classrooms()
{
return $this->hasMany('App\Classroom')->withTimestamps();
}
Student model:
public function classrooms()
{
return $this->belongsTo('App\Classroom')->withTimestamps();
}
An many to many relation returns an array which it still does when you define the sudentids ->get() also returns an array only ->first() would not return an array but then you do not get all students.
A variable does not turn in an array automatically making your foreach only return the last value.
So to correctly return the values from the students you would most likely get something like this.
Controller:
// Or even bind the term to the url
$term = Term::findOrFail($id);
return view('students.list',compact("term"));
View:
<!-- You could even remove the classroom name/list around it if you purely want to display all students under the term -->
<li>
#foreach($term->classrooms as $classroom) {
<ul>
Classroom: {{ $classroom->name }}
<li>
#foreach($classroom->students as $student)
<ul>
First name: {{ $student->first_name }}
</ul>
#endforeach
</li>
</ul>
#endforeach
</li>
Another simple way to return all students under a term is using the ->whereHas() in your query doing this would be enough
Controller:
$students = Student::whereHas("classrooms",function($q){
$q->whereHas("terms",function($q){
$q->where("id",$termId);
});
})->get();
return view('students.lists',compact("students"));
View:
<li>
#foreach($students as $student)
<ul>
First name: {{ $student->first_name }}
</ul>
#endforeach
</li>
If you want to return specific classrooms within a term or even a user under both you should create 3 controllers one for each of them (only 2 if you do not want to display students separate) and nest your classrooms under terms so you can simply type /terms/1/classrooms/2/ to get the right classroom or /terms/1/classrooms to get all classrooms under a term.