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
Related
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
//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()
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?
I'm trying to get a list of the staffs on my application.
So now I got this view:
#foreach($getteam as $team)
<!-- Begin row -->
<div class="panel-group col-sm-offset-1 col-sm-10">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{ $team->role->name }}</h3>
</div>
<div class="panel-body">
<ul class="list-group">
<li class="list-group-item">
<img src="{{ Config::get('app.url') }}/public/img/avatar.jpg" style="float:left;margin-right:15px;padding-bottom:5px;" class="img-circle" alt="{{ $team->username }}" width="75" height="75">
<h4 style="color:{{ $team->role->colour }};">{{ $team->username }}</h4>
<p>Een klein beetje info over wie ik ben enzo... :p</p>
</li>
</ul>
</div>
</div>
</div>
<!-- End row -->
#endforeach
With this query:
SELECT * FROM `user`
INNER JOIN `role` ON `user`.`role_id` = `role`.`id`
WHERE `role_id` >= '4'
ORDER BY `role`.`id` DESC
or
User::with('Role')
->join('role', 'user.role_id', '=', 'role.id')
->where('role_id', '>=', '4')
->orderBy('role.id', 'DESC')
->get();
Now, so for so good,
This works to get the users exept this is the result:
http://prntscr.com/8a6v60
That is not what I want.
This is what I want: http://prntscr.com/8a6vgo
So when the groups are the same, they need to be in the same UL.
Edit
This is my view now:
<!-- Begin row -->
<div class="panel-group col-sm-offset-1 col-sm-10">
#foreach($roles as $role)
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{ $role->name }}</h3>
</div>
<div class="panel-body">
<ul class="list-group">
#foreach($role->user() as $user)
<li class="list-group-item">
<img src="{{ Config::get('app.url') }}/public/img/avatar.jpg" style="float:left;margin-right:15px;padding-bottom:5px;" class="img-circle" alt="{{ $user->username }}" width="75" height="75">
<h4 style="color:{{ $role->colour }};">{{ $user->username }}</h4>
<p>Een klein beetje info over wie ik ben enzo... :p</p>
</li>
#endforeach
</ul>
</div>
</div>
#endforeach
</div>
<!-- End row -->
This is the controller:
public function ForumTeam()
{
$roles = Role::all();
$getTeam = User::with('Role')->join('role', 'user.role_id', '=', 'role.id')->where('role_id', '>=', '4')->orderBy('role.id', 'DESC')->get();
return View::make('team')->with('getteam', $getTeam)->with('roles', $roles);
}
And this one is the model.
<?php
class Role extends Eloquent
{
protected $table = 'role';
public function user()
{
return $this->belongsTo(User::class);
}
}
Now I only get all the role names, not the correct stuff.
Use the reverse of the relationship between users and roles. Instead of fetching the users, get the roles and for each role you can get the corresponding users (this of course requires the Role model to have a users() method with a relation defined:
// You can of course use conditions here to filter out what roles you want loaded
$roles = Role::all();
Then iterate through the roles, and for each role iterate through its users:
<div class="panel-group col-sm-offset-1 col-sm-10">
#foreach($roles as $role)
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">{{ $role->name }}</h3>
</div>
<div class="panel-body">
<ul class="list-group">
#foreach($role->users as $user)
<li class="list-group-item">
<img src="{{ Config::get('app.url') }}/public/img/avatar.jpg" style="float:left;margin-right:15px;padding-bottom:5px;" class="img-circle" alt="{{ $user->username }}" width="75" height="75">
<h4 style="color:{{ $role->colour }};">{{ $user->username }}</h4>
<p>Een klein beetje info over wie ik ben enzo... :p</p>
</li>
#endforeach
</ul>
</div>
</div>
#endforeach
</div>
I have looked at a similar question but unfortunately the answer does not apply to me.
I know that my object does contain my data but the inside of the #foreach is never called in my view.
Here is my controller:
$newest_article = $this->article->orderBy('created_at', 'DESC')->first();
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC');
return View::make('site/news/index', compact('newest_article', 'articles'));
My model's scopeAllButFirst function:
public function scopeAllButFirst($query, $id){
return $query->where('id', '<>', $id);
}
And lastly my view:
#extends('site.layouts.default')
#section('content')
<section id="news-main">
<div class="container">
<!-- all posts wrapper -->
<div class="news-box-wrap js-packery clearfix" data-packery-options='{ "itemSelector": ".news-item"}'>
#foreach($articles as $article)
<div class="col-sm-4 news-item">
<a href="{{{ $article->url() }}}" class="news-box-inner">
<div class="news-box-image-wrap">
#if($article->image->url('tile_landscape'))
<img src="{{{ $article->image->url('tile_landscape') }}}" class="news-box-image">
#endif
<span class="news-box-icon">
<i class="fa fa-align-left"></i>
</span>
</div>
<div class="news-box-bottom">
<div class="news-box-data">
<span class="news-box-cat">News</span>
•
<span class="news-box-time">{{{ $article->date() }}}</span>
</div>
<h3>{{{ $article->title }}}</h3>
<div class="news-box-det">
<span class="news-box-author">{{{ $article->author->username }}}</span>
<span class="news-box-like"><i class="fa fa-smile-o fa-lg"></i> 225</span>
<span class="news-box-comment"><i class="fa fa-comment-o fa-lg"></i> 16</span>
</div>
</div>
</a>
</div>
#endforeach
</div>
#stop
I need to loop through the Eloquent object because I have to access some of the methods in my model class.
just as a reference, I am following andrewelkins/Laravel-4-Bootstrap-Starter-Site
UPDATE
In my debugging I noticed if I replace
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC');
with
$articles = Article::all();
I don't have this problem.
For those facing the problem, the answer as usual is in the API. Turns out you have to call the get() method in order to receive a Collection. And that is what all() returns. So simply changing
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC');
to
$articles = Article::allButFirst($newest_article->id)->orderBy('created_at', 'DESC')->get();
solves the problem.
Hope it helps