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!
Related
I want to fetch data from database in table but it show me undefined variable error in view please help me to solve this problem
my controller
class showAttendanceController extends Controller
{
public function index()
{
$users=DB::select('select * from requests');
return view('showAttendance',compact('users'));
}
my view
#foreach ($users as $user)
<td>{{$user->date}}</td>
<td>{{$user->Name}}</td>
<td>{{$user->Misid}}</td>
<td>{{$user->semester}}</td>
<td>{{$user->Department}}</td>
<td>{{$user->section}}</td>
<td>{{$user->Attendance}}</td>
My Route
Route::get('/showrecord','showAttendanceController#index')->name('showrecord');
Controller:
public function index()
{
$users = DB::table('requests')->get();
return view('showAttendance',compact('users'));
}
View:
#foreach($users as $user)
<td>{{$user->date}}</td>
<td>{{$user->Name}}</td>
<td>{{$user->Misid}}</td>
<td>{{$user->semester}}</td>
<td>{{$user->Department}}</td>
<td>{{$user->section}}</td>
<td>{{$user->Attendance}}</td>
#endforeach
first of all, it's better to create your table using migrations in order to have Database Consistency.
Further try to use models to interact with Database
for example
namespace App;
use Illuminate\Database\Eloquent\Model;
class deposit extends Model
{
//
protected $keyType = 'string';
protected $table = "deposit";
protected $fillable = [
'uid', 'amount', 'title', 'description'
];
}
and then you can use it in your controller
$deposit = deposit::find($request->deposit_id);
if($deposit){
return $deposit
} else {
return 'Some Error'}
first of all you have to use DB in your controller
public function index()
{
$users = DB::table('table_name')->get();
return view('showAttendance',compact('users'));
}
than you have to confirm your return view file location is right or not.Exmple if your showAttendence file is inside a folder you have to use
return view('foldername.showAttendence',compact('users));
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');
}
I'm trying to pass my article data to the single page article named article.blade.php although all the data are recorded into the database but when I tried to return them in my view, nothing showed and the [ ] was empty. Nothing returned.
this is my articleController.php
<?php
namespace App\Http\Controllers;
use App\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function single(Article $article)
{
return $article;
}
}
this is my model:
<?php
namespace App;
use Cviebrock\EloquentSluggable\Sluggable;
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
use Sluggable;
protected $guarded = [];
protected $casts = [
'images' => 'array'
];
public function sluggable()
{
return [
'slug' => [
'source' => 'title'
]
];
}
public function path()
{
return "/articles/$this->slug";
}
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
and this is my Route
Route::get('/articles/{articleSlug}' , 'ArticleController#single');
Change your code to
class ArticleController extends Controller
{
public function single(Article $article)
{
return view('article', compact('article'));
}
}
change route to
Route::get('/articles/{article}' , 'ArticleController#single');
And model
public function getRouteKeyName()
{
return 'slug';
}
See docs https://laravel.com/docs/5.7/routing#route-model-binding
You might not be getting any data because you have not specified that you're using title_slug as the route key for model binding in your model.
Add this to your model class and it should give you the data
public function getRouteKeyName()
{
return 'slug';
}
Then you can return the data in json, view or other format.
Depending on what you try to archive, you need to either ...
return $article->toJson(); // or ->toArray();
.. for json response or ..
return view(..., ['article' => $article])
for passing a the article to a certain view
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
I have the following models:
namespace App;
use Illuminate\Database\Eloquent\Model;
class forum_category extends Model
{
//
protected $table = 'forum_category';
public function posts()
{
$this->hasMany('App\forum_post');
}
}
And
namespace App;
use Illuminate\Database\Eloquent\Model;
class forum_post extends Model
{
//
protected $table = 'forum_post';
public function category()
{
$this->belongsTo('App\forum_category');
}
}
in my controller i attempt to get all categories with their posts:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\forum_category as forum_category;
class ForumController extends Controller
{
public function __construct()
{
}
public function index ()
{
$categories = forum_category::all();
return view('forum', ['categories' => $categories]);
}
public function createPost()
{
}
public function createReply()
{
}
}
However it seems to only be returning my categories.
Can someone tell me what ive done wrong?
The query should look like this:
$categories = forum_category::with('posts')->get();
https://laravel.com/docs/5.5/eloquent-relationships#eager-loading
If you have category_id in the forum_post table, this will load categories with related posts.
Then just iterate over the collection to get posts:
#foreach ($categories as $category)
#foreach ($category->posts as $post)
{{ $post->title }}
#endforeach
#endforeach
Also, the relationship should be:
public function category()
{
return $this->belongsTo('App\forum_category');
}