Laravel - Multiple Controllers within a View - php

I'm trying to code a simple social media page. The show view should display a post with all the comments for that particular post listed below.
I've tried a couple different approaches with no luck, this is the approach I feel like I might be closet to success with, any suggestions?
I can provide other extracts of code if you think the problem lies elsewhere but I think my problem lies within these 4 files.
web.php
Route::resource('post', 'PostController');
Route::resource('post', 'CommentController');
show.blade.php
<h1>{{$post->title}}</h1>
<p>Description: {{$post->description}}</p>
<h3>Comments</h3>
<ul>
#foreach ($comments as $comment)
<li>
User: {{$comments->user_name}} <br>
Comment: {{$comments->comment}} <br>
</li><br>
#endforeach
</ul>
PostController.php
public function show($id)
{
$post= Post::find($id);
return view('post.show')->with('post', $post);
}
CommentController.php
public function show($id)
{
$comments= Comment::find($id);
return view('post.show')->with('comments', $comments);
}
EDIT 1
Post.php
class Post extends Model
{
protected $fillable = ['title', 'description'];
function user() {
return $this->belongsTo('App\User');
}
function comment() {
return $this->hasMany('App\Comment');
}
}

firstly set the relationship between Post and Comment Model
In Post Model
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
In Comment Model
class Comment extends Model
{
public function post(){
return $this->belongsTo(Post::class);
}
}
Post Controller
public function show($id)
{
$post= Post::find($id);
return view('post.show')->with('post', $post);
}
Write in the blade file
<h1>{{$post->title}}</h1>
<p>Description: {{$post->description}}</p>
<h3>Comments</h3>
<ul>
#foreach ($post->comments as $comment) //get all the comments related to this post
<li>
User: {{$comment->user_name}} <br>
Comment: {{$comment->comment}} <br>
</li><br>
#endforeach
</ul>

You can get both data by make relations between your models
I think in your two models the relation would be like that,
Post Model
namespace App\Post;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function comments(){
return $this->hasMany(Comment::class);
}
}
Comment Model:
namespace App\Comment;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post(){
return $this->belongsTo(Post::class);
}
}
so if you want to return the data to view then,
PostController.php
public function show($id)
{
$post= Post::with('comments')->find($id);
$data = [
'post' => $post,
'comments' => $post->comments,
];
return view('post.show', $data);
}
CommentController.php
public function show($id)
{
$comments= Comment::with('post')->find($id);
$data = [
'post' => $comments->post,
'comments' => $comments,
];
return view('post.show' , $data);
}
For more details: https://laravel.com/docs/5.7/eloquent

Related

Delete route not getting any data Laravel 6.X

I tried changing the routes and using a specific name and several things in the action attribute but there is no way the data doesn't appear when I use the form for the delete and the dd() function on my delete route
here is what the dd shows me, no info at all
My routes:
Route::get('/home/Collections', 'CollectionController#index')->name('collection.index');
Route::get('/home/Collections/{Collection}', 'CollectionController#show')->name('collection.show');
Route::get('/home/Collections/{Collection}/edit', 'CollectionController#edit')->name('collection.edit');
Route::put('/home/Collections/{Collection}', 'CollectionController#update')->name('collection.update');
Route::get('/home/Collections/crear', 'CollectionController#create')->name('collection.create');
Route::delete('/home/Collections/{Collection}', 'CollectionController#destroy')->name('collection.destroy');
Route::post('/home/Collections', 'CollectionController#store')->name('collection.store');
My controller:
public function destroy(Collection $collection)
{
$collection->delete();
return redirect('/home'.'/Collections');
}
and my form:
#foreach ($collections as $collection)
<div id="{{$collection->id}}">
<img/>
<p>{{$collection->name}}</p>
<p>{{$collection->description}}</p>
<form action="/home/Collections/{{$collection->id}}" method="POST">
#csrf
#method('DELETE')
<input type="submit" value="ELIMINAR" class = "btn btn-outline-danger mt-2">
</form>
</div>
#endforeach
my collection model:
class Collection extends Model implements Searchable
{
protected $fillable = ['id', 'name', 'description', 'user_id', 'category_id', 'certificate_id', 'img_id'];
public function items()
{
return $this->hasMany(Item::class);
}
public function certificate()
{
return $this->hasOne(Certificate::class);
}
public function image()
{
return $this->hasOne(Image::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function getSearchResult(): SearchResult
{
$url = route('collection.show', $this->id);
return new SearchResult(
$this,
$this->name,
$url
);
}
}
Problem solved a while ago, i forgot to reply to this post.
Solved it changing the Routes URL so they dont match, it seems there was a problem with them even tho it was working like exposed on another project.

BadMethodCallException Call to undefined method App\Post::tags()

Im working on my Laravel project, and have a problem with many-to-many relationship : cannot use "sync" function to store the data in Intermediary Table.
Im following the tutorial in this series : Part 37 - Adding Tag UI/UX
Problem seems to be with this code line : $post->tags()->sync($request->tags, false);
It throws back the error :
BadMethodCallException Call to undefined method App\Post::tags()
I have tried to use attach function instead of sync, does not work.
I dont know which part of code could lead to this issue.
Pls tell me if u guys notice anythings. Tysm !
Post.php (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
protected $table = "posts";
public function category(){
return $this->belongsTo('App\Category');
}
public function user(){
return $this->belongsTo('App\User');
}
public function tag(){
return $this->belongsToMany('App\Tag', 'post_tag');
}
}
Tag.php (Model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $table = "tags";
public function post(){
return $this->belongsToMany('App\Post', 'post_tag');
}
}
create_post_tag_table.php (migrations - Intermediary Table)
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostTagTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('post_id')->unsigned()->nullable();
$table->foreign('post_id')->references('id')->on('posts');
$table->bigInteger('tag_id')->unsigned()->nullable();
$table->foreign('tag_id')->references('id')->on('tags');
});
}
}
posts.create.blade.php (views - select multiple tags)
<select class="form-control select2-multi" name="tags[]" multiple="multiple" style="width:100%;">
#foreach($tags as $tag)
<option value='{{ $tag->id }}'>{{ $tag->name }}</option>
#endforeach
</select>
PostsController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use App\Post;
use App\Tag;
use App\User;
class PostsController extends Controller
{
public function create()
{
$tags = Tag::all();
return view('posts.create')->with('tags', $tags);
}
public function store(Request $request)
{
$this->validate($request, [
'title' => 'required',
'category_id' => 'required',
]);
$post = new Post;
$post->title = $request->input('title');
$post->description = $request->input('description');
$post->content = $request->input('content');
$post->category_id = $request->input('category_id');
$post->user_id = auth()->user()->id;
$post->status = $request->input('status');
$post->save();
$post->tags()->sync($request->tags, false);
return redirect('/posts')->with('success', 'Post created.');
}
}
You have defined the relationship as tag in your Post model but you are calling tags. You should change it to tags since it is a belongsToMany relationship.
public function tags()
{
return $this->belongsToMany('App\Tag', 'post_tag');
}

Laravel Undefined offset error

I just finishing my blog, using laravel, and I want to add a comment feature on it, but i got few errors like this, can anyone help me, please??,
sorry for my English, English is not my native language,
Thank you :)
(1/1) ErrorException
Undefined offset: 1
Here is my AdminBlog.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AdminBlog extends Model
{
protected $table = 'admin';
protected $fillable = ['title','text','images','slug'];
public function comment(){
return $this->hasMany('App\Comment');
}
}
Comment.php Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
protected $table = 'comment';
protected $fillable = ['name','email','text','post_id'];
public function post(){
return $this->belongsTo('App\AdminBlog');
}
}
BlogController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\AdminBlog;
use App\Comment;
class BlogController extends Controller
{
//Index
public function index(){
$post = AdminBlog::all();
return view('blog/index', compact('post'));
}
//Show
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
}
show.blade.php
<div class="col-md-12 post-comment-show">
#foreach($post->comment() as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
You should use:
<div class="col-md-12 post-comment-show">
#foreach($post->comment as $list)
<p>{{ $list->text }}</p>
#foreach
</div>
Note that, you have used comment(). Also, you should use a plural name for a hasMany relationship, so comment should be comments.
Also, in your show method, you should use something like the following:
public function show($id)
{
$post = AdminBlog::with('comment')->findOrFail($id);
return view('blog/show', ['post' => $post]);
}
Try the following
$post->comment()->get()
or
$post->comment
when calling a relationship with ()it returns a instance of the query builder and allows you to filter the object. If you remove the call it without () it returns you a collection which is array accessible
Another suggestion if you have many comments you should name your relationship plural.
in this case:
public function comments(){
return $this->hasMany('App\Comment');
}
// Use it like this
$post->comments
You need to change your show function:
public function show($id){
$post = AdminBlog::findOrFail($id);
$comment = Comment::all();
//dd($comment);
return view('blog/show', ['post' => $post,
'comment' => $comment]);
}
TO
public function show($id){
$post = AdminBlog::with('comment')->where('admin.id',$id)->get();
return view('blog/show', compact('post'));
}
Hope this work for you!

How to display Posts via the Category in laravel

This is my first laravel Application, and my first database based application so please be patient with me !!
I will try to be specific!!
Categories Table:
Id
Name
Timestamps
Posts table:
Id
title
body
slug
Category_id
timestamps
Lets say i have 4 catergories.
Laptops, computers,phones,tablets
I want when i go to /computers to be able to get all the posts that are specific to that category.
Posts Model
Category Model
Category Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Category;
class CatController extends Controller
{
public function getCategory($Category_id)
{
$posts = Post::where('Category_id',$Category_id);
return view('blog.index',['posts' => $posts]);
}
Route:
Route::get('computer/{Category_id}','CatController#getCategory');
I am really confused at the moment !!
Thanks everyone in advance!!
Define your Model
class Category extends Model
{
/**
* Get the posts.
*/
public function posts()
{
return $this->hasMany('App\Post', 'Category_id');
}
}
class Post extends Model
{
/**
* Get the category.
*/
public function category()
{
return $this->belongsTo('App\Category', 'Category_id');
}
}
Define your Controller
class CatController extends Controller
{
public function getCategory($Category_id)
{
$category = Category::find($Category_id);
if($category !== null){
$posts = $category->posts;
return view('blog.index',['posts' => $posts]);
}
}
I hope this will help you.
Route:
Route::get('categories/{category_id}/computers','CatController#show');
Controller:
public function show($category_id)
{
$category = Category::findOrFail($category_id);
if($category){
$posts = Post::where('Category_id',$category_id)->get();
return view('category.index', compact('posts'));
}
return view('errors.404');
}
Simply add this to your controller
public function category($id){
$data['posts'] = Post::where('status', 1)->where('category_id', $id)->orderBy('id', 'DESC')->get();
return view('frontEnd.home', $data);
}

Laravel post with comment error

So i created an app with login users and users can post, now the post is working just fine but when i put a comment function, i get an error "Invalid argument supplied for foreach()"
i have this in my Post model
<?php
class Post extends Eloquent{
protected $fillable = array('email', 'password','title','content');
protected $table = 'posts';
public function User()
{
return $this->belongsTo('User');
}
public function Comment()
{
return $this->hasMany('Comment', 'post_id');
}
}
And in my Comment model
<?php
class Comments extends Eloquent {
public function post()
{
return $this->belongsTo('Post');
}
}
and i have this in my Controller
public function viewPost($id)
{
$post = Post::find($id);
$user = Auth::user();
$this->layout->content = View::make('interface.viewPost')->with('posts', $post )->with('users',$user);
}
and in my views
<section class="comments">
#foreach($posts->comments as $comment)
<blockquote>{{$comment->content}}</blockquote>
#endforeach
</section>
now when i try do run dd($posts->comment)
it returns a null because the comment table is empty. now what i want to know is why im getting this error? thanks for your help im just curious why this error is returning and i want to solve this one thanks
In your Post Model Comment is the function name not the comments and Comment method making relation with wrong name model under hasMany method call.
public function Comment()
{
return $this->hasMany('Comments', 'post_id');
}
Try to use
#foreach($posts->Comment as $comment)
If still inaccessible then try to eager loading.
like in your controller
$post = Post::with("comment")->find($id);

Categories