i have post table and i have comment table i have made them with laravel
i made a IndexController and it has a method that returns all of my posts by their title;
i also return and compact comment of each post and show them under each post content but i have to pass the post id to comment table by myself
for example i have a post with id=7 and i have to pass the 7 to post_id column of comment table
i have to write a query something like this
select id from posts where title=$title
with this query i want to select post id by post title and pass it to post_id in my comment table
this my index controller
public function single($title)
{
$posts = Post::where('title', $title)->get();
$comments = Comment::where([
['post_id', 7],
['verify',1]
])->orderBy('id', 'desc')->get();
return view('main.single', compact('posts', 'comments'));
}
this is comment controller
public function store(Request $request)
{
Comment::create([
'post_id' => $request['post_id'],
'user_id' => Auth::user()->id,
'message' => $request['message'],
]);
}
and also this my single blade file code
#foreach($comments as $comment)
<div class="container">
<div class="bg-secondary bg-opacity-10 p-3 mb-4">
<div>
<p class="fw-bold">{{$comment->user->first_name.' '.$comment->user->last_name}}
<br>
<span class="text-muted text-small-14 fw-light">{{$comment->created_at}}</span>
</p>
</div>
<div class="mt-0">
</div>
<div>
{{$comment->message}}
</div>
</div>
</div>
#endforeach
and also i use laravel 8
You can do the following if you don't want to pass by yourself, assuming your relationships are correct. If not, feel free to include them in your current question, and I can help with those too.
public function single($title)
{
$post = Post::with(['comments' => function ($query) {
$query->where('verify', 1)->orderBy('id', 'desc');
}])->where('title', $title)->first();
return view('main.single', compact('post'));
}
This will allow you to pass just a post to your blade view.
Now instead of
#foreach($comments as $comment)
You can
#foreach($post->comments as $comment)
Related
I have a basic laravel 9 crud app.
There I have two tables in my db. companies and employees.
I'm trying to display single-user details on my employees.show blade
All my data is displayed correctly but when I try to print user's company, I'm kept getting the following error.
Property [company] does not exist on the Eloquent builder instance.
Following is my employee model
protected $fillable = [
'first_name', 'last_name', 'email', 'phone', 'company_id'
];
public function company()
{
return $this->belongsTo(Company::class);
}
and the following is the show function in my controller
public function show(Employee $employee)
{
$data = Employee::with('company')->where('id', '=', $employee->id);
return view('employees.show', compact('employee','data'));
}
and this is my show.blade
<div class="row mb-4">
<label class="col-sm-2 col-label-form"><b>Company</b></label>
<div class="col-sm-10">
{{ $data->company->name }}
</div>
</div>
How can I display the company properly...
I have company_id as a foreign key in my employees' table...
I have following when I dd $data
You're returning a QueryBuilder from the Employee query in your show() function. You want to add ->get() to return a collection or Employee records:
public function show(Employee $employee)
{
$data = Employee::with('company')->where('id', '=', $employee->id)->get();
return view('employees.show', compact('employee','data'));
}
I think the problem in Query for get data. In employees.show you only show one data then and in controller you got collection of data as array. So your single data element can't access because it is array and for execution you need to add foreach loop for that.
Here you need to change query method from get() to first() and it will resolve your issue.
Your show function code looks like this
public function show(Employee $employee)
{
$data = Employee::with('company')->where('id', '=', $employee->id)->first();
return view('employees.show', compact('employee','data'));
}
Your employees.show blade looks like this
<div class="row mb-4">
<label class="col-sm-2 col-label-form"><b>Company</b></label>
<div class="col-sm-10">
{{ $data->company->name }}
</div>
</div>
I'm new to Laravel and I'm trying to make a post where the user's post can receive likes from other users. But I'm trouble at when you click the user, it was suppose to direct to the users page where you can see all its post and the likes the it received. This is the code that suppose to do that work:
This is the controller:
public function index(User $user)
{
$posts = $user->posts()->with('user', 'likes')->get();
return view('users.posts.index', [
'user' => $user,
'posts' => $posts,
]);
}
}
and this is the view/template:
<div class="flex justify-center">
<div class="w-8/12 bg-white p-6 rounded-lg">
{{$user->name}}
</div>
</div>
I don't know what's the problem though, or is it a bug with Laravel eager loading?
But unfortunately it only returns a blank page, there's no error though.
The thing is after putting this code inside dump and die, there's data showing from the database. I don't why it doesn't show. Can someone help me with this problem? Much appreciated
Following this tutorial: https://www.youtube.com/watch?v=MFh0Fd7BsjE
Tutorial Github: https://github.com/codecourse/posty-traversy-media
If you want to access the posts you can iterate through them:
#foreach($posts as $post)
{{ $post->title }}
{{ $post->likes->count() }}
#endforeach
Not sure what data or relationships you want to access.
Check your route whether it has a user id for model injection
eg:/index/{user}
also in your blade example, there is no posts are used.you are using the user object
public function index(User $user)
{
$posts = $user->posts()->with('user', 'likes')->get();
return view('users.posts.index')->with([
'user' => $user,
'posts' => $posts,
]);
}
I want to show my product in a single page but I have "Property [name] does not exist on this collection instance." error
blade:
<div class="title">
<h2>{{ $singleproduct->name }}</h2>
</div>
<div class="single-product-price">
<h3>{{ $singleproduct->price }}</h3>
</div>
<div class="single-product-desc">
<p>{!! $singleproduct->explain !!} </p>
</div>
controller:
public function show()
{
$singleproduct = Singleproduct::get();
return view('UI.store.SingleProduct' , compact('singleproduct' ));
}
route:
Route::get('/singleproduct/{product}' , 'admin\SingleproductController#show');
You have a Collection of potentially many or no Singleproducts. If you only want 1 you would use first.
Most likely because this is a show route you want a specific Singleproduct, which I will guess you are passing an 'id' via the URL.
public function show($product)
{
$singleproduct = Singleproduct::findOrFail($product);
return view('UI.store.SingleProduct', compact('singleproduct'));
}
Now in the view you know that singleproduct is definitely an instance of Singleproduct and is accessible.
You need to select only one product not all of them,
so you can update your show method like this
using the route model binding you can read more about this awesome feature in laravel docs
public function show(Singleproduct $product)
{
return view('UI.store.SingleProduct' , compact('product' ));
}
Solution: I used db facade, DB::select() to run raw sql query.
I have two tables users(id, username, city, country) and friends(id, user_id, friend_id, status). The 'users' table stores the user information and 'friends' table store the currently logged in user's id, friend_id is the id of the user who sent a friend request to the current user and status will be 'received'. I want to show information of the users to sent requests to the current user. Is my database query syntax correct? I can see correct output if I don't use the nested subquery. Thanks in advance!
My DB query:
$friendrequests = DB::table('users')->select(['username','city','country'])->where('id',DB::table('friends')->select('friend_id')->where([['status','received'],['user_id',$user->id]]));
My html:
#extends('layouts.master')
#section('title')
Friend Requests
#endsection
#section('content')
#include('includes.message-block')
<section class="row requests">
<div class="col-md-6 col-md-offset-3">
<header><h3>Friend Requests</h3></header>
<div class="requestlist">
<header><h2>You have request from:</h2></header>
#foreach($users as $user)
<p>Name: {{ $user->username }}<br />City: {{ $user->city }}<br />Country:{{ $user->country }}</p>
<div class="interaction">
//stuff here
</div>
#endforeach
Back
</div>
</div>
</section>
#endsection
The route:
Route::get('/friendrequests',[
'uses' => 'FriendController#getFriendRequests',
'as' => 'friendrequests',
'middleware' => 'auth'
]);
The controller (works if I don't use the nested subquery):
public function getFriendRequests()
{
$user = Auth::user();
$friendrequests = DB::table('users')
->select(['username','city','country'])
->where('id',
DB::table('friends')->select('friend_id')->where([['status','received'],['user_id',$user->id]])->get())->get();
return view('friendrequests',['users' => $friendrequests]);
}
You can solve this problem with the approach of "hasManyThrough". In your User's model you should do something like this:
class User extends Model{
//... your code here
public function possibleFriends(){
$this->hasManyThrough(User::class, Friend::class, 'friend_id', 'id')->wherePivot('status', 'received');
}
}
More details in the official docs.
Please try this may be helpful
$friendrequests = DB::table('users')
->select(['username','city','country'])
->whereIn('id', function($query) use($user) {
$query->select('friend_id')
->from('friends')
->where('status', 'received')
->where('user_id', $user->id);
})->get();
so i want to display post in my index page but only the posts that are reviewed by the admin. so i added another column in my database table post which is called "review" which is integer. So this is what i have in hand.
in my controller i have this
public function index()
{
$this->layout->content = View::make('partials.index',
array(
'posts' => Post::paginate(9)
));
}
and in my index page i have this
#section('content')
<div class="dashboard">
#foreach (array_chunk($posts->getCollection()->all(),2) as $row)
<div class="row">
#foreach($row as $post)
<article class="col-md-4 effect4" id="dash-box">
<p></p>
<c>{{$post->content}}</c><br>
<b>{{$post->title}}</b><br>
<d>posted..{{$post->created_at->diffForHumans()}}</d>
<hr>
</article>
#endforeach
</div>
#endforeach
<div class="page">
{{$posts->appends(Request::only('difficulty'))->links()}}
</div>
</div>
#stop
Help im newbie here i hope someone can help me out with this one hoping for a reply thanks
Just call:
Post::whereReview(1)->paginate(9);
Please read the documentation (and also the one for the query builder since these pages apply to Eloquent as well)
You can just add a where() call to the query:
$posts = Post::where('review', '=', 1)->paginate(9);
Or a shorter version (= is the default operator)
$posts = Post::where('review', 1)->paginate(9);
Or even with a dynamic method name:
$posts = Post::whereReview(1)->paginate(9);
Also you can use true instead of 1. Laravel will convert it:
$posts = Post::whereReview(true)->paginate(9);
There is also no need to do chunking that complicated:
#foreach (array_chunk($posts->getCollection()->all(),2) as $row)
You can just use the chunk method on any collection:
#foreach ($posts->chunk(2) as $row)