Implementing Searchable, a search trait for Laravel - php

I was trying to implement a searchable function using Searchable, a search trait for Laravel by nicolaslopezj, i have used the following code. But it doesn't seem to work. If there are only two records in the database it show the records but if more then two records it doesn't search.
Model: Contact.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Nicolaslopezj\Searchable\SearchableTrait;
class Contact extends Model
{
use SearchableTrait;
protected $searchable = [
'columns' => [
'contacts.first_name' => 10,
'contacts.last_name' => 10,
]];
}
Controller: SearchController
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Nicolaslopezj\Searchable\SearchableTrait;
use View;
use App\Contact;
use App\Tag;
use App\Project;
use App\User;
//use Illuminate\Support\Facades\Input;
class SearchController extends Controller
{
public function findContact(Request $request)
{
return Contact::search($request->get('cname'))->get();
}
public function contactPrefetch()
{
$all_contacts= Contact::All();
return \Response::json($all_contacts);
}
}
View: show.blade.php
<script src="{{asset('global/js/plugins/datatables/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('global/js/pages/base_tables_datatables.js')}}"></script>
<div class="input-group input-medium " style="float: right; padding-top: 3px; ">
<input type="search" name="cname" class="form-control search-input" placeholder="search contact" autocomplete="off" >
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap JS -->
<!-- Typeahead.js Bundle -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
<script>
jQuery(document).ready(function($) {
// Set the Options for "Bloodhound" suggestion engine
var engine = new Bloodhound({
prefetch: '/find_contact_all',
remote: {
url: '/find_contact?q=%QUERY%',
wildcard: '%QUERY%'
},
datumTokenizer: Bloodhound.tokenizers.whitespace('cname'),
// queryTokenizer: Bloodhound.tokenizers.whitespace
});
$(".search-input").typeahead({
hint: true,
highlight: true,
minLength: 1
}, {
source: engine.ttAdapter(),
name: 'contact',
display: function(data) {
return data.first_name + ' '+ data.last_name ;
},
templates: {
empty: [
'<a class="list-group-item"> Agent not found.</a>'
],
header: [
'<div class="list-group search-results-dropdown">'
],
suggestion: function (data) {
return '' + data.first_name + ' ' + data.first_name + ''
}
}
});
});
</script>
Routes:
Route::get('find_contact', 'SearchController#findContact');
Route::get('find_contact_all', 'SearchController#contactPrefetch');

Simply add the package to your "composer.json" file and "composer update"[update your composer]
"nicolaslopezj/searchable": "1.*"

Related

I am trying to get images from my backend api. But i am not able to perform that.please help me

I am trying to upload a image along with its details. but i can get the all details but only the image is not displaying in the browser. i used php laravel for backend api. The images are located in the Storage/app/apiDocs folder in backend laravel. the i write displayBooks function the get all the books in laravel. But in front end only image is not displaying. Here is a screenshot of output.
screenshot of inspect elements.
DisplayBooks.vue
<template>
<div class="bookdisplay-section">
<div class="book" v-for="book in books" :key="book.id">
<div class="image-section">
<div class="image-container">
<img v-bind:src="book.file" />
</div>
</div>
<div class="name-section">
{{book.name}}
</div>
<div class="author-section">
by {{book.author}}
</div>
<div class="price-section">
Rs. {{book.price}}<label>(2000)</label>
<button v-if="flag" type="submit" #click="handleSubmit();Togglebutton();">close</button>
</div>
<div class="rating">
<p>4.5<i class="fas fa-star"></i></p>
</div>
<div class="quantity">
<p>(20)</p>
</div>
</div>
</div>
</template>
<script>
import service from '../service/User'
export default{
name: 'DisplayBooks',
data(){
return{
flag: true,
books: [{
id: 1,
file: 'display image',
name: 'Dont make me Think',
author : 'Joseph',
price : '1500',
},]
}
},
methods:{
Togglebutton(){
this.flag = !this.flag;
},
async handleSubmit(){
service.userDisplayBooks().then(response => {
this.books.push(...response.data);
})
},
}
}
</script>
<style lang="scss" scoped>
#import "#/Styles/DisplayBooks.scss";
</style>
FileController.php
<?php
namespace App\Http\Controllers;
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
// use Illuminate\Http\Request;
use App\Http\Resources\Books as BooksResource;
use App\Models\Books;
use App\Models\User;
use Illuminate\Contracts\Filesystem\Filesystem;
use League\Flysystem\AwsS3v3\AwsS3Adapter;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class FileController extends Controller
{
public function displayBooks()
{
$books=Books::all();
return User::find($books->user_id=auth()->id())->books;
}
function upload(Request $request){
$book = new Books();
$book->price=$request->input('price');
$book->name=$request->input('name');
$book->quantity=$request->input('quantity');
$book->author=$request->input('author');
$book->description=$request->input('description');
$book->file=$request->file('file')->store('apiDocs');
$book->user_id = auth()->id();
$book->save();
return ["result"=>$book];
// return [$book];
}
public function updateBook(Request $request, $id)
{
$book = Books::find($id);
if($book->user_id==auth()->id()){
dd($request->all());
$book->price=$request->input('price');
$book->name=$request->input('name');
$book->quantity=$request->input('quantity');
$book->author=$request->input('author');
$book->description=$request->input('description');
// $book->file=$request->file('file')->store('apiDocs');
$book->save();
return[$book];
}
else
{
return response()->json([
'error' => ' Book is not available with this id'], 404);
}
}
Images will only be visible if the visibility of the file is set to public. The best practice here is to upload the image to the Public disk (https://laravel.com/docs/8.x/filesystem#the-public-disk). Make sure to create the symoblic link using php artisan storage:link.
This means you should change your upload function as well, to something like:
$request->file('file')->store('fileName', 'public');
In case this project will be made publicly available, consider adding Request validation to the store/update functions.

Laravel Pusher 401 Unauthorized

I cannot get my events working on laravel 7.x, pusher, laravel-echo. I have set up everything correctly but still getting 401 error. I have also set up broadcast_driver as pusher in .env file. If anyone can help, I will appreciate.
CommentEvent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;
class CommentEvent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $comment;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct($comment)
{
$this->comment =$comment;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new Channel('comment-channel');
}
public function broadcastAs()
{
return 'newComment';
}
}
CommentController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Events\CommentEvent;
use App\Comment;
class CommentController extends Controller
{
public function index(){
return view('comments');
}
public function fetchComments(){
$comments =Comment::all();
return response()->json($comments);
}
public function store(Request $request){
$comment =Comment::create($request->all());
event(new CommentEvent($comment));
return response()->json('ok');
}
}
/routes/channels.php
<?php
use Illuminate\Support\Facades\Broadcast;
/*
|--------------------------------------------------------------------------
| Broadcast Channels
|--------------------------------------------------------------------------
|
| Here you may register all of the event broadcasting channels that your
| application supports. The given channel authorization callbacks are
| used to check if an authenticated user can listen to the channel.
|
*/
// Broadcast::channel('App.User.{id}', function ($user, $id) {
// return (int) $user->id === (int) $id;
// });
Broadcast::channel('comment-channel', function () {
return true;
});
bootstrap.js
window._ = require('lodash');
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
window.axios = require('axios');
window.moment = require('moment');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
window.axios.defaults.headers.common.crossDomain = true;
// window.axios.defaults.baseURL = '/api';
let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://adonisjs.com/docs/4.1/csrf');
}
import Echo from 'laravel-echo';
window.Pusher = require('pusher-js');
window.Echo = new Echo({
broadcaster: 'pusher',
key: process.env.MIX_PUSHER_APP_KEY,
cluster: process.env.MIX_PUSHER_APP_CLUSTER,
forceTLS: true
});
store.js
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export const store =new Vuex.Store({
state:{
//stores all the comments in this array//
comments:[]
},
getters:{
//returns the comments array//
comments:state=>{
return state.comments
}
},
mutations:{
//populates the comments array in the state with the comments from the database//
getComments:(state,comments)=>{
state.comments =comments
},
addComment:(state,comment)=>{
state.comments = state.push(comment)
}
},
actions:{
/* gets all the comments from comments endpoint api*/
getComments:({commit})=>{
axios.get(`http://127.0.0.1:8000/api/comments`)
.then(res=>{
//commits getcomments mutation and passes a parameter of comments from the response//
commit('getComments',res.data)
})
.catch(err=>{
console.log(err)
})
},
addComment:({commit},comment)=>{
return new Promise((resolve,reject)=>{
axios.post(`http://127.0.0.1:8000/api/comments`,{
author:comment.author,
content:comment.content
})
.then(res=>{
resolve(res)
}).catch(err=>{
reject(err)
})
})
}
}
})
MainApp.vue
<template>
<div class="container">
<div class="row">
<div class="col">
<div class="card">
<div class="card-body">
<form #keyup.enter="postComment">
<div class="form-group">
<input type="text" class="form-control" placeholder="Author's Name" v-model="comment.author">
</div>
<div class="form-group">
<textarea name="comment" id="" rows="6" class="form-control" v-model="comment.content" >
</textarea>
</div>
<div class="form-group">
<input type="submit" value="Submit" class="btn btn-success" #click.prevent="postComment">
</div>
</form>
</div>
</div>
</div>
<div class="col">
<div class="card">
<div class="card-body">
<div class="media" v-for="comment in comments" :key="comment.id">
<img class="mr-3" src="https://api.adorable.io/avatars/48/#adorable.io.png" alt="Generic placeholder image">
<div class="media-body">
<h5>{{comment.author}}</h5>
{{comment.content}}
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
<script>
import {store} from '../store';
import {mapGetters} from 'vuex';
import {mapActions} from 'vuex';
export default {
store:store,
data:function(){
return{
comment:{
author:'',
content:''
}
}
},
mounted() {
//calls the action getcomments from store.js//
this.$store.dispatch('getComments');
Echo.channel('comment-channel')
.listen('.newComment', (e)=>{
console.log(e)
})
},
computed:{
//gets the comments array from store.js//
...mapGetters([
'comments'
])
},
methods:{
postComment:function(){
this.$store.dispatch('addComment',this.comment)
.then(res=>{
if(res==='ok'){
console.log('success')
}
}).catch(err=>{
console.log(err)
})
}
}
}
</script>
Make sure to pass $user into the channel route callback. replace this code with your channel route. then you are good to go :)
Broadcast::channel('comment-channel', function ($user) {
return true;
});

Websocket chat in Laravel isnt real time

I am creating a chat in Laravel Websocket i followed a youtube tutorial and the message goes to the other user they can talk with each other but i need to reload the page to get the message that was sent,its not real time.At the console before i send a message it says this error: Failed to load resource: the server responded with a status of 404 (Not Found) and than after sending says this POST http://127.0.0.1:8000/broadcasting/auth 404 (Not Found) .I have run "php artisan websocket:serve" command in terminal.Thanks in advance
ChatsController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function __construct()
{
$this->middleware('auth');//only authenticated users can acces to chat
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessage(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' => 'success'];
}
}
User.php
public function messages()
{
return $this->hasMany(Message::class);
}
Message.php
public function user()
{
return $this->belongsTo(User::class);
}
web.php
<?php
use App\User;
use App\Department;
use App\Events\WebsocketDemoEvent;
/*
|--------------------------------------------------------------------------
| 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('/', function () {
broadcast(new WebsocketDemoEvent('some data'));
return view('welcome');
});
Route::get('/page', function () {
return view('admin.page');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::group(['middleware' => ['auth','admin']], function () {
Route::get('/role-register','Admin\DashboardController#registered');
Route::delete('/role-delete/{id}', 'Admin\DashboardController#registerdelete');//delete user
Route::post('/save-user', 'Admin\DashboardController#store');
Route::get('/department', 'Admin\DepartmentController#index');
Route::post('/save-department', 'Admin\DepartmentController#store');
Route::get('/department-edit/{id}', 'Admin\DepartmentController#edit');//edit department
Route::put('/department-update/{id}', 'Admin\DepartmentController#update');
Route::delete('/department-delete/{id}', 'Admin\DepartmentController#delete');//delete department
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/chats', 'ChatsController#index');//chats
Route::get('/messages', 'ChatsController#fetchMessages');//messages
Route::post('/messages', 'ChatsController#sendMessage');//messages
Route::get('/dashboard', 'Admin\DashboardController#dbcheck');//DATABASE
Route::get('/user-edit/{id}', 'HomeController#registeredit');
Route::get('/role-edit/{id}', 'Admin\DashboardController#registeredit');//edit user
Route::put('/role-register-update/{id}', 'Admin\DashboardController#registerupdate');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('store_image', 'StoreImageController#index');
Route::post('store_image/insert_image', 'StoreImageController#insert_image');
Route::get('store_image/fetch_image/{id}', 'StoreImageController#fetch_image');
Route::get('/page',array('as'=>'jquery.treeview','uses'=>'Admin\DepartmentController#treeView'));
Route::get('/pageusers', 'Admin\DepartmentController#usersdep');
ChatsComponent.vue
<template>
<div class="row">
<div class="col-8">
<div class="card card-default">
<div class="card-header">Messages</div>
<div class="card-body p-0">
<ul class="list-unstyled" style="height:300px; overflow-y:scroll">
<li class="p-2" v-for="(message, index) in messages" :key="index">
<strong>{{ message.user.name }}</strong>
{{ message.message }}
</li>
</ul>
</div>
<input
#keyup.enter="sendMessage"
v-model="newMessage"
type="text"
name="message"
placeholder="Enter your message"
class="form-control">
</div>
<span class="text-muted">user is typing...</span>
</div>
<div class="col-4">
<div class="card card-default">
<div class="card-header">Active Users</div>
<div class="card-body">
<ul>
<li class="py-2">{{ user.name }}</li>
</ul>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
props:['user'],
data() {
return {
messages: [],
newMessage:''
}
},
created() {
this.fetchMessages();
Echo.join('chat')
.listen('MessageSent',(event) => {
this.messages.push(event.message);
})
},
methods: {
fetchMessages() {
axios.get('messages').then(response => {
this.messages = response.data;
})
},
sendMessage(){
this.messages.push({
user: this.user,
message: this.newMessage
});
axios.post('messages', {message: this.newMessage});
this.newMessage = '';
}
}
}
</script>
MessageSent.php
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use App\Message;
class MessageSent implements ShouldBroadcast
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $message;
/**
* Create a new event instance.
*
* #return void
*/
public function __construct(Message $message)
{
$this->message = $message;
}
/**
* Get the channels the event should broadcast on.
*
* #return \Illuminate\Broadcasting\Channel|array
*/
public function broadcastOn()
{
return new PresenceChannel('chat');
}
}
Sorry to post this as an answer, but you need 50 reputation to place a comment.
Did you uncomment the App\Providers\BroadcastServiceProvider::class, line in your config/app.php?

Autocomplete Search not Working in Laravel

I have a search field with the same name and id inside my categories page and inside my products page.The autocomplete suggestions seems to work fine , however once I click on requested product inside the search field, it's stays on the same page and not redirecting me to the view.I want my view to show only products. This is my code so far:
After update
My routes:
<?php
Route::get('products/{id}', 'AutoCompleteController#show');
Route::get('autocomplete', array('as' => 'autocomplete', 'uses' => 'AutoCompleteController#show'));
Route::get('searchajax', array('as' => 'searchajax', 'uses' => 'AutoCompleteController#autoComplete'));
My AutoCompleteController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\MainController;
use App\Product;
class AutoCompleteController extends MainController
{
public function show(Product $product)
{
return view('content.products', ['product' => $product]);
}
public function autoComplete(Request $request)
{
$query = $request->get('term', '');
$products = Product::where('title', 'LIKE', '%' . $query . '%')->get();
$data = [];
foreach ($products as $product) {
$data[] = array('label' => $product->title, 'value' => $product->id);
}
if (count($data)) {
return $data;
} else {
return ['value' => 'No Result Found', 'id' => ''];
}
}
}
My view in products.blade.php and categories.blade.php for my autocomplete search is the same:
#extends('master')
#section('content')
<link href="http://demo.expertphp.in/css/jquery.ui.autocomplete.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="row">
<form class="navbar-form text-center " form method="GET" action=" ">
<input id="search_text" placeholder=" Search products" name="search_text" type="text" value=""
style="width: 400px; height: 35px; border-radius: 5px ; padding-left: 12px;"><br><br>
<input class="btn btn-default " type="submit" value=" Search">
</form>
</div>
<script>
$(document).ready(function () {
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
select: function (event, ui) {
window.location = '{{ url('shop/{category_url}')}}' + ui.item.id
} // not sure if this is the correct way , please advise
});
});
</script>
#endsection
If you seems the issue with JS conflict, try below code:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
Added missing ui css too. Let me know the result.
There are a few problems:
An autocomplete response should include label and value pairs, you are returning value and id. See the jQuery UI source docs.
Your Javascript is missing the select event handler, which specifies what happens when one of the suggestions is selected. So right now clicking one will just fill the clicked value in the input field. See the jQueryUI autocomplete select docs.
Maybe you want to be able to view product ID 1 when you browse to /products/1. First you need to set up a route for that:
Route::get('products/{id}', 'AutoCompleteController#index');
Then in your controller, first fix the autocomplete response to return the right format:
foreach ($products as $product) {
$data[]=array('label'=>$product->title,'value'=>$product->id);
}
Next, still in the controller, update the method for showing your product (BTW this should probably be called show, index would usually be a list of products:
use App\Product;
class AutoCompleteController extends MainController {
// This assumes you have a Product model
public function index(Product $product) {
return view('content.products', ['product' => $product]);
}
And your Javascript:
$("#search_text").autocomplete({
source: function (request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term: request.term
},
success: function (data) {
response(data);
}
});
},
minLength: 3,
select: function( event, ui ) {
// Your autoComplete response returns the ID in the 'value' field
window.location = 'http://yoursite.com/products/' + ui.item.value
}
});

Not able to store boolean value in database in laravel

I am trying to make like and dislike system in laravel and I am doing this by by returning 1 when someone clicks like and 0 when someone dislikes but databse is showing no entry.
here is the code in my web.php
<?php
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index');
//comments
Route::resource('comments','CommentsController');
//like
Route::post('/like', [
'uses' => 'LikeController#postLikePost',
'as' => 'like'
]);
here is my controllers code:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class LikeControler extends Controller
{
//
public function postLikePost(Request $request)
{
$is_like = $request['isLike'] === 'true';
$update = false;
$user = Auth::user();
$like = $user->likes();
if ($like) {
$already_like = $like->like;
$update = true;
if ($already_like == $is_like) {
$like->delete();
return null;
}
} else {
$like = new Like();
}
$like->like = $is_like;
$like->user_id = $user->id;
if ($update) {
$like->update();
} else {
$like->save();
}
return null;
}
}
here is my layout code named create.blade.php
<html>
<head>
<h1>DONE</h1>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<script>
$('.like').on('click', function(event) {
event.preventDefault();
var isLike = event.target.previousElementSibling == null;
$.ajax({
method: 'POST',
url: urlLike,
data: {isLike: isLike,_token: token}
})
</script>
<script> var urlLike ='{{ route ('like')}}'; </script>
</head>
<body>
<div class="row new-post">
<div class="col-md-6 col-md-offset-3">
<header><h3>Comments</h3></header>
<form action="/comments" method="post">
{{csrf_field()}}
<div class="form-group">
<textarea class="form-control" name="body" id="new-post" rows="5" placeholder="Your review on above game"></textarea>
</div>
<button type="submit" class="btn btn-primary">Post Comment</button>
</form>
</div>
</div>
<div class="interaction">
Like
Unlike
</div>
#foreach($comments as $comment)
<h1>{{$comment->body }}</h1>
#endforeach
</body>
</html>
here is my migration code:-
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateLikesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('likes', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('user_id');
$table->boolean('like');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('likes');
}
}
here is my user.php code
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function likes()
{
return $this->hasMany('App\Like');
}
}
here is code of like.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Like extends Model
{
//
public function user()
{
return $this->belongsTo('App\User');
}
}
I have even uploaded my code on github https://github.com/Pawan98/lara .Thans in advance :-)
Check the column data type for the associative column. For storing 0 or 1 into a column, either the column is:
Int,
String,
Boolean,
Enum('0', '1') or
TinyInt
So change it to one of them and try again.
If it is boolean than do not wrap it into single quotes

Categories