Laravel Livewire Star Rating - php

I have need to complete the functionality of rating start. In this code two Models use Post model and PostRate models.
Post Model have three attributes like id, title, description
PostRate have id, post_id, rate.
I have make livewire Component Rate and Resource of rate
<?php
namespace App\Http\Livewire;
use App\Models\Post;
use App\Models\PostRate;
use Livewire\Component;
class Rate extends Component
{
public $currentRating=false;
public $postId;
public function render()
{
$post = Post::withCount('rates')->latest('id')->first();
$this->postId = $post->id;
return view('livewire.rate', compact('post'));
}
public function rate($rating)
{
PostRate::create(['post_id'=>$this->postId,'rate'=>$rating]);
$this->currentRating = true;
}
}
Resource Rate
<div>
<h2 class="text-3xl">{{ $post->title }}</h2>
<p>{{ $post->description }}</p>
<div class="mt-4 mb-4">
Current rating: <b>2.83 / 5 ({{ $post->rates_count }} votes)</b>
</div>
<h3 class="text-2xl">Rate the post</h3>
<div class="flex">
<img src="http://demo-star-rating.livewirekit.com/img/star-active.png" width="30">
<a wire:click.prevent="rate(1)" href="#"><img src="http://demo-star-rating.livewirekit.com/img/star-inactive.png" width="30"></a>
<a wire:click.prevent="rate(2)" href="#"><img src="http://demo-star-rating.livewirekit.com/img/star-inactive.png" width="30"></a>
<a wire:click.prevent="rate(3)" href="#"><img src="http://demo-star-rating.livewirekit.com/img/star-inactive.png" width="30"></a>
<a wire:click.prevent="rate(4)" href="#"><img src="http://demo-star-rating.livewirekit.com/img/star-inactive.png" width="30"></a>
<a wire:click.prevent="rate(5)" href="#"><img src="http://demo-star-rating.livewirekit.com/img/star-inactive.png" width="30"></a>
</div>
<div>
You rated: 4 / 5
</div>
</div>

Assume that you handle the relationship between Post and Rate and could be many to many and be sure if your function will accept more than one vote for the same user. Maybe if you explain more about your task

Related

i can't listing users' post in theirs profile. i use one to many relationship in User model

//here is my controller `
public function index($id){
$users=User::where('id',$id)->get();
return view('user',compact('users'));
}
}`
//here is my User model
public function getPosts()
{
return $this->hasMany('App\Post','user_id','id');
}
//here is my user blade
#foreach($user->getPosts as $post)
<div class="profile-content">
<section class="post-heading">
<div class="rows">
<div class="col-md-11">
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object photo-profile" src="https://scontent.fgyd4-2.fna.fbcdn.net/v/t1.0-9/p960x960/73248174_2597397730318615_6397819353256951808_o.jpg?_nc_cat=109&_nc_sid=7aed08&_nc_ohc=VxH_cAqJ778AX_7B97W&_nc_ht=scontent.fgyd4-2.fna&_nc_tp=6&oh=e5b02c7f91818664cf253e71f2ddf106&oe=5F5F4E74" width="40" height="40" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">{{$user->name}} </h4>
{{$user->$post['created_at']}}
</div>
</div>
</div>
<div class="col-md-1">
<i class="glyphicon glyphicon-chevron-down"></i>
</div>
</div>
</section>
<section class="post-body">
<p>{{ $user->getPost->post['post_description'] }}</p> <!-- i stick around here -->
</section>
//it give this error to me
Property [getPosts] does not exist on this collection instance. (View: C:\xampp\htdocs\site\resources\views\user.blade.php)
In controller get() will return collection,you want one user, so use find() or first(), it will return one user object
public function index($id){
$user=User::find($id); //or $user=User::where('id',$id)->first();
return view('user',compact('user'));
}
Relation method
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
Since their is one to many relation between user and posts,you have to use loop to show posts for a user
foreach($user->posts as $post)
<div class="profile-content">
<section class="post-heading">
<div class="rows">
<div class="col-md-11">
<div class="media">
<div class="media-left">
<a href="#">
<img class="media-object photo-profile" src="https://scontent.fgyd4-2.fna.fbcdn.net/v/t1.0-9/p960x960/73248174_2597397730318615_6397819353256951808_o.jpg?_nc_cat=109&_nc_sid=7aed08&_nc_ohc=VxH_cAqJ778AX_7B97W&_nc_ht=scontent.fgyd4-2.fna&_nc_tp=6&oh=e5b02c7f91818664cf253e71f2ddf106&oe=5F5F4E74" width="40" height="40" alt="...">
</a>
</div>
<div class="media-body">
<h4 class="media-heading">{{$user->name}} </h4>
{{$post->created_at}}
</div>
</div>
</div>
<div class="col-md-1">
<i class="glyphicon glyphicon-chevron-down"></i>
</div>
</div>
</section>
<section class="post-body">
<p>{{ $post->post_description }}</p> <!-- i stick around here -->
</section>
#endforeach
$users=User::where('id',$id)->get(); returns a collection of users
So when you do this:
#foreach($user->getPosts as $post)
$user is a collection of users. That collection doesn't have a getPosts() method.
you are returning list of users, so you don't have one user and you can't have the posts of all certain user
below code can fix the issue:
User::where('id', $id)->first();
First of all you should update your controller like this
User::find($id);
You should update your relation like this
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
After that you should update your blade like this
foreach ($user->posts as $post)
You can't access posts with ->getPosts. If you want, you should use like this ->getPosts()->get()

In my e-commerce site single product page didn't be loaded

I am developing an e-commerce website in Laravel. On my product page, I have all my products. If I select one product that needs to direct for another page as a single product details page and that page should be loaded. In my case, when I select a product, I am directed to a single product page as well as that product's product id showed in the URL, but the page data didn't be loaded. what could be the problem?
This is my first project in laravel. If anyone can give a hand to sort it out it will be a great help.
SingleProductController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
use App\Category;
class SingleProductController extends Controller
{
public function index(Product $product)
{
$arr['product'] = $product;
return view('singleproducts')->with($arr);
}
// public function update(Request $request, Product $product)
// {
// $product-> prod_name = $request-> prod_name;
// $product-> prod_image_path = $request-> prod_image_path;
// return view('singleproducts',['product'=>$product]);
// }
public function show($id)
{
$product = Product::find($id);
return view ('singleproducts',['product'=>$product]);
}
}
singleproducts.blade.php
<form action="{{ route('singleproducts',$product->id) }}" enctype="multipart/form-data">
<div class="mb-xl-14 mb-6">
<div class="row">
<div class="col-md-5 mb-4 mb-md-0">
<div id="sliderSyncingThumb" class="js-slick-carousel u-slick u-slick--slider-syncing u-slick--slider-syncing-size u-slick--gutters-1 u-slick--transform-off"
data-infinite="true"
data-slides-show="5"
data-is-thumbs="true"
data-nav-for="#sliderSyncingNav">
<div class="js-slide">
<img class="img-fluid" src="{{asset('/storage/admin/'.$product ['prod_image_path'] ) }}" alt="Image Description">
</div>
</div>
</div>
</div>
<div class="col-md-7 mb-md-6 mb-lg-0">
<div class="mb-2">
<div class="border-bottom mb-3 pb-md-1 pb-3">
<h2 class="font-size-25 text-lh-1dot2">{{ $product ['prod_name'] }}</h2>
<div class="mb-2">
<a class="d-inline-flex align-items-center small font-size-15 text-lh-1" href="#">
<div class="text-warning mr-2">
<small class="fas fa-star"></small>
<small class="fas fa-star"></small>
<small class="fas fa-star"></small>
<small class="fas fa-star"></small>
<small class="far fa-star text-muted"></small>
</div>
</a>
</div>
</div>
</div>
</div>
</form>
This is my route
Route::get('/singleproducts', 'SingleProductController#index')->name('singleproducts');
What could be the problem?
Assuming that you have set your routes well, it may be due to a problem in your blade file. Just try it with a simple blade file and if it works you can search for a problem in your blade file.

SOLVED! Call to undefined method App\Category::posts() Laravel

i want to create some CMS project with the laravel, when the user trying to click the categories, the app will show the post that only shows the category that user clicked. When the user click the categories, the app says error Bad Method Call. What should i do? Any help will be appreciated.
Here's the code from web.php
<?php
use App\Http\Controllers\Blog\PostsController;
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'WelcomeController#index')->name('welcome');
Route::get('blog/posts/{post}', [PostsController::class, 'show'])->name('blog.show');
Route::get('blog/categories/{category}', [PostsController::class, 'category'])->name('blog.category');
Route::get('blog/tags/{tag}', [PostsController::class, 'tag'])->name('blog.tag');
Auth::routes();
Route::middleware(['auth'])->group(function () {
Route::get('/home', 'HomeController#index')->name('home');
Route::resource('categories', 'CategoriesController');
Route::resource('posts','PostsController');
Route::resource('tags','TagsController');
Route::get('trashed-posts','PostsController#trashed')->name('trashed-posts.index');
Route::put('restore-post/{post}', 'PostsController#restore')->name('restore-posts');
});
Route::middleware(['auth', 'admin'])->group(function () {
Route::get('users/profile', 'UserController#edit')->name('users.edit-profile');
Route::put('users/profile', 'UserController#update')->name('users.update-profile');
Route::get('users','UserController#index')->name('users.index');
Route::post('users/{user}/make-admin', 'UserController#makeAdmin')->name('users.make-admin');
});
Here's the code from PostsController.php
<?php
namespace App\Http\Controllers\Blog;
use App\Http\Controllers\Controller;
use App\Post;
use Illuminate\Http\Request;
use App\Tag;
use App\Category;
class PostsController extends Controller
{
public function show(Post $post) {
return view('blog.show')->with('post', $post);
}
public function category(Category $category) {
return view('blog.category')
->with('category', $category)
->with('posts', $category->posts()->simplePaginate())
->with('categories', Category::all())
->with('tags', Tag::all());
}
public function tag(Tag $tag) {
return view('blog.tag')
->with('tag', $tag)
->with('posts', $tag->posts()->simplePaginate(3));
}
}
Here's the code from App\Category.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $fillable = ['name'];
public function post() {
return $this->hasMany(Post::class);
}
}
Here's the code from category.blade.php
#extends('layouts.blog')
#section('title')
Category {{ $category->name }}
#endsection
#section('header')
<header class="header text-center text-white" style="background-image: linear-gradient(-225deg, #5D9FFF 0%, #B8DCFF 48%, #6BBBFF 100%);">
<div class="container">
<div class="row">
<div class="col-md-8 mx-auto">
<h1>{{ $category->name }}</h1>
<p class="lead-2 opacity-90 mt-6">Read and get updated on how we progress</p>
</div>
</div>
</div>
</header><!-- /.header -->
#endsection
#section('content')
<main class="main-content">
<div class="section bg-gray">
<div class="container">
<div class="row">
<div class="col-md-8 col-xl-9">
<div class="row gap-y">
#forelse($posts as $post)
<div class="col-md-6">
<div class="card border hover-shadow-6 mb-6 d-block">
<img class="card-img-top" src="{{ asset($post->image) }}" alt="Card image cap">
<div class="p-6 text-center">
<p>
<a class="small-5 text-lighter text-uppercase ls-2 fw-400" href="#"></a>
{{ $post->category->name }}
</p>
<h5 class="mb-0">
<a class="text-dark" href="{{ route('blog.show',$post->id) }}">
{{ $post->title }}
</a>
</h5>
</div>
</div>
</div>
#empty
<p class="text-center">
No Results found for query <strong>{{ request()->query('search') }} </strong>
</p>
#endforelse
</div>
{{-- <nav class="flexbox mt-30">
<a class="btn btn-white disabled"><i class="ti-arrow-left fs-9 mr-4"></i> Newer</a>
<a class="btn btn-white" href="#">Older <i class="ti-arrow-right fs-9 ml-4"></i></a>
</nav> --}}
{{ $posts->appends(['search' => request()->query('search') ])->links() }}
</div>
#include('partials.sidebar')
</div>
</div>
</div>
</main>
#endsection
If you guys didn't see which file that i don't show up, just ask,.
If you guys see any problems that confusing, i can use teamviewer.
Any Help will be appreciated.
Thank you.
The error told that you don't have posts. Indeed it is. What you have is post() method on Category class, as evidently seen in this line:
public function post() {
You should change this ->with('posts', $category->posts()->simplePaginate()) to be:
public function category(Category $category) {
return view('blog.category')
->with('category', $category)
->with('posts', $category->post()->simplePaginate())
->with('categories', Category::all())
->with('tags', Tag::all());
}
In your model, you defined a post relationship whereas you use a posts relationship then, they're not the same one. You should replace post by posts because it's a to-many relationship.
Your relationship is post and you have multiple ->with('posts', $category->posts()->simplePaginate()). Can you change those to ->with('post') and try again?

Laravel undefined variable $articles

I'm busy with my own news system and I'm using Laravel 5. I'm quite new to Laravel and using tutorials to walk my way through it. Now I'm having this error "Undefined variable: articles".
Here is my ArticlesController.php
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
return view('pages.news');
}
}
Here is my news.blade.php
#foreach ($articles as $article)
<!-- Post -->
<div class="blog-item">
<!-- Post title -->
<h2 class="blog-item-title font-alt">
{{ $article->title }}
</h2>
<!-- Post data -->
<div class="blog-item-data">
<i class="fa fa-clock-o"></i> 5 December
<span class="seperator"> </span>
<i class="fa fa-user"></i> John Doe
<span class="seperator"> </span>
<i class="fa fa-folder-open"></i>
Category, Category
<span class="seperator"> </span>
<i class="fa fa-comments"></i> 5 Comments
</div>
<!-- Media gallery -->
<div class="blog-media">
<ul class="clearlist content-slider">
<li><img src="images/portfolio/full-project-1.jpg" alt="Blog image"></li>
</ul>
</div>
<!-- Text intro -->
<div class="blog-item-body">
<p>{{ $article->body }}</p>
</div>
<!-- Read more -->
<div class="blog-item-foot">
Read More <i class="fa fa-angle-right"></i>
</div>
</div>
#endforeach
I have tried couple things, such as removing everything and starting over. Nothing really did the trick.
You have to pass the variable to your view, else the view does not "know" the variable. Like this:
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticlesController extends Controller
{
public function index()
{
return view('pages.news', ['articles' => Article::all(),]);
}
}
Reference here.
You do not pass any data from the controller to the view, so do something like this:
$articles = Article::get();
return view('pages.news', ['articles' => $articles]);
Or:
return view('pages.news', compact('articles'));
Or:
return view('pages.news')->with('articles', $articles);
https://laravel.com/docs/5.5/views#passing-data-to-views

Laravel 5 get profile name

I'm laravel begginer and I wan't to make simple CMS. Ok, so i have simple question:
I want when click on avatar (profile image) - redirect to user profile (http://example.com/profiles/nickname/id)
In DB it saves that:
as you see author_id I have, now I need to get author name from users table:
And then generate url: http://example.com/profiles/Evaldas/2 (Evaldas, because author_id is 2 in topics table)
My routes file:
Route::get('topic/{tname}/{tid}', 'viewTopic#showTopic');
My viewTopic.php Controller:
<?php
namespace App\Http\Controllers;
use DB;
use View;
class viewTopic extends Controller
{
public function showTopic($tname, $tid)
{
return View::make('posts', [
'topics' => DB::table('topics')
->where('id', $tid)
->where('seo_title', $tname)
->first(),
'posts' => DB::table('posts')
->where('topic_id', $tid)
->select()
->get()
]);
}
}
And layout:
#extends('layouts.main')
#section('content')
<div class="media">
<div class="media-left">
<a href="HERE MUST BE HREF TO PROFILE">
<img class="media-object" src="http://localhost/uploads/avatars/2.jpg" style="width: 64px">
</a>
</div>
<div class="media-body" rel="#author{{ $topics->author_id }}">
<h4 class="media-heading">{{ $topics->title }}</h4>
#if(!empty($topics->text))
{{ $topics->text }}
#else
Message empty :(
#endif
</div>
#foreach($posts as $post)
<div class="media">
<div class="media-left">
<a href="HERE MUST BE HREF TO PROFILE">
<img class="media-object" src="http://localhost/uploads/avatars/1.png" style="width: 64px">
</a>
</div>
<div class="media-body" rel="#post{{ $post->pid }}">
{{ $post->text }}
</div>
</div>
#endforeach
</div>
#stop
Thanks in advance ;)
You could use the User object to look it up ... but a better option would be to join the 'posts' table to the 'user' table, and select it from the results - have a look at http://laravel.com/docs/5.1/queries#joins

Categories