Comment Table Giving SQLSTATE[42S02] laravel 5.8 - php

I am trying to make an forum where the user can post a Thread and on the bottom of the thread the user can comment to thread but when I add the commenting part to the thread it throws the SQLSTATE[42S02] Error I am trying to use Morph relation ships from laravel https://laravel.com/docs/5.8/eloquent-relationships so I can connect the thread to the corresponding thread or comment. and the final product has to be someting like Reddits one http://prntscr.com/mwvors where comment go under each other and comment can be commented on other comments.
Edit:
after php artisan migrate it updated the the migrations but give this error instead
Error
"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'comments.commmentable_id' in 'where clause' (SQL: select * from `comments` where `comments`.`commmentable_id` = 1 and `comments`.`commmentable_id` is not null and `comments`.`commmentable_type` = App\Thread) (View: C:\Users\Merlijn\AppData\Roaming\Composer\Laravel Projects\Forum\resources\views\thread\single.blade.php
single.blade.php
{{--Answers/comments--}}
<div class="comment-list">
#foreach($thread->comments as $comment)
<h4>{{$comment->body}}</h4>
<lead>{{$comment->user->name}}</lead>
#endforeach
</div>
<div class="comment-form">
<form action="{{ route('threadcomment.store', $thread->id) }}" method="post" role="form">
{{csrf_field()}}
<h4>Create Comment</h4>
<div class="form-group">
<input type="text" class="form-control" name="body" id="" placeholder="Input...">
</div>
<button type="submit" class="btn btn-primary">Comment</button>
</form>
</div>
user model
public function threads(){
return $this->hasMany(Thread::class);
}
thread model
public function user()
{
return $this->belongsTo(User::class);
}
public function comments()
{
return $this->morphMany(Comment::class,'commmentable');
}
comment model
public function commenttable()
{
return $this->morphTo();
}
public function user()
{
return $this->belongsTo(User::class);
}
comment controller
public function addThreadComment(Request $request, Thread $thread)
{
$this->validate($request,[
'body' => 'required|min:10|max:250'
]);
$comment = new Comment();
$comment->body = $request->body;
$comment->user_id = auth()->user()->id;
$thread->comments()->save($comment);
}
web.php
Route::resource('comment','CommentController', ['only' =>['update','destroy']]);
Route::post('comment/create/{thread}','ThreadController#storeComment')->name('threadcommment.store');

there where typos in the code
public function comments()
{
return $this- >morphMany(Comment::class,'commmentable');
}
Route::post('comment/create/{thread}','ThreadController#storeComment')->name('threadcommment.store');
triple MMM instead of 2 mm

Related

Call to undefined function App\Http\Controllers\categories() in Laravel

Please I need help, I am working on a project in Laravel, I encounter a problem when T tried to use a pivot table in manay-to-many
In my category model Category.php, I have the function below
public function users()
{
return $this->belongsToMany(user::class);
}
In my user model User.php, I have the function below
public function authors()
{
return $this->belongsToMany(author::class);
}
In web.php, I have this
Route::post('/onboarding', 'OnboardsController#categoryUser');
In my onboarding view, I have a form:
<form action="{{ url('/onboarding') }}" method="POST">
#csrf
#foreach($categories as $category)
<div class="radio-item">
<input class="form control" name="category_id" type="checkbox" id="category_id" required>
<label for="name">{{ $category -> title }}</label>
</div>
#endforeach
<div class="form-row">
<div class="form-group col-md-12 text-center">
<button type="submit">Proceed to Authors</button>
</div>
</div>
</form>
In my OnboardsController
I have this
public function categoryUser (Request $request)
{
$user = User::findOrFail(Auth::user()->id);
$user = categories()->attach($request->input('category_id'));
return redirect ( route ('onboarding_author'));
}
This is the returned error:
Call to undefined function App\Http\Controllers\categories()
When I change the code in my controller to
$category = Category::find($request->input('category_id'));
$user = User::where('user_id', Auth::id());
$category->users()->attach($user->id);
This is the returned error:
Call to undefined function App\Http\Controllers\users()
Here is my full OnboardsController.php code
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;
use App\Author;
use App\User;
use App\Category;
class OnboardsController extends Controller
{
public function index()
{
//
return view('onboarding')
->with('categories', Category::all());
}
public function author()
{
//
return view('onboarding_author')
->with('authors', Author::all());
}
public function categoryUser (Request $request)
{
dd(request('category_id'));
Category::findOrFail(request('category_id'))
->users()
->attach(auth()->user()->id);
return redirect ( route ('onboarding_author'));
}
Please I am new to Laravel and I have been on this for 3 days, I don't know how to solve this. I need help.
Your problem is right here:
$user = User::findOrFail( Auth::user()->id );
$user = categories()->attach($request->input('category_id'));
^^^^^^
You are calling a method categories() on... what? on nothing. I'm assuming that you want to call the categories() method inside your User.php model. So try updating your code like this:
$user = User::findOrFail( Auth::user()->id );
$user->categories()->attach($request->input('category_id'));
^^^^^
This way, you will relate both objects.
Side notes
As I mentioned, I'm assuming that you have the categories method in your User model:
# User.php
public function categories()
{
return $this->belongsToMany(Category::class);
}
Remember that models should be capitalized.
Also, you could improve your code getting the User directly from the Auth facade
This:
$user = User::findOrFail(Auth::user()->id);
is the equivalente of:
$user = Auth::user();
You can achieve this with the following:
public function categoryUser()
{
Category::findOrFail(request('category_id'))
->users()
->attach(auth()->user()->id);
return redirect(route('onboarding_author'));
}
Here, you get the Category by the request's category_id, and attach the logged in user (using the auth() helper to get the user's id).
replace
$category->users()->attach($user->id);
return BACK()->with('message', "message!");

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.

Two models for one Controller in Laravel (methods Edit & Update)

Would you please let me know if this controller SerieController is correct? As I don't think so.
There are two models in fact. One Model is Serie and the other is Mark.
When, I click on the drop down list, I don't see my items...
public function edit($id)
{
$series = Serie::with('marks')->find($id);
return view('admin.series.edit', compact('series'));
}
public function update(Request $request, $id)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
$series = Serie::with('marks')->find($id);
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
My edit.blade.php
<form class="panel-body" action="{{route('series.update',$series->id)}}" method="POST">
<input name="_method" type="hidden" value="PATCH">
#csrf
<fieldset class="form-group">
<label for="form-group-input-1">Name</label>
<input type="text" name="name" class="form-control" id="form-group-input-1" value="{{$series->name}}">
</fieldset>
<div class="form-group">
<label for="company-content">Select Mark</label>
<select name="fk_mark" id="" class="form-control">
#foreach($series->marks as $mark)
<option value="{{$mark['id']}}">{{$mark['name_mark']}}</option>
#endforeach
</select>
</div>
Concerning the model
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
public function cars(){
return $this->hasMany('App\Car','fk_serie');
}
}
Thank you in advance.
In your edit function you have to do this:
public function edit($id)
{
$series = Serie::with('marks')->find($id);
return view('admin.series.edit', compact('series'));
}
and in your blade you will fetch the marks like this:
$series->marks->name_mark;
and it is the same method for update function to update two tables data.
I hope it would helpful.
First of all: Which version of Laravel do you use?
Check out route model binding which would compact your functions like this:
public function edit(Serie $serie)
{
$series->load('marks');
return view('admin.series.edit', compact('series'));
}
public function update(Request $request, Serie $serie)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
$series->load('marks');
$series->name = $request->get('name');
$series->fk_mark = $request->get('fk_mark');
$series->save();
return redirect()->route('series.index')
->with('success', 'updated successfully');
}
Further tipps for debugging:
Set 'debug' => true in your app.php
Try to use dd($serie); to see what happens to your model.
Install debugbar: composer require barryvdh/laravel-debugbar --dev
Check your database tables to see if your code successfully created the data.
Write Unit/Feature Test to validate your application logic
Provide more data in your next SO question like sql schema, error messages etc
Without the sql schema and exact problem you're facing it's very hard to debug someone else code. I hope this helps nonetheless.
Edits: grammar, spelling and last sentence fixed/added

Comment on posts

Hey Guys I'm trying to store comments for every service in my website
first I created the relationships between user,comment,service
then when I try to add a comment I get an error :
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'services_id' cannot be null (SQL: insert into comments (body, user_id, services_id, updated_at, created_at) values (ggg, 1, , 2018-03-20 21:12:17, 2018-03-20 21:12:17))
That's the service model : Service.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Service extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function comments(){
return $this->hasMany('App\comment');
}}
That's the model Comment.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
public function services() {
return $this->belongsTo('App\Service');
}}
That's the model User.php
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
protected $fillable = ['username', 'email','password','tel','ville','description','image','diplomes','langues',
];
protected $hidden = [
'password', 'remember_token',
];
public function services(){
return $this->hasMany('App\Service');
}
public function comments(){
return $this->hasMany('App\Comment');
}}
the route:
Route::post('/services/{services_id}','CommentsController#store');
Store method in CommentsController :
public function store(Request $request, $services_id)
{
$this->validate($request,array(
'body'=>'required',
));
$comment=new Comment;
$service=Service::find($services_id);
$comment->body=$request->body;
$comment->user_id=$request->user()->id;
$comment->services()->associate($service);
$comment->save();
$request->session()->flash('notif','success');
return back(); }
And that's the blade page
<form class="col s12" method="post" action="/services/{$services->id}">
{{ csrf_field() }}
<div class="row">
<div class="input-field col s12">
<i class="material-icons prefix">insert_comment</i>
<textarea id="textarea1" name="body" class="materialize-textarea"></textarea>
<label for="textarea1" style="color: black;">Commentaire</label>
</div>
</div>
<div class="row">
<div class="col s12 center-align">
<input type="submit" value="confirmer" class="btn-large purple hoverable">
</div>
</div>
</form>
Your answer is here:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'services_id' cannot be null (SQL: insert into comments (body, user_id, services_id, updated_at, created_at) values (ggg, 1, MISSING VALUE , 2018-03-20 21:12:17, 2018-03-20 21:12:17))
Your query want to put to database services_id but it is undefined in yoour request
So debug it:
Make dd($request) and see the services_id value
Guess CommentController should look like this:
public function store(Request $request, $services_id)
{
$this->validate($request,array(
'body'=>'required',
));
$comment=new Comment;
$service=Service::find($services_id);
$comment->body=$request->body;
$comment->user_id=$request->user()->id;
$comment->service_id=$services_id; //here I made change!!!
$comment->save();
$request->session()->flash('notif','success');
return back(); }

Trying to get column data from pivot table laravel

Hi I'm trying to output a certain column from my pivot table. To show you what I have tried, I will first show you my models (my pivot tables are ordertasks and tagtasks):
Task table:
class Task extends \Eloquent {
// Add your validation rules here
public static $rules = [
// 'title' => 'required'
];
// Don't forget to fill this array
protected $fillable = ['task_name','task_description','hour','difficulty'];
public function ordertask()
{
//oneToMany
return $this->hasMany('Ordertask', 'id_task', 'id');
}
public function tagtask()
{
//oneToMany
return $this->hasMany('Tagtask', 'id_task', 'id');
}
}
Tagtask table:
<?php
class Tagtask extends \Eloquent {
protected $fillable = ['id_tag','id_task'];
public function task()
{
//manyToOne
return $this->belongsTo('Task', 'id_task', 'id');
//return $this->belongsTo('Task');
}
public function tag()
{
//manyToOne
return $this->belongsTo('Tag', 'id_tag', 'id');
}
}
Ordertask table:
<?php
class Ordertask extends \Eloquent {
// Add your validation rules here
public static $rules = [
// 'title' => 'required'
];
// Don't forget to fill this array
protected $fillable = ['id_order','id_task', 'hour', 'hourprice','id_user', 'createdBy'];
public function user()
{
//manyToOne
return $this->belongsTo('User', 'id_user', 'id');
//return $this->belongsTo('User');
}
public function task()
{
//manyToOne
return $this->belongsTo('Task', 'id_task', 'id');
//return $this->belongsTo('Task');
}
}
Here is my TaskController.php with the following piece of code:
public function index()
{
$Tasks=Task::with('tagtask','ordertask')->get();
return View::make('user.tasks.index', compact('Tasks'));
}
Okay now comes the part where I want to show $Task->ordertask['id_user'] on my browser with the following piece of code:
#if (count($Tasks))
<ul>
#foreach($Tasks as $Task)
<div class="row">
<div class="col-md-3">
<li>
{{--as a third parameter we need to pass in the id of task, because it needs to be fed to
our actual user.task.edit route. --}}
{{link_to_route('user.tasks.edit', $Task['task_name'], array($Task->id))}}
</li>
</div>
<div class="col-md-3">
<li>
{{$Task->ordertask['id_user']}}
</li>
</div>
<div class="col-md-3">
<li>
{{$Task['task_hour']}}
</li>
</div>
<div class="col-md-3">
<li>
{{Form::open(array('route'=>array('user.tasks.destroy',$Task->id),
'method'=>'delete','class'=>'destroy'))}}
{{Form::submit('Delete')}}
{{Form::close()}}
</li>
</div>
</div>
#endforeach
</ul>
#endif
Unfortunately that doesn't work because I get the following error:
Undefined index: id_user
Instead of:
{{$Task->ordertask['id_user']}}
I have also tried this just to see what output it gave me:
{{$Task->ordertask}}
Which gave me the following output:
[{"id":5,"id_order":2,"id_task":1,"hour":63,"hourprice":15,"id_user":5,"createdBy":4,"created_at":"2014-10-13 10:21:33","updated_at":"2014-10-13 10:21:33"}]
So gladly I want to output id_user from the ordertask table. Gladly I'm waiting on your answer. Anyway thanks for your response.
One Task can have many order tasks, so to display users instead of
{{$Task->ordertask['id_user']}}
You should use:
#foreach ($Task->ordertask as $ot)
{{ $ot->id_user }}
#endforeach

Categories