Fetching post comment order by in laravel - laravel

I want to fetch comment order by created at but how can i do that?
I did it as usual order by but it didnot work.
#foreach( $post->comnt->take(1)->orderBy('created_at','DESC') as $comments )
#if($post->comnt)
<div class="comments clearfix">
#foreach( $post->comnt->take(1) as $comments )
<div class="each_coments clearfix">
<p> <span class="comment_profile"><img src="{{ asset('img').'/'.$comments->user->image }}" alt=""></span></p>
<p>{{ $comments->user->username }}{{ $comments->comment }}</p>
</div><?php $last_id = $comments->id ?>
#endforeach
<a data-lastid="#if(!empty($last_id)){{$last_id}}#else{{'0'}}#endif" href="">lode more comments</a>
</div>
<?php unset($last_id); ?>
#endif
Here is my post model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = 'posts';
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->hasMany('App\like');
}
public function comnt()
{
return $this->hasMany('App\comment');
}
}

Maybe
public function comnt()
{
return $this->hasMany('App\comment')->orderBy('created_at','DESC');
}

Related

In my laravel 8, i need to show all the licenses related to a single beat ($id) in the beatreferencing license table with beat_id in the show.blade

//Genre Model//
class Genre extends Model
{
use HasFactory;
protected $table = 'genres';
protected $fillable = [
'name', 'slug', 'status', 'popular',
];
/**
* Get all of the licenses for the user.
*/
public function beat()
{
return $this->hasMany(Beat::class);
}
public function license()
{
return $this->hasManyThrough(license::class, Beat::class);
}
}
//Beat Model//
class Beat extends Model
{
use HasFactory;
protected $table = 'beats';
protected $fillable = [
'genre_id',
'name',
'slug',
'image',
'status',
'new',
'trending',
'meta_title',
'meta_keywords',
];
public function license()
{
return $this->hasMany(License::class,'beat_id', 'id');
}
public function genre()
{
return $this->belongsTo(Genre::class, 'genre_id', 'id');
}
}
//License//
{
use HasFactory;
protected $table = 'licenses';
protected $primaryKey = 'id';
protected $fillable = [
'beat_id',
'license_name',
'beat_name',
'genre',
'bpm',
'key',
'tag_1',
'tag_2',
'time',
'price',
'status',
'popular',
'wav',
'trackout',
'unlimited',
'exclusive',
'image',
'audio',
];
public function beat()
{
return $this->belongsTo(Beat::class, 'id');
}
}
//LicenseController//
public function show($id)
{
$license = License::find($id);
return view('admin.license.show')->with('license', $license,);
}
// Show.blade.php//
#extends('layouts.admin')
#section('content')
<div class="container">
#foreach($licenses->chunk(4) as $license)
<div class="card">
<div class="card-body">
#foreach($licenses as $license)
<div class="">
<img src="{{ asset('assets/uploads/licenses/img/'.$license->image) }}"
alt="image here">
<p>{{ $license->id }}</p>
<p>{{ $license->beat_id }}</p>
<p>{{ $license->beat_name }}</p>
</div>
#endforeach
</div>
</div>`enter code here`
#endforeach
</div>
#endsection
Anytime i try to use #foreach to call {{ $license->beat->id }}, it give me errors like this Error:
Method name must be a string
http://127.0.0.1:8000/licenses/1
Your organization is a bit strange, as I'd expect to see this method called something more like BeatController::showLicenses(). But setting that aside, you should be using route model binding to automate a lot of this stuff. This is what your controller method should look like:
public function show(Beat $beat)
{
return view('admin.license.show')->with('licenses', $beat->licenses);
}
If you define your route with a parameter called beat instead of id, something like this:
Route::get('/admin/license/{beat}', [LicenseController::class, 'show']);
The type hint in the method signature will signal the routing engine to automatically do the database lookup for you. As a bonus, it also handles 404 errors in case in invalid ID is passed.
To get all the licenses related to a single beat, if you have the beat id in the $id variable, you can do the query like this:
License::where('beat_id', $id)->get();
So, your controller function could look like this:
//LicenseController//
public function show($id)
{
$licenses = License::where('beat_id', $id)->get();
return view('admin.license.show')->with('licenses', $licenses);
}
Then in the view you can loop over the licences collection to show each one:
// Show.blade.php//
#extends('layouts.admin')
#section('content')
<div class="container">
#foreach($licenses as $license)
<div class="card">
<div class="card-body">
<div class="">
<img src="{{ asset('assets/uploads/licenses/img/'.$license->image) }}" alt="image here">
<p>License Id: {{ $license->id }}</p>
<p>License Name: {{ $license->license_name }}</p>
<p>License Beat Id: {{ $license->beat_id }}</p>
</div>
</div>
</div>
#endforeach
</div>
#endsection

laravel livewire, how to pass the id or data to another component by click

I have two components Posts and Post, Posts show the posts and by clicking the image I want to show the data of clicked post in another component.
Posts class and component down below:
Component View:
<div class="post" x-data="{open:false}">
#foreach($posts as $post)
<div>
<h1>{{ $post->name }}</h1>
<h3>{{ $post->body }}</h3>
<img #click="open = !open" wire:click="showPost({{ $post->id }})" src="{{ $post->image }}" alt="">
</div>
#endforeach
<livewireL:post>
</div>
Component Class:
class Posts extends Component
{
public $posts, $post;
public function mount(){
$this->posts = Post::all();
}
public function showPost($id){
$post = Post::find($id);
$this->post = $post;
}
public function render()
{
return view('livewire.posts');
}
}
and this is the Post component and class that I want to show the clicked data in this component, I have tried $emit and many as documentation but no result.
Component view which I want to render that data:
<div x-show="open">
<h1>{{ $post->name }}</h1>
<h3>{{ $post->body }}</h3>
<img src="{{ $post->image }}">
</div>
Class which I want to pass data:
class Post extends Component
{
public $post;
public function mount($id)
{
$this->post = \App\Post::find($id);
}
public function render()
{
return view('livewire.post');
}
}
You have to use events to pass data from one component to another component like below.
Component A Blade:
<img #click="open = !open" wire:click="showPost({{ $post->id }})" src="{{ $post->image }}" alt="">
Component A Class:
public function showPost($id){
$post = Post::find($id);
$this->post = $post;
$this->emit('newPost', $post->id);
}
you can now catch that event from other livewire component like this:
Component B Class:
class Post extends Component
{
public $post;
protected $listeners = ['newPost'];
public function mount($id)
{
$this->post = \App\Post::find($id);
}
public function render()
{
return view('livewire.post');
}
public function newPost($postId)
{
// here u have the id in your other component.
}
}
you can achieve this other way also. You can pass the id from your component blade as well check this out.

Get objects of related tables from a collection laravel

I want to pass the result of a searching action but I am facing a problem because it is returning an array and from that all the relationships of the table are not working
result view. For this I can only access the data on my table not the related data through relationships
#extends('layouts.app')
#section('content')
#foreach ($result as $object)
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h3>Details for the animal</h3>
</div>
<div class="card-body">
<div class="col-12">
<p><strong>Id: </strong>{{ $object->id }}</p>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
#endsection
Here is my controller
<?php
namespace App\Http\Controllers;
use App\Animal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class SearchController extends Controller
{
public function index()
{
Animal::all();
return view('search.index');
}
public function postSearch(Request $request)
{
$serial_number = $request->input('search');
$this->getResult($serial_number);
return redirect()->route('result',$serial_number);
}
public function getResult($serial_number){
$result = DB::table('slaughters')->where(function ($query) use ($serial_number) {
$query->where('id','LIKE',"%$serial_number%");
})->latest()->get();
return view('search.result', ['result'=>$result]);
}
}
And my routes
Route::get('/search','SearchController#index')->name('search');
Route::post('/get','SearchController#postSearch');
Route::get('/search/{result}','SearchController#getResult')->name('result');
I would like to access data from the table related to this one too. What am to do
Slaughter model
class Slaughter extends Model
{
protected $guarded = [];
public function user(){
return $this->belongsTo(User::class);
}
public function animal(){
return $this->belongsTo(Animal::class);
}
You must create model Slaughter and define relations.
And then you can get result:
public function getResult($serial_number)
{
$result = Slaughter::with(['name_of_relation_1', 'name_of_relation_2'])->latest()->get();
return view('search.result', ['result'=>$result]);
}
In your Controller:
use App\Slaughter;
public function getResult($serial_number) {
$result = Slaughter::where('id', 'like', "%{$serial_number}%")
->with('user', 'animal')
->latest()
->get();
return view('search.result', compact('result'));
}
In your view you can then access the relationships like so:
{{ $object->user }}
{{ $object->animal }}

Get the user name and comment with article id in Laravel

I have 3 tables users, comments, and articles. I have a route like this:
Route::get('/article/{id}', 'ArticlesController#view');
What I want is when I accessing that route I will get User Name and their comment in this article id.
so here's my view function in ArticlesController:
public function view($id){
$article = Article::with('comments')->find($id);
return view('front.single',compact('article'));
}
and here's my single.blade.php code:
<div class="single-grid">
#section('content')
<h1>{{ $article->title }}</h1>
<p>{{ $article->content }}</p>
#show
</div>
<div class="comment-list">
#foreach($article->comments as $comment)
<ul class="comment-list">
<div class="comment-grid">
<img src="/images/avatar.png" alt=""/>
<div class="comment-info">
<h4>{{ $comment->user->name }}</h4>
<p>{{ $comment->comment }}</p>
<h5>{{ $comment->created_at->diffForHumans() }}</h5>
Reply
</div>
<div class="clearfix"></div>
</div>
</ul>
#endforeach
</div>
I'm not sure what how to do it since it gives me error like this:
"Call to undefined relationship [comment] on model [App\User]."
I already define the relation in each model. here's my articles model:
public function comments(){
return $this->hasMany(Comment::class);
}
public function user(){
return $this->belongsTo(User::class);
}
My comment model:
public function article(){
$this->belongsTo(Article::class);
}
public function user(){
$this->belongsTo(User::class);
}
and here's my User model:
public function articles(){
return $this->hasMany(Article::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
public function publish(Article $article){
$this->articles()->save($article);
}
here's my table structure:
-users(id,name,email,password,remember_token,created_at,updated_at)
-comments(id,user_id,article_id,comment,created_at,updated_at)
-articles(id,user_id,title,content,created_at,updated_at)
so how can I can User Name just by using this route? thanks.
on Your Comment Model, You need to replace articles to article
public function article(){
$this->belongsTo(Article::class);
}
also, if you want to get user specific comments, than you need to change your controller action code from
$article = Article::with('user.comment')->find($id) to
$article = Article::with('user.comments')->find($id);
I think that your issue comes from the use of compact function : an array is passed to the view instead of an object.
Can you try it like this :
// Controller
public function view($id) {
$article = Article::findOrFail($id);
return view('front.single', $article);
}
<!-- View -->
#foreach($article->comments as $comment)
{{ $comment->user->name }}
{{ $comment->comment }}
{{ $comment->created_at->diffForHumans() }}
#endforeach

Individual profile pages and searches Laravel 5.2

Having a real confusing time with this project, my issue is I'm trying to get my search working but for some reason its not pulling results from my query when there is that information in the database, also when I click on the username in the top corner of my page, it should redirect to the user page but instead I get this error "NotFoundHttpException in Application.php line 879:" with the URl looking like this "http://localhost/WorldLink/users/firstName%20=%3E%20Auth::user%28%29-%3EfirstName" and I have exhausted all other means of trying to fix it so I'm back for some help! my code is below Im using laravel 5.2:
Users.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model
{
protected $table = 'users';
protected $fillable = [
'id', 'firstName', 'lastName', 'bio', 'homeLocation', 'currentLocation', 'email', 'password',
];
public function getName()
{
if ($this->firstName && $this->lastName) {
return "{$this->firstName} {$this->lastName}";
}
if ($this->firstName) {
return $this->firstName;
}
return null;
}
public function getNameOrLocation()
{
return $this->getName() ?: $this->currentLocation;
}
public function getFirstNameOrLocation()
{
return $this->firstName ?: $this->currentLocation;
}
public function getAllAvatarsUrl()
{
return "https://www.gravatar.com/avatar/{{ md5($this->email) }}?d=mm&s=40";
}
}
SearchController.php:
<?php
namespace App\Http\Controllers;
use DB;
use App\Users;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class SearchController extends BaseController
{
public function getResults(Request $request)
{
$query = $request->input('query');
if (!$query) {
return back();
}
$users = Users::where(DB::raw("CONCAT(firstName, ' ', lastName)"), '
LIKE', "%{$query}%")
->orWhere('currentLocation', 'LIKE', "%{$query}%")
->get();
return view('search/results')->with('users', $users);
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
class ProfileController extends BaseController
{
public function getProfile($firstName)
{
$users = User::where('firstName', $firstName)->first();
if (!$users) {
abort(404);
}
return view('profile.index')
->with('users', $users);
}
}
userblock.blade.php
<div class="media">
<a class="pull-left" href="{{ route('profile/index', ['firstName' => $users->firstName]) }}">
<img class="media-object" alt="{{ $users-getNameOrLocation() }}" src="{{ $users->getAllAvatarsUrl() }}">
</a>
<div class="media-body">
<h4 class="media-heading">{{ $users->getNameOrLocation() }}</h4>
</div>
#if ($users->currentLocation)
<p>{{ $users->currentLocation }}</p>
#endif
results.blade.php
#extends('layouts.app')
#section('content')
<h3>Search Results for "{{ Request::input('query') }}"</h3>
#if (!$users->count())
<p>No Results Found</p>
#else
<div class="row">
<div class="col-lg-12">
#foreach ($users as $user)
#include('users/partials/userblock')
#endforeach
</div>
</div>
#endif
#endsection
And finally my two routes, the problem is connected in here somewhere I just cant find where its going wrong.
Route::get('/search', [
'uses' => '\App\Http\Controllers\SearchController#getResults',
'as' => 'search/results',
]);
Route::get('/users/{firstName}', [
'uses' => '\App\Http\Controllers\ProfileController#getProfile',
'as' => 'profile/index',
]);
The Link:
#if (Auth::guest())
<li>Login</li>
<li>Register</li>
#else
<ul class="nav navbar-nav">
<form class="navbar-form navbar-left" role="search" action="{{ route('search/results') }}">
<input type="text" class="form-control" placeholder="Search" name="query">
</form>
<li>{{ Auth::user()->firstName }}</li>
<li>Timeline</li>
<li>Link</li>
<li>Journeys <span class="journey-num">{{ Auth::user()->journeys }}</span></li>
<li>Forum</li>
</ul>
Defo quoting incorrectly
....
<li>{{ Auth::user()->firstName }}</li>
....
Note closing ' moved to after firstName array key.
That should at least fix the link

Resources