(Internal Server Error) laravel and ajax - php

I am newbie in laravel and I get internal server error when i use ajax .
I found when I want to save data(comment object) in database i have got this error exactly when I write this line:
$request->Post()->comments()->save($comment);
in the controller file.I attach all necessary code here.is there any body to help me please?
route.php
Route::post('/savecomment',[
'uses'=>'CommentController#postCreateComment',
'as'=>'comment.save'
]);
commentController.php
public function postCreateComment(Request $request)
{
$this->validate($request,[
'commentBody'=>'required|max:1000'
]);
$comment=new Comment();
$comment->body=$request['commentbody'];
$comment->post_id=$request['postId'];
$message ='there was an error';
$request->Post()->comments()->save($comment);
$message='comment successfuly created';
//return redirect()->route('dashboard')->with(['message'=>$message]);
}
jquery
$('[id^=comment-save]').on('click', function (event) {
event.preventDefault();
postId = $(this).parents('.post').attr('data-postId');
$.ajax({
method :'POST',
url: urlComment,
data:{postId:postId,_token:token,commentBody:$('#comment-body'+postId ).val()}
})
.done(function(){
//change the page
});
html part
<section class="row posts">
<div class="cod-md-6 col-md-offset-3">
<header><h3>what is other`s idea</h3></header>
#foreach($posts as $post)
<article class="post" data-postId='{{ $post->id}}'>
<p>
{{$post->body}}
</p>
<div class="info">
posted by {{$post->user->first_name}} in {{$post->created_at}}
</div>
<div class="interaction">
<a class="like" href="#">Like</a>|
<a class="dislike" href="#">Dislike</a>|
<a data-toggle="collapse" href="#collapseComment{{ $post->id }}" aria-expanded="false" aria-controls="">
comment
</a>
#if(Auth::user() == $post->user)
|<a data-toggle="modal" href="#edit-model" class="edit" >Edit</a>|
Delete
#endif
</div>
<div class="collapse" id="collapseComment{{ $post->id }}">
<div class="card card-block">
<input type="test" name="comment-body{{ $post->id }}" id="comment-body{{ $post->id }}" >
<button type="button" id="comment-save{{ $post->id }}" class="btn btn-primary">comment</button>
</div>
</div>
</article>
#endforeach
</div>
</section>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment.save') }}';
</script>
comment class
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function post()
{
return $this->belongsTo('App\Post');
}
}
post class
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\user');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}

I think $comment->save(); will be ok.

Related

$post->user->name not working (ErrorException Trying to get property 'name' of non-object) || Laravel 8

I was trying to show the name who have posted the post. It was working well. But after a few days, It is showing an error (ErrorException Trying to get property 'name' of non-object). I was searching for a solution for the last few days. And I have found laravel 8 introduced jetstream for authentication purposes. But I have already started with the laravel ui.
I have checked the model of mine. But I could not find anything which could solve the problem. Here are my codes.
view
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-10 mx-auto">
#foreach ($posts as $post)
<div class="post-preview">
<a href="{{route('singlePost',$post-> id )}}">
<h2 class="post-title">
{{$post->title}}
</h2>
<h3 class="post-subtitle">
{!!$post->content!!}
</h3>
</a>
<p class="post-meta">Posted by
{{$post->user->name}}
on {{date_format($post->created_at,'F d,Y')}}
|| <i class="fa fa-comment" aria-hidden="true"></i> {{$post->comments->count()}}
</p>
</div>
<hr>
#endforeach
<!-- Pager -->
<div class="clearfix">
<a class="btn btn-primary float-right" href="#">Older Posts →</a>
</div>
</div>
</div>
</div>
<hr>
#endsection
Model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
public function user(){
return $this->belongsTo('App\Models\User');
}
public function comments(){
return $this->hasMany('App\Models\PostComments');
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PublicController extends Controller
{
//This is the function which is showing posts
public function index(){
$posts = Post::all();
return view("welcome",compact('posts'));
}
public function contact(){
return view("contact");
}
public function about()
{
return view('about');
}
public function samplePost(Post $post){
return view('samplePost', compact('post'));
}
}

I want to display username of comment's owner, however, comments table has user_id only

After I send the variable that contains the comments to the view, I can only display the user id. This is why I need to somehow foreach through all the comments and based on their user_id to add a new key-pair value with username-username and send it to the view afterwards. Unfortunately, I'm having trouble figuring how to do that.
public function specificImage($id){
$similarImages = null;
$image = Image::with('comments.user')->find($id);
$subImages = Image::where('parent_id', $id)->get();
$views = $image->views;
$image->views = $views + 1;
$image->save();
$authorId = $image->user_id;
$author = User::find($authorId);
$comments = Comment::where('image_id', $id)->get();
$recentImages = Image::where('parent_id', NULL)->where('user_id', $authorId)->orderBy('created_at', 'desc')->limit(9)->get();
$tag = Tag::whereHas('images', function($q) use ($id) {
return $q->where('taggable_id', $id);
})->first();
if (!empty($tag)) {
$tagId = $tag->id;
}
if (!empty($tagId)) {
$similarImages = Image::where('parent_id', NULL)->whereHas('tags', function($q) use ($tagId) {
return $q->where('tag_id', $tagId);
})->orderBy('created_at', 'desc')->limit(9)->get();
}
return view('specificImage', ['image' => $image,'subImages' => $subImages, 'recentImages' => $recentImages, 'similarImages' => $similarImages, 'author' => $author, 'comments' => $comments]);
}
Table:
Table: Comments
Columns: id, user_id, image_id, comment
Image model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Image extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
public function tags(){
return $this->morphToMany('App\Tag', 'taggable');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function updateVotes()
{
$this->upvotes = Vote::where('image_id', $this->id)->where('vote', true)->count();
$this->downvotes = Vote::where('image_id', $this->id)->where('vote', false)->count();
$this->save();
}
public function updateComments()
{
$this->comments = Comment::where('image_id', $this->id)->count();
$this->save();
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function image(){
return $this->belongsTo('App\Image');
}
public function user(){
return $this->belongsTo('App\User');
}
}
User model:
<?php
namespace App;
use Illuminate\Contracts\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Authenticatable
{
use \Illuminate\Auth\Authenticatable;
public function images(){
return $this->hasMany('App\Image');
}
public function comments(){
return $this->hasMany('App\Comment');
}
public function votes(){
return $this->hasMany('App\Vote');
}
public function roles(){
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}
public function hasAnyRole($roles) {
if (is_array($roles)) {
foreach ($roles as $role) {
if ($this->hasRole($role)){
return true;
}
}
} else {
if ($this->hasRole($roles)){
return true;
}
}
return false;
}
public function hasRole($role){
if ($this->roles()->where('name', $role)->first()){
return true;
}
return false;
}
}
Blade
#extends('layouts.app')
#section('content')
<div class="specific-image-flexbox">
<div class="specific-image-column">
<div class='specific-image-container'>
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$image->file_name)}}' alt='Random image' />
#foreach($subImages as $subImage)
<img class='specific-image' src='{{url("storage/uploads/images/specificImages/".$subImage->file_name)}}' alt='Random image' />
#endforeach
</div>
</div>
<div class="artwork-info-column">
<div class="artwork-info-container">
<p class='title'>{{ $image->name }}<p>
<p class='author'>на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
#if(Auth::user())
#if(Auth::id() === $image->user_id || Auth::user()->hasRole('Admin'))
<a class='placeholderDelete' href='{{ route('deleteImage', ['image_id' => $image->id]) }}'><i class="far fa-trash-alt"></i> Изтрий изображението</a>
#endif
#endif
<p class='description'>{{ $image->description }}</p>
<p class='description'>Техника: {{ $image->medium }}</p>
<p><i class="far fa-eye"></i> {{ $image->views }} Преглеждания</p>
<p><i class="far fa-thumbs-up"></i> {{ $image->upvotes }} Харесвания</p>
<p class='commentsCount'><i class="far fa-comments"></i> {{ $image->comments }} Коментари</p>
<a class='downloadImage' href="{{url("storage/uploads/images/specificImages/".$image->file_name)}}" download="{{ $image->name }}"><i class="fas fa-file-download"></i> Изтегли</a>
<!--<a class='placeholderDelete fas fa-expand' href='{{url("storage/uploads/images/specificImages/".$image->file_name)}}'></a>-->
<div class='social-container'>
<div class="addthis_inline_share_toolbox"
data-url="{{ url()->full() }}"
data-title="{{ $image->name }} by {{ $author->username }}"
data-description="{{ $image->description }}"
data-media="{{url("storage/uploads/images/specificImages/".$image->file_name)}}">
</div>
</div>
#if(!empty($recentImages))
#if(count($recentImages) >= 9)
<p class='author'>Още произведения на<a href='{{url("profile/".$author->username )}}'><span class='usernameA artwork-info-username-span'>{{$author->username}}</span></a><img class='artwork-info-profile-picture' src='{{url("storage/uploads/profile_pictures/edited/".$author->profile_picture)}}'></p>
<div class="more-images-container">
#foreach($recentImages as $recentImage)
<div class="more-images-container-element">
<a href='{{url("image/".$recentImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$recentImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#if(!empty($similarImages))
#if(count($similarImages) >= 9)
<p class='similar-images'>Подобни произведения</p>
<div class="similar-images-container">
#foreach($similarImages as $similarImage)
<div class="similar-images-container-element">
<a href='{{url("image/".$similarImage->id)}}'>
<img class='more-images' src='{{url("storage/uploads/images/miniImages/".$similarImage->file_name)}}' alt='Random image' />
</a>
</div>
#endforeach
</div>
#endif
#endif
#auth
<div class='postComments'>
<form method='POST' action=''>
<textarea class='comment-section' name='comment'></textarea>
<input type="hidden" name="user_id" value="{{ Auth::user()->id }}">
<input type="hidden" name="image_id" value="{{ $image->id }}">
<button class='postComment submit' type='submit' name='commentSubmit'>Изпрати</button>
</form>
</div>
#endauth
<div class='comments'>
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach
</div>
</div>
</div>
</div>
<script>
var token = '{{ Session::token() }}';
var urlComment = '{{ route('comment') }}';
var urlLike = '{{ route('vote') }}';
</script>
#endsection
I would suggest adding the user relationship to your Comment model as well:
class Comment extends Model
{
public function image()
{
return $this->belongsTo('App\Image');
}
public function user()
{
return $this->belongsTo('App\User');
}
}
You can then eager load the relationships and then access them in your blade file:
public function specificImage($id)
{
$image = Image::with('comments.user')->find($id);
return view('specificImage', ['image' => $image]);
}
Then in your blade file you would have something like:
#foreach($image->comments as $comment)
{{ $comment->user->username }}
#endforeach

How I use relationship in blade template (hasOne) || Laravel

Okay i'm trying get "likes" and "users" in Posts by relationship hasOne.
here is my Post.php Model
class Posts extends Model
{
protected $table = 'posts';
public function User()
{
return $this->hasOne(User::class, 'id', 'user_id');
}
public function Like()
{
return $this->hasOne(Like::class, 'post_id', 'id');
}}
My Blade template
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{$deal->like->status}}
<br>
{{$deal->user->email}}
<div class="sl-item">
<div class="sl-left"> <img src=" {{asset( '/assets/images/users/2.jpg')}}" alt="user" class="img-circle"> </div>
<div class="sl-right">
<div> {{$deal->user->username}} || {{$deal->subject}} <Br> <span class="sl-date">{{$deal->created_at}}</span>
<div class="m-t-20 row">
<div class="col-md-3 col-xs-12"><img src="{{$deal->image}}" alt="user" class="img-responsive radius"></div>
<div class="col-md-9 col-xs-12">
<p> {{$deal->body}} </p> עבור למוצר </div>
</div>
<div class="like-comm m-t-20"> 2 תגובות <i class="fa fa-heart text-danger"></i> 5 לייקים </div>
</div>
</div>
</div>
</div>
<hr></div>
</div>
#endforeach
And there is my Controller
class PostsController extends Controller
{
public function showdeals()
{
$showdeals = Posts::with( 'User', 'Like')->get();
return view('posts.show', compact('showdeals'));
}
public function helpnewview(){
return view('posts.anew');
}
public function helpnew(Request $request){
//User pick link
$userlink = $request['userlink'];
return \Redirect::route('newdeal', compact('userlink'));
}
public function new(Request $request)
{
//Emdeb user link
$link = Embed::create($request['userlink']);
$linke = $request['userlink'];
return view('posts.new', compact('link', 'userlink', 'linke'));
}
public function create(Request $request)
{
$posts = New Posts;
$posts->user_id = Auth::User()->id;
$posts->subject = $request['subject'];
$posts->body = $request['body'];
$posts->link = $request['link'];
$posts->price = $request['price'];
$posts->image = $request['image'];
$posts->tag = $request['tag'];
$posts->save();
return back();
}
}
Now if I do something like {{$deal->user->email}} its will work,
if I go to something like this {{$deal->like->status}} its does not work,
am I missing something ?
If you want multiple relationships to be eagerly loaded you need to use an array of relationships: Model::with(['rl1', 'rl2'])->get();
public function showdeals()
{
...
$showdeals = Posts::with(['User', 'Like'])->get();
...
}
EDIT:
From that json in the comments that I see, there is no attribute named status in your Like model so thats probably the root of the problem
Controller edit this code
public function showdeals()
{
$showdeals = Posts::all();
return view('posts.show', compact('showdeals'));
}
And blade file code
#foreach ($showdeals as $deal)
<div class="tab-pane active" id="home" role="tabpanel">
<div class="card-body">
<div class="profiletimeline">
{{ $deal->Like->status }}
<br>
{{ $deal->User->email }}
#endforeach
I think everything is good except
{{$deal->like->status}} {{$deal->user->email}}
Please try as
{{$deal->Like()->status}}
<br>
{{$deal->User()->email}}

laravel private chat application

Hello i'm a new developer and in my laravel project i have implemented a real time group chat that uses ajax but now i need a real time chat between users in ajax i have tried many things but none have worken it would be very helpful if you could help me or if could send me a link to a good tutorial
Here's the index of my group chat :
#extends('admin.app')
#section('content')
<div class="container">
<div class="row" style ="padding-top:40px;">
<h3 class="text-center">Welcome {{Auth::user()->FullName}}</h3>
<br/><br/>
<div class="col-md-2">
<p>Users online</p>
#foreach($users as $user)
#if($user->isOnline())
<li>{{$user->FullName}}</li>
#endif
#endforeach
</div>
<div class="col-md-8">
<div class="panel panel-info">
<div class="panel-heading">
Recent Chat
</div>
<div class="panel-body">
<ul class="media-list" id="message">
#foreach($messages as $message )
<li class="media">
<div class="media-body">
<div class="media">
<div class="media-body" >
{{$message->message}}
<br/>
<bold> <small class="text-muted">{{$message->from_name}} |{{$message->created_at}}
</small></bold>
<hr>
</div>
</div>
</div>
</li>
#endforeach
</ul>
<div>
<div class="panel-footer">
<div class="input-group">
<input type="text" name="message" class="form-control" placeholder="Enter Message"/>
{{csrf_field()}}
<input type="hidden" name="from_name" value="{{Auth::user()->FullName}}">
<span class="input-group-btn">
<button type="submit" id="send" class="btn btn-info">Send</button>
</span>
</div>
</div>
</div>
<div class="col-md-2">
</div>
</div>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/assets/admin/plugins/jquery/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
setTimeout(realTime, 2000);
});
function realTime() {
$.ajax({
type:'post',
url:'/chat/get',
data:{
'_token':$('input[name=_token]').val(),
},
success: function (data) {
$('#message').replaceWith(' <ul class="media-list" id="message"></ul>');
for (var i=0; i < data.length; i++){
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data[i].message+'<br/><small class="text-muted">'+data[i].from_name+'|'+ data[i].created_at+'</small><hr/></div></div></div></li>')
}
},
});
setTimeout(realTime, 2000);
}
$(document).on('click','#send', function (){
$.ajax({
type:'post',
url:'/chat/send',
data:{
'_token':$('input[name=_token]').val(),
'from_name':$('input[name=from_name]').val(),
'message':$('input[name=message]').val(),
},
success: function (data) {
$('#message').append(' <li class="media"><div class="media-body"><div class="media"><div class="media-body">'+data.message+'<br/><small class="text-muted">'+data.from_name+'|'+ data.created_at+'</small><hr/></div></div></div></li>');
}
})
$('input[name=message]').val('');
});
</script>
#stop
here are the routes of my group chat:
Route::get('/chat', 'Chat\ChatController#index')->name('chat.index');
Route::post('/chat/send', 'Chat\ChatController#sendMessage' )->name('admin.chat.sendMessage');
Route::post('/chat/get', 'Chat\ChatController#getMessage' );
here's my controllers of the group chat:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
$users=user::all();
$messages=message::all();
return view('admin.chat.index',['messages'=> $messages],compact('users'));
}
public function sendMessage(Request $request){
$send = new Message();
$send ->from_name = $request->from_name;
$send ->message = $request->message;
$send->save();
return response()->json($send);
}
public function getMessage(){
$message = Message::all();
return response()->json($message);
}
here the migration for my gruop chat :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMessagesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('messages', function (Blueprint $table) {
$table->increments('id');
$table->string('from_name');
$table->text('message');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('messages');
}
}
Sorry in advance for the bad english and it would very grateful if you could help me or if you could send the link of a good tutorial
You need a live connection for that using a websocket, and you can achieve this with Laravel.
What this does is actually keep the connection between the server and the clients open and allows the server to send data to the clients, not just the other way around. Therefore you are able to send the messages to one of the people in your chat as soon as you receive them from the other participant.
That's called Broadcasting in Laravel, take a look at the documentation here:
https://laravel.com/docs/5.5/broadcasting

Pagination replacing new search results with old ones when try to change page

I've added a ajax search box in app's home page. It works fine. But when i use the pagination after the new results shows up, pagination leads me to the old results. I'm not sure what I'm not doing right. So looking for expert's help to get a solution for it.
I've these in routes --
Route::get('/', 'BookmarkController#index');
Route::post('/', 'BookmarkController#search');
I've these in their controller -
public function index(Request $request)
{
$tags_list = Tag::orderBy('tag', 'asc')->get();
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->paginate(10);
$bookmarks_all = Bookmark::orderBy('created_at','desc')->where('public', '1')->get();
return view('welcome')->with('bookmark', $bookmarks)->with('tags_list', $tags_list)->with('bookmarks_all', $bookmarks_all);
}
public function search(Request $request){
$search_value = $_POST['search'];
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->where('title', 'rlike', $search_value)->orwhere('description', 'rlike', $search_value)->orwhere('contents', 'rlike', $search_value)->orwhere('tags', 'rlike', $search_value)->paginate(10);
return view('public_bookmarks')->with('bookmark', $bookmarks);
}
In welcome.blade.php
<div class="container content-container">
<div class="row ">
<div class="col-sm-12">
<div class="page-header">
<div class="row">
<span class="title col-sm-8">Recent Bookmarks</span>
<form id="demo-2" class="search-form col-sm-4" method="post">
{{ csrf_field() }}
<div class="input-group">
<!-- <input id="search" class="form-control" onkeyup="search_data(this.value, 'result');" placeholder="Search" name="search" value="" type="text"> -->
<input id="search" class="form-control" placeholder="Search" name="search" value="" type="text">
<span class="input-group-btn">
<button class="btn btn-primary" id="search-btn" type="button"><i class="fa fa-search"></i></button>
</span>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#search-btn').click(function(){
$.ajax({
url: '/',
type: "post",
data: {'search':$('input[name=search]').val(), '_token': $('input[name=_token]').val()},
success: function(data){
$('#search-results').html(data);
},
error: function (data) {
console.log('Error on Article extracting');
console.log(data);
}
});
});
});
</script>
</form>
</div>
</div>
</div>
<div class="col-sm-9" id="search-results">
#include ('public_bookmarks')
</div>
</div>
In public_bookmars.blade.php
#if (count($bookmark) > 0)
<div class="row card-row">
#foreach ($bookmark as $bookmark_single)
<div class="col-sm-4 col-xs-12 card-parent" data-col="col-sm-4">
<div class="card">
<div class="card-part1">
<div class="img-card">
<img src="{{$bookmark_single->thumbnail}}" />
</div>
<div class="card-content">
<h4 class="card-title">
{{ $bookmark_single->title }}
</h4>
<div class="card-desc">
{{ str_limit($bookmark_single->description, $limit = 50, $end = ' [...]') }}
</div>
</div>
<div class="card-read-more">
<p><?php $tags = $bookmark_single->tags;
$tag_list = explode(',', $tags); ?>
#foreach ($tag_list as $tag)
{{$tag}}
#endforeach
</p>
<p class="card-user">- {{ $bookmark_single->bookmarker }}</p>
<a class="v-link" target="_blank" href="{{ $bookmark_single->url }}">Visit the link</a>
</div>
<button type="button" class="btn btn-success btn-circle btn-lg btn-read-more"><i class="fa fa-chevron-right"></i></button>
</div>
<div class="card-part2 col-xs-0">
{{ print $bookmark_single->contents }}
</div>
</div>
</div>
#endforeach
</div>
{{ $bookmark->links() }}
#endif
You can use flash() method to achieve this. Old Input
In your search() method add $request->flash(). This will flash the current inputs in the session.
And, next time you want retrieve it by $request->old('search');
Here's the complete search() method:
public function search(Request $request){
$search_value = $_POST['search']; //assign the current value of search field
if(!$search_value) //check if current value is not null, means this is new search or previous one
{
$search_value = $request->old('search'); //If search_value is null use the old value
$request->search = $request->old('search'); //add the old value to current request so that it can be flashed
}
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->where('title', 'rlike', $search_value)->orwhere('description', 'rlike', $search_value)->orwhere('contents', 'rlike', $search_value)->orwhere('tags', 'rlike', $search_value)->paginate(10);
$request->flash(); //adding this request's search value to the session
return view('public_bookmarks')->with('bookmark', $bookmarks);
}
Update:
public function search(Request $request){
//$search_value = $_POST['search']; change this to use $request
$search_value = $request->search;
$bookmarks = Bookmark::orderBy('created_at','desc')->where('public', '1')->where('title', 'rlike', $search_value)->orwhere('description', 'rlike', $search_value)->orwhere('contents', 'rlike', $search_value)->orwhere('tags', 'rlike', $search_value)->paginate(10);
return view('public_bookmarks')->with('bookmark', $bookmarks)->withInput($request->only('search')); // flashed input to the view
}
Now, in your view you can get the value with old() method:
{{ $bookmark->appends(['search' => old('search')])->links()}}
Update 2:
change your ajax call to use get method and point it to new address:
type: "get",
url: '/search'
Add a route to handle search request as a get method:
Route::get('/search', 'BookmarkController#search');
In your search() method use $request to get the search value:
$search_value = $request->search;

Categories