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
Related
I created a page using the pagination feature, when I opened the blog page everything went well, but when I opened the blog page based on the username from the user table there was an error Method Illuminate\Database\Eloquent\Collection::paginate does not exist. BTW it uses the same view.
blog.blade.php
#extends('layouts.main')
#section('container')
<main class="mt-20 mb-5 w-[800px] mx-auto">
#foreach ($blogs as $blog)
<article class="mb-5">
{{-- judul --}}
<h2 class="text-blue-600 text-2xl mb-2 font-semibold">{{ $blog->title }}</h2>
{{-- penulis category --}}
<p>Author : {{ $blog->user->name }} | Category : {{ $blog->category->name }}</p>
<p class="mt-2 pb-2 border-b border-grey-500">{{ Str::limit($blog->body, 100) }}</p>
</article>
#endforeach
{{ $blogs->links() }}
</main>
#endsection
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Blog;
class BlogController extends Controller
{
public function index() {
return view('blog', [
'title' => 'All Blog',
'blogs' => Blog::latest()->paginate(5)
]);
}
public function show(Blog $blog) {
return view('show_blog.index', [
'title' => $blog->title,
'blog' => $blog
]);
}
}
UserController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\User;
class UserController extends Controller
{
public function blogFromUser(User $user) {
return view('blog', [
'title' => $user->name,
'blogs' => $user->blog->paginate(5)
]);
}
}
Blog.php *relate to user (belongsTo)
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Blog extends Model
{
use HasFactory;
public function category() {
return $this->belongsTo(Category::class);
}
public function user() {
return $this->belongsTo(User::class);
}
}
)*
User.php *related to Blog (hasMany)
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
public function Blog() {
return $this->hasMany(Blog::class);
}
}
)*
When you do :
$user->blog
it will execute the query and retrieve the results, so $user->blog will be a collection.
If you want to paginate it, you need to call paginate on the query/relation, not the result, so you need to do something like :
$user->blog()->paginate(5)
then to access other pages, you will have to append ?page=xy to the page url
be aware that if you have multiple paginations within the same page you will need to change the name of the parameter to avoid conflict like so :
$user->blog()->paginate(5, '*', 'blog')
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]);
}
}
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 }}
I had problem on calling page inside Foreach Loop.Although It is Okay before I click Login, but when I'd try to login,only the html tag where loaded and foreach loop cannot... On my HomeController extends Controller
public function index()
{
return view('pages.welcome');
}
on where I call welcome page. and inside of it which is foreach loop.
<div class="row">
<div class="col-md-8">
#foreach ($posts as $post)
<div class="post">
<h3>{{ $post->title }}</h3>
<p>{{ substr($post->body, 0,300) }}
{{ strlen($post->body) > 300 ? "..." : " " }}</p>
Read More...
</div>
<hr>
#endforeach
</div>
</div>
And I think the problem is my route:
Route::get('/home', 'HomeController#index');
You haven't passed the $posts variable to the view.
Change
public function index()
{
return view('pages.welcome');
}
To something like this:
public function index()
{
$posts = \App\Post::all(); //Assuming your model is called "Post" in the App namespace
return view('pages.welcome', compact('posts'));
}
NOTE: compact('posts') is just a shortcut for ['posts'=>$posts]
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');
}