I want to display username of comment's owner, however, comments table has user_id only - php

After I send the variable that contains the comments to the view, I can only display the user id. This is why I need to somehow foreach through all the comments and based on their user_id to add a new key-pair value with username-username and send it to the view afterwards. Unfortunately, I'm having trouble figuring how to do that.
public function specificImage($id){
$similarImages = null;
$image = Image::with('comments.user')->find($id);
$subImages = Image::where('parent_id', $id)->get();
$views = $image->views;
$image->views = $views + 1;
$image->save();
$authorId = $image->user_id;
$author = User::find($authorId);
$comments = Comment::where('image_id', $id)->get();
$recentImages = Image::where('parent_id', NULL)->where('user_id', $authorId)->orderBy('created_at', 'desc')->limit(9)->get();
$tag = Tag::whereHas('images', function($q) use ($id) {
return $q->where('taggable_id', $id);
})->first();
if (!empty($tag)) {
$tagId = $tag->id;
}
if (!empty($tagId)) {
$similarImages = Image::where('parent_id', NULL)->whereHas('tags', function($q) use ($tagId) {
return $q->where('tag_id', $tagId);
})->orderBy('created_at', 'desc')->limit(9)->get();
}
return view('specificImage', ['image' => $image,'subImages' => $subImages, 'recentImages' => $recentImages, 'similarImages' => $similarImages, 'author' => $author, 'comments' => $comments]);
}
Table:
Table: Comments
Columns: id, user_id, image_id, comment
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->morphToMany('App\Tag', 'taggable');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function updateVotes()
{
$this->upvotes = Vote::where('image_id', $this->id)->where('vote', true)->count();
$this->downvotes = Vote::where('image_id', $this->id)->where('vote', false)->count();
$this->save();
}
public function updateComments()
{
$this->comments = Comment::where('image_id', $this->id)->count();
$this->save();
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function image(){
return $this->belongsTo('App\Image');
}
public function user(){
return $this->belongsTo('App\User');
}
}
User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function images(){
return $this->hasMany('App\Image');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function roles(){
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function hasAnyRole($roles) {
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)){
return true;
}
}
} else {
if ($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if ($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
}
Blade
#extends('layouts.app')
#section('content')
<div class="specific-image-flexbox">
<div class="specific-image-column">
<div class='specific-image-container'>
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$image->file_name)}}' alt='Random image' />
#foreach($subImages as $subImage)
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$subImage->file_name)}}' alt='Random image' />
#endforeach
</div>
</div>
<div class="artwork-info-column">
<div class="artwork-info-container">
<p class='title'>{{ $image->name }}<p>
<p class='author'>на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
#if(Auth::user())
#if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
<a class='placeholderDelete' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'><i class="far fa-trash-alt"></i> Изтрий изображението</a>
#endif
#endif
<p class='description'>{{ $image->description }}</p>
<p class='description'>Техника: {{ $image->medium }}</p>
<p><i class="far fa-eye"></i> {{ $image->views }} Преглеждания</p>
<p><i class="far fa-thumbs-up"></i> {{ $image->upvotes }} Харесвания</p>
<p class='commentsCount'><i class="far fa-comments"></i> {{ $image->comments }} Коментари</p>
<a class='downloadImage' href="{{url("storage/uploads/images/specificImages/".$image->file_name)}}" download="{{ $image->name }}"><i class="fas fa-file-download"></i> Изтегли</a>
<!--<a class='placeholderDelete fas fa-expand' href='{{url("storage/uploads/images/specificImages/".$image->file_name)}}'></a>-->
<div class='social-container'>
<div class="addthis_inline_share_toolbox"
data-url="{{ url()->full() }}"
data-title="{{ $image->name }} by {{ $author->username }}"
data-description="{{ $image->description }}"
data-media="{{url("storage/uploads/images/specificImages/".$image->file_name)}}">
</div>
</div>
#if(!empty($recentImages))
#if(count($recentImages) >= 9)
<p class='author'>Още произведения на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
<div class="more-images-container">
#foreach($recentImages as $recentImage)
<div class="more-images-container-element">
<a href='{{url("image/".$recentImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$recentImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#if(!empty($similarImages))
#if(count($similarImages) >= 9)
<p class='similar-images'>Подобни произведения</p>
<div class="similar-images-container">
#foreach($similarImages as $similarImage)
<div class="similar-images-container-element">
<a href='{{url("image/".$similarImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$similarImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#auth
<div class='postComments'>
<form method='POST' action=''>
<textarea class='comment-section' name='comment'></textarea>
<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
<input type="hidden" name="image_id" value="{{ $image->id }}">
<button class='postComment submit' type='submit' name='commentSubmit'>Изпрати</button>
</form>
</div>
#endauth
<div class='comments'>
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach
</div>
</div>
</div>
</div>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment') }}';
var urlLike = '{{ route('vote') }}';
</script>
#endsection

I would suggest adding the user relationship to your Comment model as well:
class Comment extends Model
{
public function image()
{
return $this->belongsTo('App\Image');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
You can then eager load the relationships and then access them in your blade file:
public function specificImage($id)
{
$image = Image::with('comments.user')->find($id);
return view('specificImage', ['image' => $image]);
}
Then in your blade file you would have something like:
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach

Related

ArgumentCountError Too few arguments to function App\Http\Controllers\Shop\CartController::addToCart()

So this function is supposed to add the product into a cart, but i've been getting the error
Too few arguments to function
App\Http\Controllers\Shop\CartController::addToCart(), 0 passed in
C:\xampp\htdocs\nerdS\vendor\laravel\framework\src\Illuminate\Routing\Controller.php
on line 54 and exactly 1 expected
I tried changing key words here and there on my controller, but nothing seems to do it. This is the the controller:
<?php
namespace App\Http\Controllers\Shop;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
Use App\Models\Product;
Use App\Models\Order;
class CartController extends Controller {
public function placeOrder() {
if(session('id')){
if(\Cart::count()){
\App\Models\Order::store();
return redirect('shop')->with('status', 'Thank you for buying!');
}
return redirect('cart');
}
session(['place-order-process' => true]);
return redirect('login')->with('status', 'To complete your order, please log in. Not a member yet? Join the club! ');
}
public function deleteCart() {
\Cart::destroy();
return redirect('shop')->with('status', 'The cart is now empty.');
}
public function deleteItem($rowId) {
\Cart::remove($rowId);
return redirect('cart')->with('status', 'The item was deleted.');
}
public function updateCart(Request $request){
\Cart::update($request->rowId, $request->quantity);
$data = [
'cart_count' =>\Cart::count(),
'cart_total' => \Cart::total(),
'product_total' => \Cart::get($request->rowId)->total(),
];
return json_encode($data);
}
public function displayCart() {
\Cart::setGlobalTax(0);
$data['items'] = \Cart::content();
$data['total'] = \Cart::total();
return view('cart.cart', $data);
}
public function addToCartByQty (Request $request){
\App\Models\Product::addToCart($request->id, (int) $request->quantity);
return \Cart::count();
}
public function addToCart ($id){
\App\Models\Product::addToCart($id);
return \Cart::count();
}
}
My model for products:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
class Product extends Model {
public function category() {
return $this->belongsTo('App\Models\Category');
}
public static function deleteProduct($id){
$product = self::findOrFail($id);
Storage::disk('public')->delete($product->image);
self::destroy($id);
}
public static function editProduct($request){
$product = self::findOrFail($request->product);
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
if ($request->image){
Storage::disk('public')->delete($product->image);
$product->image = $request->image->store('images/products', 'public');
}
$product->save();
}
public static function getProductById($id){
return self::finOrFail($id);
}
public static function store($request){
$product = new self();
$product->name = $request->name;
$product->slug = $request->slug;
$product->price = $request->price;
$product->description = $request->description;
$product->category_id = $request->category;
$product->image = $request->image->store('images/products', 'public');
$product->save();
}
public static function getAll(){
return self::orderBy('slug')->get();
}
public static function addToCart($id, $qty = 1){
$product = self::findOrFail($id);
\Cart::add([
'id' => $product->id,
'name' => $product->name,
'qty' => $qty,
'price' => $product->price,
'weight' => 0
]);
}
public static function getProduct($cat, $pro){
$product = self::where('slug', $pro)->firstOrFail();
$product_cat = $product->category->slug;
//retun ($product_cat === $cat) ? $product_cat: false;
abort_if($product_cat !== $cat, 404);
return $product;
}
//use HasFactory;
}
The page view:
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart')}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
and my route:
Route::get('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
You need to pass the $product->id in the form action's url(). That route parameter needs to be there so that it is received in the addToCart method in controller
#extends('template')
#section('content')
<div class="row">
<div class="col-md-7">
<h1> {{$product->name}} </h1>
<p>{{$product->descriprion}}</p>
<p> Only for: ₪ {{$product->price}}</p>
<form id="add-to-cart" method="post" action="{{url('add-to-cart/' . $product->id)}}">
#csrf
<div class="number">
<span class="minus"> - </span>
<input type="text" value="1" readonly/>
<span class="plus"> + </span>
<input type="hidden" value="{{$product->id}}">
<button class="btn btn-primary" type="submit"> Add </button>
</div>
</form>
<div class="col-md-5">
<img src="{{asset('storage/' . $product->image)}}">
</div>
</div>
</div>
#endsection
And you have declared your route as get instead of post. Following restful conventions your route should be declared as a post route
Route::post('add-to-cart/{product_id}', 'App\Http\Controllers\Shop\CartController#addToCart');
There is a mismatch in your route (Route::get('add-to-cart/{product_id}) and the parameter passed in your function addToCart ($id)
Had u provide product_id in route (add-to-cart/{product_id})?
Since you are using a GET route vs POST, you have to change your form method from POST to GET and also pass the id in the action url -
<form id="add-to-cart" method="get" action="{{url('add-to-cart/' . $product->id)}}">
Change your definition of addToCart method in CartController as following.
public function addToCart (Request $request, $id)
{
\App\Models\Product::addToCart($id);
return \Cart::count();
}

Trying to get property 'slug' of non-object 5.7

Looking to solve this error that I'm getting when trying to display some data to the view. I'm working with v5.7 and I have a feeling it might be something with the index method in my controller, I could be very wrong. If there is any more info that is needed please let me know.
Trying to get property 'slug' of non-object (0)
Route:
Route::get('/category/{category}','BlogController#category')->name('category');
BlogCategory Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class BlogCategory extends Model
{
protected $fillable = ['title', 'slug'];
public function posts()
{
return $this->hasMany(Post::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
Post Model
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
Controller:
protected $limit = 3;
public function index()
{
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = Post::with('author')
->latestFirst()
->published()
// ->filter(request()->only(['term','year','month']))
->simplePaginate($this->limit);
return view('pages.frontend.blog.index', compact('posts', 'categories'));
}
public function category(BlogCategory $category)
{
$categoryName = $category->title;
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = $category->posts()
->with('author')
->latestFirst()
->published()
->simplePaginate($this->limit);
return view("pages.frontend.blog.index", compact('posts', 'categories', 'categoryName'));
}
View:
#foreach ($posts as $post)
<article class="post-item">
#if ($post->image_url)
<div class="post-item-image">
<a href="{{ route('blog.show', $post->slug) }}">
<img src="{{ $post->image_url }}" alt="">
</a>
</div>
#endif
<div class="post-item-body">
<div class="padding-10">
<h2>
{{ $post->title }}
</h2>
{!! $post->excerpt_html !!}
</div>
<div class="post-meta padding-10 clearfix">
<div class="pull-left">
<ul class="post-meta-group">
<li>
<i class="fa fa-user"></i>
{{ $post->author->name }}
</li>
<li>
<i class="fa fa-clock-o"></i>
<time> {{ $post->date }}</time>
</li>
<li>
<i class="fa fa-folder"></i>
{{ $post->category->title }}
</li>
<li>
<i class="fa fa-comments"></i>
4 Comments
</li>
</ul>
</div>
<div class="pull-right">
Continue Reading »
</div>
</div>
</div>
</article>
#endforeach
Post table
Blog Cats table
The belongsTo function accepts a second argument for the name of the foreign key in your posts table, if you do not provide it the framework will try to guess what is the foreign key column name giving the name of the function as pattern, in your case category(), so the framework is searching for category_id, however, your foreign key column name is blog_category_id.
public function category()
{
return $this->belongsTo(BlogCategory::class, 'blog_category_id');
}
You should call the category relationship in the index of your controller, if this view is related to the index method!
public function index()
{
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = Post::with('author')
->category()
->latestFirst()
->published()
// ->filter(request()->only(['term','year','month']))
->simplePaginate($this->limit);
return view('pages.frontend.blog.index', compact('posts', 'categories'));
}

How to set limit to 4 users?

I have this section on my website: [1]: https://imgur.com/a/xJjb1ww "section"
I want to limit this photos to show max. 4 contacts, because if I have more, it looks bad.How can I add to this a max. limit to show?Sorry for so much code but I don't know exactly where is my function.Thank you.
Here is my view:
<!-- Tabs Widget -->
<div class="tab-content" style="padding: 8px !important">
<?php $count_user = 0; ?>
#foreach($user->contact as $contact)
<div id="contact<?php echo $count_user++; ?>" class="tab-pane magazine-sb-categories <?php if($count_user == 1){ echo "active"; } ?>">
<div class="row team-v1">
<ul class="list-unstyled col-xs-12" style="margin-bottom: -10px">
<li><h3 style="margin-top: 5px !important;text-transform: none; " >
#if($contact->role[0]->slug == "individuals")
<i style="font-size: 13px;" class="icon-user"></i>
#elseif($contact->role[0]->slug =='organizations')
<i style="font-size: 13px;" class="icon-hotel-restaurant-172 u-line-icon-pro fa- fa-lg"></i>
#endif
<a style="font-size: 14px" href="{{ url('') }}/{{ $contact->username }}">{{ $contact->username }}</a></h3>
<p>
<strong><i class="icon-real-estate-020 u-line-icon-pro"></i> : </strong><a>{{ $contact->country->country }}</a><br>
<strong><i class="icon-screen-tablet fa-" aria-hidden="true"></i> : </strong><a>{{ $contact->industry->industry }}</a><br>
#if($contact->role[0]->slug == "individuals")
#foreach($contact->career_path as $career_path)
<i style="font-size: 13px" class="icon-speedometer"></i> : {{ $career_path->functions->function }}
#break;
#endforeach
#elseif($contact->role[0]->slug =='organizations')
<i style="font-size: 13px" class="icon-frame fa-"></i> : {{ $user->organization_type->organization_type }}<br>
#endif
</p>
</ul>
</div>
#endforeach
Here is my User.php:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class User extends Authenticatable
{
use SoftDeletes;
/**
* The attributes that are mass assignable.
*
* #var array
*/
// protected $fillable = [
// 'name', 'email', 'password',
// ];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
// protected $hidden = [
// 'password', 'remember_token',
// ];
public function comment()
{
return $this->hasMany('App\Comment');
}
public function country()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\Country','country_id','id');
}
public function organization_type()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\OrganizationType');
}
public function industry()
{
// return $this->hasOne('App\Country','state_country_id','id');
return $this->belongsTo('App\Industry');
}
public function career_path()
{
return $this->hasMany('App\CareerPath');
}
public function education()
{
return $this->hasMany('App\Education');
}
public function about()
{
return $this->hasOne('App\About');
}
public function portfolio()
{
return $this->hasOne('App\Portfolio');
}
public function language_skills_selected()
{
return $this->belongsToMany('App\LanguageSkill','language_skills_selected','user_id','language_skills');
}
public function offices_branch()
{
return $this->hasMany('App\OfficesBranch');
}
public function my_alert()
{
return $this->hasOne('App\MyAlert');
}
public function privancy_setting()
{
return $this->hasOne('App\PrivancySetting');
}
public function event()
{
return $this->hasMany('App\Event');
}
public function news()
{
return $this->hasMany('App\News');
}
public function opinion()
{
return $this->hasMany('App\Opinion');
}
public function career_solution()
{
return $this->hasMany('App\CareerSolution');
}
public function contact()
{
return $this->belongsToMany('App\User','contacts','contact_id','user_id');
}
public function user()
{
return $this->belongsToMany('App\User','contacts','user_id','contact_id');
}
}
public function contact()
{
return $this->belongsToMany('App\User','contacts','contact_id','user_id')->limit(4);
}
This should be done in User.php.
If you have a relationship set up for $user->contact (i.e. hasMany), you should be able to call it like this in your loop in your blade file:
$limitedContacts = $user->contact->limit(4);
#foreach($limitedContacts as $contact)
....
#endforeach

How I use relationship in blade template (hasOne) || Laravel

Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?
If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem
Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach
I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}

Why does /user/{username} not show up automatically?

My route:
Route::get('/user/{username}', [
'uses' => '\MostWanted\Http\Controllers\ProfileController#getProfile',
'as' => 'profile.index',
]);`
My Controller:
use MostWanted\Models\User;
use Illuminate\Http\Request;
class ProfileController extends Controller{
public function getProfile($username){
$user = User::where('username', $username)->first();
if (!$user) {
abort(404);
}
return view('profile.index')
->with('user', $user);
}
}
The username field in the database exists and is filled in. When I go into search, the users pop up but the URL always misses out on the {username}. When I manually enter the {username} e.g. mostwanted.dev:8000/user/yes.man, it functions normally.
EDIT: This is the view that is hooked to (userblock.blade.php)
<div class="media">
<a class="pull-left" href="{{ route('profile.index', ['username' => $user->username]) }}">
<img class="media-object" alt="{{ $user->getNameOrUsername() }}" src="">
</a>
<div class="media-body">
<h4 class="media-heading">
{{ $user->getNameOrUsername() }}
</h4>
#if ($user->location)
<p>{{ $user->location }}</p>
#endif
</div>
Here is the User.php:
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'users';
protected $fillable = [
'username',
'first_name',
'last_name',
'email',
'password',
'location',
'gender',
'date_of_birth',
];
protected $hidden = [
'password',
'remember_token',
];
public function getName()
{
if ($this->first_name && $this->last_name) {
return "{$this->first_name} {$this->last_name}";
}
if ($this->first_name) {
return $this->first_name;
}
return null;
}
public function getUsername()
{
if ($this->first_name && $this->last_name) {
return "{$this->first_name}.{$this->last_name}";
}
if ($this->first_name) {
return $this->first_name;
}
return null;
}
public function getNameOrUsername()
{
return $this->getName() ?: $this->username;
}
public function getUsernameOrName()
{
return $this->getUsername() ?: $this->username;
}
public function getFirstNameOrUsername()
{
return $this->first_name ?: $this->username;
}
}
EDIT**: Search results view:
#extends('templates.default')
#section('content')
<h3>Your search for "{{ Request::input('query') }}"</h3>
#if (!$users->count())
<p>No results found.</p>
#else
<div class="row">
<div class="col-lg-12" style="padding: 50px;">
#foreach ($users as $user)
#include('user/partials/userblock')
#endforeach
</div>
</div>
#endif
#stop
SearchController:
use DB;
use MostWanted\Models\User;
use Illuminate\Http\Request;
class SearchController extends Controller
{
public function getResults(Request $request)
{
$query = $request->input('query');
if (!$query) {
return redirect()->route('home');
}
$users = User::where(DB::raw("CONCAT(first_name, ' ', last_name)"),
'LIKE', "%{$query}%")
->orWhere('username', 'LIKE', "%{query}%")
->get();
return view('search.results')->with('users', $users);
}
}
EDIT***:
ProfileController:
use MostWanted\Models\User;
use Illuminate\Http\Request;
class ProfileController extends Controller
{
public function getProfile($username)
{
$user = User::where('username', $username)->first();
if (!$user) {
abort(404);
}
return view('profile.index')
->with('user', $user);
}
}
Try to modify userblock.blade.php
<div class="media">
<a class="pull-left" href="{{ url('user/'.$user->username) }}">
<img class="media-object" alt="{{ $user->getNameOrUsername() }}" src="">
</a>
<div class="media-body">
<h4 class="media-heading">
{{ $user->getNameOrUsername() }}
</h4>
#if ($user->location)
<p>{{ $user->location }}</p>
#endif
</div>

Categories