Can someone tell me what to do in this error.
The error is in this line. 'posts' => $author->posts->load('category', 'author')
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->posts->load('category', 'author'),
]);
});
this is my controller
class PostController extends Controller
{
public function index()
{
return view('frontend.posts', [
"title" => "All Posts",
// "posts" => Post::all()
"posts" => Post::latest()->get()
]);
}
public function show(Post $post)
{
return view('frontend.post', [
"title" => "Single Post",
"post" => $post
]);
}
}
this is my models
class Post extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $with = ['category', 'author'];
public function category(){
return $this->belongsTo(Category::class);
}
public function author(){
return $this->belongsTo(User::class, 'user_id');
}
}
and this is my user models
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
public function post(){
return $this->hasMany(Post::class);
}
}
I have this previous error to "foreach() argument must be of type array|object, null given".
I want to display blog posts from certain users.
This is the code from posts.blade.php.
#foreach ($posts as $post)
<div class="p-t-32">
<h4 class="p-b-15">
<a href="/posts/{{ $post->slug }}"
class="ltext-108 cl2 hov-cl1 trans-04">
{{ $post->title }}
</a>
</h4>
<p class="stext-117 cl6">
{{ $post->excerpt }}
</p>
<div class="flex-w flex-sb-m p-t-18">
<span class="flex-w flex-m stext-111 cl2 p-r-30 m-tb-10">
<span>
<span class="cl4">By</span> <a class="stext-111 cl2 hov-cl1 trans-04" href="/authors/{{ $post->author->username }}">{{ $post->author->name }}</a>
<span class="cl12 m-l-4 m-r-6">|</span>
</span>
<span>
<a class="stext-111 cl2 hov-cl1 trans-04" href="/categories/{{ $post->category->slug }}">{{ $post->category->name }}</a>
<span class="cl12 m-l-4 m-r-6">|</span>
</span>
<span>
8 Comments
</span>
</span>
<a href="/posts/{{ $post->slug }}" class="stext-101 cl2 hov-cl1 trans-04 m-tb-10">
Continue Reading
<i class="fa fa-long-arrow-right m-l-9"></i>
</a>
</div>
</div>
#endforeach
The name of the relationship in User is post but in your controller you used posts.
The following should probably work:
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->load('post.category'),
]);
});
Related
I try to show image from product_galleries table with related to products table but I got this error. In my products table have 'id' field and in products galleries have 'products_id' field. I already try to google it but still don't get the answer to solve my problem
Thank you
Here is my home.blade.php
<div class="row">
#php $incrementProduct = 0 #endphp
#forelse ($products as $product)
<div
class="col-6 col-md-4 col-lg-3"
data-aos="fade-up"
data-aos-delay="{{ $incrementProduct+=100 }}" >
<a href="{{ route('detail', $product->slug) }}" class="component-products d-block">
<div class="products-thumbnail">
<div
class="products-image"
style="
#if($product->galleries)
background-image: url('{{ Storage::url($product->galleries->first()->photos) }}')
#else
background-color: #eee"
#endif
>
</div>
</div>
<div class="products-text">{{ $product->name }}</div>
<div class="products-price">{{ $product->price }}</div>
</a>
</div>
#empty
<div class="col-12 text-center py-5" data-aos="fade-up"
data-aos-delay="100">
No Product Found
</div>
#endforelse
</div>
My HomeController.php
class HomeController extends Controller
{
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
$categories = Category::take(6)->get();
$products = Product::with(['galleries'])->take(8)->get();
return view('pages.home', [
'categories' => $categories,
'products' => $products
]);
}
}
My Product.php Model
class Product extends Model
{
use SoftDeletes;
protected $fillable = [
'name', 'users_id', 'categories_id', 'price', 'description', 'slug'
];
protected $hidden = [
];
public function galleries() {
return $this->hasMany(ProductGallery::class, 'products_id', 'id');
}
public function user() {
return $this->hasOne(User::class, 'id', 'users_id');
}
public function category() {
return $this->belongsTo(Category::class, 'categories_id', 'id');
}
}
My ProductGallery.php Model
class ProductGallery extends Model
{
protected $fillable = [
'photos', 'products_id'
];
protected $hidden = [
];
public function product() {
return $this->belongsTo(Product::class, 'products_id', 'id');
}
}
//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
So I am being given this error when trying to paginate my data and send it in to a view through a livewire component.
I am trying to get all posts and display at max 5 posts per page using pagination in laravel.
Livewire version: 2.3.1
Laravel version: 8.13.0
Error:
Livewire\Exceptions\PublicPropertyTypeNotAllowedException
Livewire component's [user-posts] public property [posts] must be of type: [numeric, string, array, null,
or boolean]. Only protected or private properties can be set as other types because JavaScript doesn't
need to access them.
My Component:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
use Livewire\WithPagination;
class UserPosts extends Component
{
use WithPagination;
public $posts;
public $type;
protected $listeners = ['refreshPosts'];
public function delete($postId)
{
$post = Post::find($postId);
$post->delete();
$this->posts = $this->posts->except($postId);
}
public function render()
{
if($this->type == 'all')
$this->posts = Post::latest()->paginate(5);
else if($this->type == 'user')
$this->posts = Post::where('user_id',Auth::id())->latest()->paginate(5);
return view('livewire.user-posts', ['posts' => $this->posts]);
}
}
My Blade:
<div wire:poll.5s>
#foreach($posts as $post)
<div style="margin-top: 10px">
<div class="post">
<div class="flex justify-between my-2">
<div class="flex">
<h1>{{ $post->title }}</h1>
<p class="mx-3 py-1 text-xs text-gray-500 font-semibold"
style="margin: 17px 0 16px 40px">{{ $post->created_at->diffForHumans() }}</p>
</div>
#if(Auth::id() == $post->user_id)
<i class="fas fa-times text-red-200 hover:text-red-600 cursor-pointer"
wire:click="delete({{$post->id}})"></i>
#endif
</div>
<img src="{{ asset('image/banner.jpg') }}" style="height:200px;"/>
<p class="text-gray-800">{{ $post->text }}</p>
#livewire('user-comments', [
'post_id' => $post->id,
'type' => 'all'
],
key($post->id)
)
</div>
</div>
#endforeach
{{ $posts->links() }}
</div>
$posts should not be declared as a property in the Livewire component class, you passed the posts with the laravel view() helpers as data.
Remove the line
public $posts;
And replace $this->posts by $posts in the render function:
public function render()
{
if($this->type == 'all')
$posts = Post::latest()->paginate(5);
else if($this->type == 'user')
$posts = Post::where('user_id',Auth::id())->latest()->paginate(5);
return view('livewire.user-posts', ['posts' => $posts]);
}
}
hello i have this error : ReflectionException Class App\User does not exist Previous exceptions syntax error, unexpected '{', expecting ')' (0)
but dont understand where is syntax error ,
User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable implements MustVerifyEmail
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'nom', 'prenom', 'adresse', 'ville', 'codepostale', 'datedenaissance','email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
protected static function boot()
{
parent::boot();
static::created(function ($user {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
}
public function getRouteKeyName()
{
return 'username';
}
public function profile()
{
return $this->hasOne('App\Profile');
}
public function posts()
{
return $this->hasMany('App\Post')->orderBy('created_at', 'DESC');
}
}
ProfileController.php
<?php
namespace App\Http\Controllers;
use App\User;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
class ProfileController extends Controller
{
public function show(User $user)
{
return view('profile.show', compact('user'));
}
public function edit(User $user)
{
$this->authorize('update', $user->profile);
return view('profile.edit', compact('user'));
}
public function update(User $user)
{
$this->authorize('update', $user->profile);
$data = request()->validate([
'title' => 'required',
'description' => 'required',
'image' => 'sometimes|image|max:3000'
]);
if (request('image')) {
$imagePath = request('image')->store('avatars', 'public');
$image = Image::make(public_path("/storage/{$imagePath}"))->fit(800, 800);
$image->save();
auth()->user()->profile->update(array_merge($data,
['image' => $imagePath]
));
} else {
auth()->user()->profile->update($data);
}
auth()->user()->profile->update($data);
return redirect()->route('profile.show', ['user' => $user]);
}
}
show.blade.php
<#extends('layouts.app')
#section('content')
<div class="container">
<div class="row">
<div class="col-4">
<img src="{{ $user->profile->getImage() }}" class="rounded-circle">
</div>
<div class="col-8">
<div class="d-flex align-items-baseline">
<div class="h4 mr-3 pt-2">{{ $user->username }}</div>
<button class="btn btn-primary">S'abonner</button>
</div>
<div class="d-flex">
<div class="mr-3">{{ $user->posts->count() }} article(s) en vente
</div>
#can('update', $user->profile)
Modifier Profile
#endcan
<div class="mt-3">
<div class="font-weight-bold">
{{ $user->profile->title }}
</div>
<div class="font-weight-bold">
{{ $user->profile->description }}
</div>
</div>
</div>
</div>
<div class="row mt-5">
#foreach ($user->posts as $post)
<div class="col-4">
<img src="{{ asset('storage') . '/' . $post->image }}" class="w-100">
</div>
#endforeach
</div>
</div>
#endsection
Profile.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
protected $fillable = ['title'];
public function user()
{
return $this->belongsTo('App\User');
}
public function getImage()
{
$imagePath = $this->image ?? 'avatars/default.png';
return "/storage/" . $imagePath;
}
}
i try to create profile with upload image, someone can help me with this error?
Your IDE should give you an error in your overridden boot method, so change this:
static::created(function ($user {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
to this:
static::created(function ($user) {
$user->profile()->create([
'title' => 'Profil de' . $user->username
]);
});
Note the missing ) in your $user param.
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