Adding comments to my website via AJAX in laravel 8 - php

I need to store the comment and then show it without reloading the page using AJAX
meaning that I will not use redirect() and not even go the route: /comment/create
I am using Laravel 8
the form in HTML "post.blade.php"
<form action={{route('comment.store')}} method="post">
#csrf
<div class="form-floating">
<textarea class="form-control" placeholder="Leave a comment here" id="floatingTextarea2" style="height: 100px" name="feedback"></textarea>
<label for="floatingTextarea2">Leave a Comment</label>
<button type="submit" class="btn btn-outline-info mt-1">feedBack</button>
<input type="hidden" name='postid' value={{$post->id}}>
</div>
</form>
the Route "web.php"
Route::post('/comment/create','App\Http\Controllers\CommentController#store')->name('comment.store');
Route::get('/articles/{id}/','App\Http\Controllers\ArticlesController#getArticle')->name('singleArticles');
The Article Controller: the function where sho the article
public function getArticle($id){
$row = DB::table('posts')
->join('categories','categories.id','=','posts.category_id')
->join('users','users.id','=','owner_id')
->select('posts.*','categories.name as name_categories','users.name as owner_name','users.id as owner_id')
->where('posts.id',$id)
->first();
$data['post'] = $row;
$data['page_title'] = $row->title;
$data['categories'] = DB::table('categories')->get();
//this line here is for importing comments and showing them later
$data['result'] = DB::table('comments')
->join('posts','posts.id','=','comments.post_id')
->join('users','users.id','=','contributor_id')
->select('comments.*','users.name as name')
->where('posts.id',$id)
->orderby('comments.id','desc')
->get();
return view('post',$data);
}
And the Comment Controller where I store the comments after submitting
public function store(Request $request)
{
$id_user = Auth::user()->id;
$ldate = date('Y-m-d H:i:s');
$feedback = $request->input('feedback');
$postid = $request->input('postid');
$data = array('contributor_id'=>$id_user,'text'=>$feedback,'post_id'=>$postid,'created_at'=>$ldate);
DB::table('comments')->insert($data);
return redirect()->route('singleArticles',$postid);
}

Related

How do I show the name of the related tables in my "empleados" datatable after doing a search in Laravel 8?

Sorry for my grammar, english is not my native language.
My data table is working fine when is not doing any search. But, when I do a search with the field nombre is giving me this error:
Undefined property: stdClass::$departamento (View: /Users/xxx/Sites/contablerd/resources/views/rrhh/empleado/index.blade.php)
This is my "Advanced Search" above the table:
<form action="#" method="GET">
<h3>Busqueda Avanzada</h3><br>
<div class="row">
<div class="row g-2">
<div class="col-md">
<div class="form-floating">
<input type="nombre" class="form-control" id="nombre" name="nombre" placeholder="" value="">
<label for="nombre">Nombre</label>
</div>
</div>
</div>
</div><br>
<input type="submit" value="Search" class="btn btn-secondary">
</form>
This is the part of the code where I am using a foreach. This part work fine when I am not using the "Advanced Search" (rrhh/empleado/index.blade.php):
#foreach($empleados as $empleado)
<tr>
<td>{{$empleado->id}}</td>
<td>{{$empleado->nombre}}</td>
<td>{{$empleado->apellido}}</td>
<td>{{$empleado->departamento->det}}</td>
<td>{{$empleado->cargo->det}}</td>
<td>{{$empleado->nomina->det}}</td>
<td>{{number_format($empleado->sueldo,2)}}</td>
<td>{{number_format($empleado->ars_empleado+$empleado->afp_empleado,2)}}</td>
<td>{{number_format($empleado->sueldo-($empleado->ars_empleado-$empleado->afp_empleado),2)}}</td>
<td>
<a class="btn btn-info" href="/empleado/{{$empleado->id}}/edit">Editar</a>
<button class="btn btn-danger">Borrar</button>
</td>
</tr>
#endforeach
This is my index method where I confirm is there is any request to change the query (EmpleadoController.php):
public function index(Request $request)
{
$empleados = \DB::table('empleados');
if($request->input('nombre')){
$empleados = $empleados->where('nombre', 'LIKE', "%".request('nombre')."%");
$empleados = $empleados->get();
}else{
$empleados = Empleado::all();
}
return view('rrhh.empleado.index',
[
'empleados'=>$empleados
]);
}
So when I do a search is giving me the above error. I got all my relationships in Empleado.php model.
I would like to ask too, is this the correct way to do this?
Thanks in advance and happy rest of the day.
Added eager loading for departamento, cargo and nomina relations and used the query based on the model, using DB will not access your relations.
public function index(Request $request)
{
if($request->has('nombre')) {
$empleados = Empleado::with(['departamento', 'cargo', 'nomina'])->where('nombre', 'LIKE', '%' . $request->get('nombre') . '%')->get();
} else {
$empleados = Empleado::all();
}
return view('rrhh.empleado.index', ['empleados' => $empleados]);
}
First, Did you identify the code line where this error was generated Undefined property: stdClass::$departamento ?
Second, it's recommended use compact instead array in the controller, like that
public function index(Request $request)
{
$empleados = \DB::table('empleados');
if($request->input('nombre')){
$empleados = $empleados->where('nombre', 'LIKE', "%".request('nombre')."%");
$empleados = $empleados->get();
}else{
$empleados = Empleado::all();
}
return view('rrhh.empleado.index',compact('empleados'));
}
If there are something wrong in your model, you need share it here to can see how you have the relationships

Can't update in database data. Laravel

I have a small problem with my Controller action. I can't update my "link" in Database, bt dd method work is correctly when I'm try to check data.
Form
<form class="col-lg-push-6" action="/admin/links/{{$link->id}}/update" method="POST">
#csrf
<div class="form-group bmd-form-group">
<label class="bmd-label-floating">New Link Value</label>
<input type="text" class="form-control" size="100" name="value">
<button class="btn btn-primary" type="submit">Update</button>
</div>
</form>
Controller
public function update(Request $request, $id)
{
$this->validate($request, [
'value' => 'required'
]);
$link=RedirectUrl::AllLinks()->where('id', $id);
$link->value = $request->input('value');
return redirect()->back()->with('message', 'Link Updated!');
}
Model
public function scopeAllLinks($query){
return $query->get();
}
Route
Route::prefix('admin')->middleware('auth')->group(function(){
Route::get('/', 'Admin\IndexController#index');
Route::get('dashboard', 'Admin\IndexController#index')->name('dashboard');
Route::get('links', 'Admin\LinkController#index')->name('links');
Route::get('links/{id}', 'Admin\LinkController#linkById');
Route::post('links/{id}/update', 'Admin\LinkController#update');
});
Few things here:
Your scopeAllLinks scope is incorrect, you don't call get inside a scope, instead you return the query builder instance.
You can use find since you're passing in a record id:
$link = RedirectUrl::find($id);
You never call save or update on the record:
$link->value = $request->input('value');
$link->save(); // <--- add this

Pass id from controller index to store - Laravel

This is my route :
Route::post('/store', 'EditlinkController#store');
My controller
public function index()
{
$id = $_GET['id'];
$links = DB::table('slugs')->where('slugs.id',$id)
->join('links','links.sid','=','slugs.id')
->get();
return view('editlink', ['links' => $links]);
}
public function store(Request $request, $id)
{
$url = $request->input('url');
$data =new link;
$sid = $id;
$data->sid = $sid;
$data ->url = $url;
$data ->save();
return redirect('/links');
}
And my view:
<form role="form" method='POST' action="{{url('store')}}">
<div class="entry input-group col-xs-3">
<input class="form-control" name="url" type='url' placeholder="https://..." size="100"/>
<input type="hidden" name="_Token" value="{{ csrf_token() }}">
<button type="submit" class="btn btn-primary" type="button">
<span class="material-icons md-12">add</span>
</button>
{{ csrf_field() }}
</div>
</form>
So basically here I want to call $id from index to store. I also have tried
Route::post('/store/{id}', 'EditlinkController#store');
But still doesn't work. Thank you.
Your route, /store/{id}, requires you to have a route parameter. Make sure you have an $id available to you before you generate your url for your form.
An example of what your open form tag should look like with the $id included:
<form role="form" method='POST' action="{{url('store', $id)}}">
I'm assuming the view editlink is where the markup for the form resides. If so, then you can simply pass the value of the id to your view from your controller:
return view('editlink', ['links' => $links, 'id' => $id]);

Edit page show blank in laravel

I have news details inserted and i need to show it on the edit page but when i try to edit and delete it shows blanks page insert and show is working properly. i have been stucked on this from morning. id is getting from the database but it shows a blank page,Not using any Form helper
1.what's problem,is it on route file
2.is it on Controller file
route.php
Route::get('/', function () {
return view('welcome');
});
Route::resource('books','BookController');
Route::resource('news','NewsController');
Auth::routes();
Route::get('/news','NewsController#index')->name('news');
//Route::get('/news/create','NewsController#create');
//Route::get('/news/edit','NewsController#edit');
Edit.blade.php
#extends('theme.default')
#section('content')
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default">
<div class="panel-heading">
NEW BEE NEWS DETAILS
</div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<form method="post" action="{{route('news.update',[$news->id])}}"
enctype="multipart/form-data">
{{csrf_field()}}
<input type="hidden" name="_method" value="put">
<div class="form-group">
<label>NEWS TITLE</label>
<input type="text" name="atitle" id="atitle" class="form-control"
placeholder="PLEASE ADD TITLE OF NEWS" value="{{$news->name}}">
<p class="help-block">Example: SELFY PLAYSHARE </p>
</div>
<div class="form-group">
<label>NEWS</label>
<textarea name="news" id="news" class="form-control" {{$news->news}}></textarea>
<p class="help-block">DETAILED NEWS HERE</p>
</div>
<div class="form-group">
<label>NEWS LINK</label>
<input type="text" name="alink" id="alink" class="form-control"
placeholder="PLEASE ADD LINK OF NEWS" value="{{$news->alink}}">
<p class="help-block">Example: https://play.google.com/store/apps/selfyplusure</p>
</div>
<div class="form-group">
<label>NEWS IMAGE</label>
<input type="file" name="addimage" id="addimage" value="{{$news->imagename}}">
</div>
<button type="submit" class="btn btn-default">ADD NEWS</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
NewsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
use App\News;
use Illuminate\Http\Request;
class NewsController extends Controller
{
public function index()
{
$news = News::all();
return view('news.index', ['news' => $news]);
}
public function create()
{
return view('news.create');
}
public function store(Request $request)
{
$news=new News();
if($request->hasFile('addimage')){
$request->file('addimage');
$imagename=$request->addimage->store('public\newsimage');
$news->name = $request->input('atitle');
$news->alink = $request->input('alink');
$news->news = $request->input('news');
$news->imagename = $imagename;
$news->save();
if($news) {
return $this->index();
} }
else{
return back()->withInput()->with('error', 'Error Creating News ');
}
}
public function show(News $news)
{
//
}
public function edit(News $news)
{
$news=News::findOrFail($news->id);
return view('news.edit',['News'=>$news]);
}
public function update(Request $request, $id)
{
$news = News::findOrFail($id);
// update status as 1
$news->status = '1';
$news->save();
if ($news) {
// insert datas as new records
$newss = new News();
//On left field name in DB and on right field name in Form/view
$newss->name = $request->input('atitle');
$newss->alink = $request->input('alink');
$newss->news = $request->input('news');
$newss->imagename = $request->input('addimage');
$newss->save();
if ($newss) {
return $this->index();
}
}
}
public function destroy($id)
{
$news = News::findOrFail($id);
$news->status = '-1';
$news->save();
if ($news) {
return $this->index();
}
else{
return $this->index();
}
}
}
Link to delete and Edit
<td><input type="button" name="edit" value="EDIT">
<td><input type="button" name="delete" value="DELETE"></td>
This is the link to edit
<td><input type="button" name="edit" value="EDIT">
For delete please go through
Delete
In your controller try to use this.
return view('news.edit',compact('news'));

How to show message after filter in laravel?

After selecting Filter,I want to show summary tab/message what we selected.
I googled it and found session method, is it suitable in my case?
Here is my blade
{!! Form::open(['url'=>'/jobseekers','method'=>'GET', 'class'=>'form', 'id'=>'search_data']) !!}
<div class="form-group col-md-4">
<input type="text" name="fullname" placeholder="Name" value="{{ request()->input('fullname')}}" class="form-control"/>
</div>
<div class="form-group col-md-4">
<input type="text" name="fb_name" placeholder="Fb Name" value="{{ request()->input('fb_name')}}" class="form-control"/>
</div>
<button class="btn btn-flat btn-primary">Search</button>
</div>
{!! Form::close() !!}
and in my controller
public function index(Request $request)
{
$result = null;
if(count($request->all())!=0){
if ($request->has('sub_search')) {
$jobseekers = Jobseeker::Subsearch($request)->paginate(10);
dd($applicant_information);
}else{
$result=Jobseeker::Search($request)->paginate(10);
// dd($orders);
}
}
else{
$jobseekers = Jobseeker::with('calllogs')->orderBy('created_at', 'desc')->paginate(16);
}
return view('backend.jobseekers.index',compact('jobseekers','result'));
}
I am using get method to filter,and i want to show like
The Search results for fullname and fb_name are:
Is there any way to do like that in my case? Please guide me, thanks.
Are you trying to display filtered result in view? If so, change your code to:-
public function index(Request $request)
{
$fullname = $request->fullname;
$fb_name= $request->fb_name;
$result = null;
if(count($request->all())!=0){
if ($request->has('sub_search')) {
$jobseekers = Jobseeker::Subsearch($request)->paginate(10);
dd($applicant_information);
}else{
$result=Jobseeker::Search($request)->paginate(10);
// dd($orders);
}
}
else{
$jobseekers = Jobseeker::with('calllogs')->orderBy('created_at', 'desc')->paginate(16);
}
return view('backend.jobseekers.index',compact('jobseekers','result'))->with('fullname',$fullname)->with('fb_name',$fb_name);
}
All you need to is to access the passed variable from this controller is like
The Search results for {{$fullname}} and {{$fb_name}} are:
and loop your result here...

Categories