I am trying to build a commenting system where users are able to leave comments behind on posts.
I can save and display the post and on a page i display all post I have a form where users can leave comments behind. I am able to save the comments in the database but when I try to show the comments I get this error Undefined variable: comments (View: /var/www/resources/views/projects/comment.blade.php).
My files: Comment Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class Comment extends Model
{
use HasFactory, SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['user_id', 'post_id', 'parent_id', 'description'];
/**
* Write Your Code..
*
* #return string
*/
public function user()
{
return $this->belongsTo(User::class);
}
/**
* Write Your Code..
*
* #return string
*/
public function replies()
{
return $this->hasMany(Comment::class, 'parent_id');
}
}
Post Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class post extends Model
{
use HasFactory, SoftDeletes;
protected $dates = ['deleted_at'];
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [ 'titre',
'description',
'image',
'tag',
'video',
'status',
'user_id'];
/**
* Write Your Code..
*
* #return string
*/
public function comments()
{
return $this->hasMany(Comment::class)->whereNull('parent_id');
}
}
My CommentController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Comment;
class CommentController extends Controller
{
/**
* Write Your Code..
*
* #return string
*/
public function store(Request $request)
{
$input = $request->all();
$request->validate([
'body'=>'required',
]);
$input['user_id'] = auth()->user()->id;
Comment::create($input);
return back();
}
}
post display controller
public function post_display()
{
if(Auth::id()){
$userid=Auth::user()->id;
$profile=user::find($userid);
$post=post::where('user_id',$userid)->get();
return view('user.post_display',compact('post','profile'));
}
else{
return redirect()->back();
}
}
My post display view
#include('user.head')
#include('user.create_post')
<section class="ftco-section">
<div class="container" align="center" >
#foreach($post as $posts)
#if(session()->has('message2'))
<div class="alert alert-success">
<button type="button" class="close" data-dismiss="alert">
x
</button>
{{session()->get('message2')}}
</div>
#endif
<div class="col-md-8 col-xl-6 middle-wrapper">
<div class="row">
<div class="col-md-12 grid-margin">
<div class="card rounded">
<div class="card-header">
<div class="d-flex align-items-center justify-content-between">
<div class="d-flex align-items-center">
<img class="img-xs rounded-circle" src="https://bootdey.com/img/Content/avatar/avatar6.png" alt="">
<div class="ml-2">
<p>{{$profile->username}}</p>
<p class="tx-11 text-muted">{{$posts->created_at}}</p>
</div>
</div>
<div class="dropdown">
#include('user.update_post')
</div>
</div>
</div>
<div class="card-body">
<h5> {{$posts->tag}}
</h5>
<h4 class="mb-3 tx-14"> {{$posts->status}}</h4>
<p class="mb-3 tx-14"> {{$posts->description}}</p>
<img class="img-fluid" src="postimage/{{$posts->image}}" alt="">
</div>
<div class="card-footer">
<div class="d-flex post-actions">
<a href="javascript:;" class="d-flex align-items-center text-muted mr-4">
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart icon-md">
<path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path>
</svg>
<p class="d-none d-md-block ml-2">Like</p>
</a>
<h4>Display Comments</h4>
<hr />
#include('user.comment', ['comments' => $posts->comments, 'post_id' => $posts->id])
<h4>Add comment</h4>
<form method="post" action="{{ route('comments.store') }}">
#csrf
<div class="form-group">
<textarea class="form-control" name="description"></textarea>
<input type="hidden" name="post_id" value="{{ $posts->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Comment" />
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endforeach
</div>
</section>
#include('user.footer')
<!-- loader -->
<div id="ftco-loader" class="show fullscreen"><svg class="circular" width="48px" height="48px"><circle class="path-bg" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke="#eeeeee"/><circle class="path" cx="24" cy="24" r="22" fill="none" stroke-width="4" stroke-miterlimit="10" stroke="#F96D00"/></svg></div>
#include('user.script')
</body>
my comment dispaly view
#foreach($comments as $comments)
<div class="display-comment" #if($comments->parent_id != null) style="margin-left:40px;" #endif>
<strong>{{ $comments->user->name }}</strong>
<p>{{ $comments->body }}</p>
<form method="post" action="{{ route('comments.store') }}">
#csrf
<div class="form-group">
<input type="text" name="body" class="form-control" />
<input type="hidden" name="post_id" value="{{ $post_id }}" />
<input type="hidden" name="parent_id" value="{{ $comments->id }}" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-success" value="Reply" />
</div>
<hr />
</form>
#include('user.comment', ['comments' => $comments->replies])
</div>
#endforeach
My comment routes:
Route::post('comment',[CommentController::class,'comment'])->name('comments.store');
whene i try to create a new laravel project and put nothing other then post and comment it work.so i don't know where is the error.
Related
I building a page to insert rows into database tables using a HTML form. I created my view, model, controller, and route already and it return this error when i try to submit the form:
Attempt to assign property "id_gerai" on null
Here are the rest of the code
resources\views\dashboard\manajemen_donasi.blade.php
#extends('layouts.dashboard')
#section('title')
<title>KitaKenyang - Dashboard Admin</title>
#endsection
#section('nav_link')
<li class="nav-item active">
<a class="nav-link" href="/manajemen donasi">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Manajemen Donasi</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/manajemen penyimpanan">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Manajemen Penyimpanan</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="/manajemen penyaluran">
<i class="fas fa-fw fa-tachometer-alt"></i>
<span>Manajemen Penyaluran</span></a>
</li>
#endsection
#section('username')
Admin
#endsection
#section('content')
<!-- Page Heading -->
<div class="d-sm-flex align-items-center justify-content-between mb-4">
<h1 class="h3 mb-0 text-gray-800 text-center">Dashboard Manajemen Donasi</h1>
</div>
<div class="container-fluid">
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h6 class="m-0 font-weight-bold text-success">Input Donasi</h6>
</div>
<div class="card-body">
<form action="#" method="post" class="probootstrap-form">
#csrf <!-- {{ csrf_field() }} -->
<div class="form-group">
<label for="id_user">ID Donatur</label>
<input type="text" class="form-control" id="id_user" name="id_user">
</div>
<div class="form-group">
<label for="tanggal">Tanggal Donasi</label>
<input type="date" class="form-control" id="tanggal" name="tanggal">
</div>
<div class="form-group">
<label for="id_kategori_barang">Kategori</label>
<input type="text" class="form-control" id="id_kategori_barang" name="id_kategori_barang">
<i>* dry staple: 1 | dehydrated food: 2 | canned food: 3 | frozen food: 4</i>
</div>
<div class="form-group">
<label for="id_kuantitas">Kuantitas</label>
<input type="text" class="form-control" id="kuantitas" name="kuantitas">
</div>
<div class="form-group">
<label for="id_nama_barang">Nama barang</label>
<input type="text" class="form-control" id="nama_barang" name="nama_barang">
</div>
<div class="form-group">
<label for="id_gerai">ID Gerai</label>
<input type="text" class="form-control" id="id_gerai" name="id_gerai">
</div>
<div class="form-group">
<input type="submit" class="btn btn-success btn-lg" id="submit" name="submit" value="Input">
</div>
</form>
</div>
</div>
</div>
<!-- /.container-fluid -->
#endsection
routes\web.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Models\Donasi;
/*
|--------------------------------------------------------------------------
| 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('/', 'PagesController#index');
Route::get('/beranda', 'PagesController#index');
Route::get('/tentang kami', 'PagesController#about');
Route::get('/berita', 'PagesController#news');
Route::get('/program', 'PagesController#program');
Route::get('/gerai donasi', 'PagesController#gerai');
Route::get('/login', 'PagesController#login');
Route::get('/register', 'PagesController#register');
Route::get('/kinerja organisasi', 'DashboardController#laporan_org');
Route::get('/donasi user', 'DashboardController#laporan_user');
Route::get('/profil user', 'DashboardController#profil_user');
Route::get('/manajemen donasi', 'DashboardController#manajemen_donasi');
Route::post('manajemen donasi', 'DashboardController#input_donasi');
Route::get('/manajemen penyimpanan', 'DashboardController#manajemen_penyimpanan');
Route::get('/manajemen penyaluran', 'DashboardController#manajemen_penyaluran');
App\Models\Donasi.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Donasi extends Model
{
use HasFactory;
protected $table = 'donasi';
protected $primaryKey = 'id';
protected $fillable = [
'id_user',
'id_kategori_barang',
'id_gerai',
'nama_barang',
'kuantitas',
'tanggal',
];
public $timestamps = false;
}
app\Http\Controllers\DashboardController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Program;
use App\Models\DonasiDalamPenyimpanan;
use App\Models\TotalDonasi;
use App\Models\TotalDonatur;
use App\Models\Donasi;
class DashboardController extends Controller
{
public function laporan_org()
{
$totaldonatur = TotalDonatur::all();
$totaldonasi = TotalDonasi::all();
$program = Program::all();
return view('dashboard.laporan_org', compact('program', 'totaldonasi', 'totaldonatur'));
}
public function laporan_user()
{
return view('dashboard.laporan_user');
}
public function profil_user()
{
return view('dashboard.profil_user');
}
public function manajemen_donasi()
{
return view('dashboard.manajemen_donasi');
}
public function manajemen_penyimpanan()
{
$penyimpanan = DonasiDalamPenyimpanan::all();
return view('dashboard.manajemen_penyimpanan', compact('penyimpanan'));
}
public function manajemen_penyaluran()
{
$program = Program::all();
return view('dashboard.manajemen_penyaluran', compact('program'));
}
public function input_donasi(Request $request)
{
$donasi = new Donasi;
$donasi->id_user = $request->input('id_user');
$donasi->tanggal = $request->input('tanggal');
$donasi->id_kategori_barang = $request->input('id_kategori_barang');
$donasi->kuantitas = $request->input('kuantitas');
$donasi->nama_barang = $request->input('nama_barang');
$donasiModel->id_gerai = $request->input('id_gerai');
$donasi->save();
}
}
For a project, I've created a method where people can add products they want to buy to a wishlist. All items in the catalog are stored and each article has a hearticon that is clickable. Once it's clicked, it's added to my database.
However, when an article is added to favourites, the icon turns red but the original transparant icon is still there. So articles whom are added to favourites all have a filled and a transparant icon, which is not how it should be done.
Here is my code:
My View:
<div class="flex flex-col justify-evenly items-center lg:flex-row flex-wrap justify-between gap-y-20 gap-x-2 lg:p-20 lg:w-12/12">
#foreach ($articles as $article)
<div class="w-8/12 lg:w-3/12 flex flex-col justify-between xl:h-100">
<form action="{{route('wishlist.store', $article->id)}}" id="wish_form" method="post">
{{csrf_field()}}
<input name="user_id" type="hidden" value="{{Auth::user()->id}}" />
<input name="article_id" type="hidden" value="{{$article->id}}" />
<button type="submit" class=""><img src="{{ 'icons/0heart.png' }}" alt="" width="25" onclick="this.form.submit()" id="emptyHeart"></button>
#foreach ($wishlists as $wishlist)
#if ($wishlist->article_id === $article->id )
<button type="submit"><img src="{{ 'icons/1heart.png' }}" alt="" width="25" onclick="this.form.submit()" id="checked"></button>
#endif
#endforeach
</form>
<div class="h-2/3 xl:h-1/3 flex justify-center items-center">
{{-- <img src="{{$article->image}}" alt="" class="h-40"> --}}
</div>
<div class="h-20 mt-2">
<h4 class="text-md text-center flex"><strong>{{ $article->title }}</strong></h4>
</div>
<div class="flex flex-row flex-wrap justify-between items-center mt-4">
<p class="p-2">{{$article->prijs}}</p>
<p>Beschikbaar via {{$article->website->title}}</p>
</div>
</div>
#endforeach
</div>
My controller:
class FilterController extends Controller
{
public function catalogus(Request $r)
{
$articles = Article::all();
$categories = Category::all();
$websites = Website::all();
$wishlists = Wishlist::all()->where('user_id',auth()->user()->id);
$list = Wishlist::all()->where('article_id', $articles->id);
dd($list);
return view('catalogus', compact('articles', 'categories', 'websites', 'wishlists', 'list'));
}
}
My model:
class Wishlist extends Model
{
protected $table = "wishlists";
protected $fillable = [
'user_id',
'article_id',
'confirmed',
'available'
];
protected $casts = [
];
public function user()
{
return $this->belongsTo(User::class);
}
public function article()
{
return $this->belongsTo(Article::class);
}
You can use contains() collection method
<form action="{{route('wishlist.store', $article->id)}}" id="wish_form" method="post">
{{csrf_field()}}
<input name="user_id" type="hidden" value="{{Auth::user()->id}}"/>
<input name="article_id" type="hidden" value="{{$article->id}}"/>
#if ($wishlists->contains('article_id', $article->id))
<button type="submit">
<img src="{{ 'icons/1heart.png' }}" alt="" width="25"
onclick="this.form.submit()" id="checked">
</button>
#else
<button type="submit" class="">
<img src="{{ 'icons/0heart.png' }}" alt="" width="25"
onclick="this.form.submit()" id="emptyHeart" />
</button>
#endif
</form>
in my blog project using livewire, i have a relationship manyToMany between tables posts & tags using a pivot table call post_tag
when i want to edit a post , in the modal i get all the data from posts table using -> wire:model.defer="post.body" ( we're using the Post model)
for the tags, i'm using a foreach to cycling through all the tags but how to get the tags associates to the post ?
Models
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $guarded = ['id', 'created_at', 'updated_at'];
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class);
}
public function comments()
{
return $this->hasMany(Comment::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
use HasFactory;
protected $guarded = ['id', 'created_at', 'updated_at'];
public function posts()
{
return $this->belongsToMany(Post::class);
}
}
Migration post_tag table
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('post_tag', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('post_id');
$table->unsignedBigInteger('tag_id');
$table->foreign('post_id')->references('id')->on('posts')->onDelete('cascade');
$table->foreign('tag_id')->references('id')->on('tags')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('post_tag');
}
};
class
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Post;
use App\Models\Category;
use App\Models\Tag;
use Livewire\WithPagination;
use Livewire\WithFileUploads;
class EditHideForm extends Component
{
use WithPagination;
use WithFileUploads;
public $open = false;
public $post, $image, $identificador;
public $taggs;
protected $rules = [
'post.name' => 'required|max:100',
'post.slug' => 'required',
'post.body' => 'required',
'post.status' => 'required',
'post.user_id' => 'required',
'post.category_id' => 'required',
'post.image' => 'required',
'tagss' => 'required'
];
public function mount(Post $post)
{
$this->post = $post;
$this->tagss = $post->tags->toArray();
$this->identificador = rand();
}
public function save()
{
$this->validate();
$this->post->save();
/* codigo para borrar la foto Aqui */
$this->post->tags()->sync($this->tagss);
$this->reset(['open']);
$this->emitTo('show-post', 'render');
}
public function render()
{
$categories = Category::all();
$tags = Tag::all();
return view('livewire.edit-hide-form', compact('categories', 'tags'));
}
}
View
<div class="mb-2">
#auth
#if (auth()->user()->id === $post->user->id)
<x-jet-button wire:click="$set('open', true)">
Editar
</x-jet-button>
<x-jet-danger-button>
Eliminar
</x-jet-danger-button>
#endif
#endauth
</div>
<x-jet-dialog-modal wire:model="open" id="commentModal">
<x-slot name="title">
<h1 class="text-2xl mb-4">Edita tu post</h1>
</x-slot>
<x-slot name="content">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="container bg-white border-b border-gray-200 shadow-lg mx-auto justify-center px-4 py-2 ">
<section id="contact-us">
<div wire:loading wire:target='image'
class="bg-red-100 border border-red-400 text-xl font-normal max-w-full flex-initial">
<div class="py-2">
<p class="ml-2">Cargando la imagen</p>
<div class="text-sm font-base">
<p class="ml-2">Espero unos instantes mientras termine el proceso...</p>
</div>
</div>
</div>
#if ($image)
<img class="mb-4" src="{{ $image->temporaryUrl() }}" alt="">
#else
<img src="{{ Storage::url($post->image) }}" alt="">
#endif
<input class="hidden" wire:model="id_user" type="text" id="id" name="user_id" value={{
Auth::user()->id }}" />
<div>
<x-jet-label for="name" value="{{ __('Título') }}" />
<x-jet-input id="slug-source" class="block mt-1 mb-2 w-full" wire:model.defer="post.name"
type="text" name="name" required autofocus autocomplete="name" />
<x-jet-input-error for="name" />
<x-jet-label for="slug" value="{{ __('Slug') }}" />
<x-jet-input id="slug-target" class="block mt-1 w-full" wire:model.defer="post.slug"
type="text" name="slug" :value="old('slug')" required autofocus autocomplete="slug" />
<x-jet-input-error for="slug" />
</div>
<!-- body -->
<div>
<x-jet-label for="body" class="mt-4 text-base" value="{{ __('Contenido del post') }}" />
<textarea wire:model.defer="post.body" id="editor" rows="8" name="body"></textarea>
</div>
<x-jet-input-error for="body" />
<div class="mt-2 center justify-center mx-auto">
<!-- Image -->
<x-jet-label for="url" value="{{ __('Imagen') }}" />
<input type="file" id="image" name="image" class="mb-2" wire:model.defer="post.image" />
<x-jet-input-error for="image" />
</div>
<div>
<!-- Drop Down-->
<x-jet-label for="categories" value="{{ __('Categoría') }}" />
<select name="category_id" class="block font-medium text-sm text-gray-700" id="categories"
wire:model.defer="post.category_id">
<option selected disabled>opciones </option>
#foreach($categories as $category)
<option value="{{ $category->id }}">{{ $category->name }}</option>
#endforeach
</select>
</div>
<br>
<div>
<x-jet-label for="tags" value="{{ __('Etiquetas') }}" />
#foreach ($tags as $tag)
<label for="tagss"
class="relative flex-inline items-center isolate p-2 mr-4 mb-2 rounded-2xl">
<input wire:model.defer="tagss" value={{ $tag->id }} type="checkbox" class="relative
peer z-20 text-blue-600 rounded-md focus:ring-0" />
<span class="ml-1 relative z-20">{{ $tag->name }}</span>
</label>
#endforeach
</div>
<br>
<x-jet-label for="status" value="{{ __('Status') }}" />
<div class="flex">
<div class="inline-block rounded-lg">
Borrador <input type="radio" value=1 wire:model.defer="post.status" id="borrador" />
</div>
<div class="inline-block rounded-lg ml-4">
Publicado <input type="radio" value=2 wire:model.defer="post.status" name="publicado"
id="publicado" />
</div>
</div>
</section>
</div>
</div>
</x-slot>
<x-slot name='footer'>
<x-jet-secondary-button wire:click="$set('open', false)">
Cancelar
</x-jet-secondary-button>
<x-jet-danger-button wire:click="save">
Actualizar
</x-jet-danger-button>
</x-slot>
</x-jet-dialog-modal>
#push('js')
<script src="https://cdn.ckeditor.com/ckeditor5/34.0.0/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ) )
.then(function(editor){
editor.model.document.on('change:data', () => {
#this.set('body', editor.getData());
})
})
.catch( error => {
console.error( error );
} );
</script>
#endpush
</div>
I would appreciate any help or advice, thanks
Charles, I wrote a POC (Proof of concept) for this problem and just found that it's related to a typo, haha.
You have the public property taggs and then you're assigning $this->tagss, that's why livewire wasn't rendering the checkboxes correctly.
I would recommend you to switch to a more verbose property like tagsSelected instead of taggs (or tagss).
I am currently trying to display todos in my app-todo view, but I keep getting the error mentioned in the title.
In my controller I have:
public function index()
{
$todos = Todo::all();
return view('content.apps.todo.app-todo', ['todos' => $todos]);
}
and in my app-todo:
<div class="todo-task-list-wrapper list-group">
<ul class="todo-task-list media-list" id="todo-task-list">
#foreach($todos as $todo)
<li class="todo-item">
<div class="todo-title-wrapper">
<div class="todo-title-area">
<i data-feather="more-vertical" class="drag-icon"></i>
<div class="title-wrapper">
<div class="form-check">
<input type="checkbox" class="form-check-input" id="customCheck1" />
<label class="form-check-label" for="customCheck1"></label>
</div>
<span class="todo-title">Drink more water</span>
</div>
</div>
<div class="todo-item-action">
<div class="badge-wrapper me-1">
<span class="badge rounded-pill badge-light-primary">Team</span>
</div>
<small class="text-nowrap text-muted me-1">Aug 08</small>
<div class="avatar">
<img
src="{{asset('images/portrait/small/avatar-s-4.jpg')}}"
alt="user-avatar"
height="32"
width="32"
/>
</div>
</div>
</div>
</li>
#endforeach
I have tried changing the code in the controller to return view('content.apps.todo.app-todo')->with(['todos' => $todos]); and using compact('todos'); ,but I get the same error.
Update:
The model is the following:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Todo extends Model
{
protected $fillable = ['todoTitleAdd','task_assigned','task_due-date','task_tag', 'task_desc'];
}
and the web.php route:
Route::resource('todos', TodoController::class);
public function index(){
$todos = Todo::all();
return view('content.apps.todo.app-todo',compact('todos'));
}
I am trying to pass the id of a user from the users table from an authenticated users profile in a chat application I am trying to build. I keep getting SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'recever' cannot be null (SQL: insert into chats (message, sender, recever, updated_at, created_at) values (hi, 2, ?, 2021-05-24 21:13:20, 2021-05-24 21:13:20)). The recever column is always empty because I couldn't pass the id value of the user.
My Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Chat;
use App\Models\typing;
use App\Models\User;
use Auth;
use DB;
use URL;
use Illuminate\Support\Str;
class ChatController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request, $id=null){
$auth_id = Auth::user()->id;
$user = DB::table('users')->where('id', $id)->first();
$chat = new Chat;
$chat->message = $request->message;
$chat->sender = $auth_id;
$chat->recever = $user->id;
$chat->save();
typing::where('recever',$chat->recever)
->where('sender', $chat->sender)
->update(['check_status' => 0]);
return back();
}
}
My Blade file
#extends('layouts.app')
#section('content')
<?php
$recever=Route::input('id');
$id=Auth::id();
$user = DB::table('users')->where('id', $recever)->first();
?>
<link href="{{ asset('css/style.css') }}" rel="stylesheet">
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-primary">
<div class="panel-heading" style="height:40px;">
<div class="pull-left">
<a onclick="seenUpdate()" style="color:#fff;text-decoration:none; margin-left: 12px;" href="{{URL::to('/')}}">
<span class="glyphicon glyphicon-comment">
</span> <b class="smsnum"id="smsnum"></b> Message
</a>
<a style="color:#fff;text-decoration:none; margin-left: 12px;" href="{{URL::to('/users')}}">
<span class="glyphicon glyphicon-user"></span> User
</a>
</a>
<a style="color:#fff; text-decoration:none; margin-left: 12px;" href="{{URL::to('/')}}">
<span class="glyphicon glyphicon-search"></span> Search
</a>
</div>
<div class="pull-right">
{{$user->name}}
</div>
</div>
<div class="panel-body" id="scrolltoheight">
<ul class="chat">
<div id="chat-message">
</div>
</ul>
</div>
<div class="typing"><p id="typing"></p></div>
<div class="panel-footer">
<form id="message-submit" action="{{ url('/send-message/'.$user->id) }}" method="post"> {{ csrf_field()}}
<div class="input-group">
<input onkeyup="typing()" id="message" type="text" name="message" required class="form-control input-sm" placeholder="Type your message here..." />
<span class="input-group-btn">
<input type="submit" class="btn btn-warning btn-sm" id="btn-chat"value="Send"/>
</span>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
My Home controller that holds the home.blade.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Chat;
use DB;
class HomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Contracts\Support\Renderable
*/
public function index()
{
return view('home');
}
public function allmessage()
{
return view('allmessage');
}
function jsonResponse(){
$user = DB::table('chats')->get();
return response()->json($user);
}
}
You are trying to pass all of the model, instead you should pass only the id, try this:
//$chat->recever = $user;
$chat->recever = $user->id;
Also in your blade change this:
<form id="message-submit" action="{{ url('/send-message') }}" method="post">
To this:
<form id="message-submit" action="{{ url('/send-message/'.$user->id) }}" method="post">
The reason for this change is you are not passing the user of id, so it returns as null.