Not able to store boolean value in database in laravel - php

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

Related

how do I call a variable in Laravel

I'm trying to call a variable from a table, but I'm getting an error "Undefined variable $user". I'm trying to make the program display the Username from the user from the table.
I'm using 2 tables, tribes which represents something like a group, and a user which represents.. well.. user.
So I'm trying to connect the two by displaying the creator of a certain "tribe".
User controller:
<?php
namespace App\Http\Controllers;
Use App\Models\User;
use Illuminate\Http\Request;
class tribesController extends Controller
{
public function index($user)
{
$user = User::findOrFail($user);
return view('home',[
'user'=>$user,
]);
}
}
Homepage:
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>
<div class="card-body">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
{{ $user->username }}
</div>
</div>
</div>
</div>
</div>
#endsection
Router:
<?php
use Illuminate\Support\Facades\Route;
/*
Route::get('/', function () {
return view('welcome');
});
Route::get('/home', function () {
return view('home');
});
Route::get('/playlist', function () {
return view('playlist');
});
Route::get('/tribe', function () {
return view('tribe');
});
Route::get('/edit', function () {
return view('edit');
});
Auth::routes();
Route::get('/tribe/{user}', [App\Http\Controllers\TribesController::class, 'index'])->name('tribe.index');
Database file:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateTribesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('tribes', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id');
$table->string('title');
$table->string('genre');
$table->string('filepath')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('tribes');
}
}
model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class tribe extends Model
{
public function user(){
return $this->belongsTo(User::class);
}
use HasFactory;
}
You are treating the url parameter as a object, it can't be an object until you get it. Pass in a user id and then query the ORM for a user matching that id then you can use it as an object!

Laravel websocket real time chat with vue.js

Hi I am trying to build a laravel real time chat. I configured websockets and it seems to be connecting, but now I am trying to send a message and its working but to the other user the message is not displayed unless I refresh the page. I was following a tutorial in youtube did everything like in the tutorial and I dont know why I am receiving this errors. If you can have a look I would appreciate it.
Errors I am receiving
DevTools failed to load SourceMap: Could not load content for http://127.0.0.1:8000/js/utf8.js.map: HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE
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">Harish</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>
Message Model
class Message extends Model
{
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $fillable = ['message'];
public function user()
{
return $this->belongsTo(User::class);
}
}
And I added this to User model
public function messages()
{
return $this->hasMany(Message::class);
}
ChatsController
use Illuminate\Http\Request;
use App\Message;
use App\Events\MessageSent;
class ChatsController extends Controller
{
public function _construct(){
$this->middleware('auth');
}
public function index()
{
return view('chats');
}
public function fetchMessages()
{
return Message::with('user')->get();
}
public function sendMessages(Request $request)
{
$message = auth()->user()->messages()->create([
'message' => $request->message
]);
broadcast(new MessageSent($message->load('user')))->toOthers();
return ['status' =>'success'];
}
}
MessageEvent event
App\Message; use App\User;
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');
}
}
Routes
Route::get('/chats','ChatsController#index')->middleware('auth');
Route::get('/messages','ChatsController#fetchMessages');
Route::post('/messages','ChatsController#sendMessages');
Broadcast::channel('chat', function ($user) {
return $user;
});
Chat view
#extends('layouts.app')
#section('content')
<div class="container">
<chats :user="{{ auth()->user()}}"></chats>
</div>
#endsection

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;
});

Laravel select models based on relationship

I am working on a library application and I want to create a function where the user can rent out a book to a customer. However, I want the books that are rented out right now to not show up in the select box when renting out another book.
I have looked up several articles about this, but couldn't really make up a solution so I would be happy about any help.
The idea is, that when a book has the attribute "maxreturndate" set it won't show up.
CheckedOutController:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\CheckedOut;
use App\Book;
use App\Reader;
class CheckedOutController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$checkedOuts = CheckedOut::with(['book', 'reader'])->get();
return view('checkedouts/index', compact('checkedOuts'));
}
/**
* Show the form for creating a new resource.
*
* #return \Illuminate\Http\Response
*/
public function create()
{
$books = Book::all();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
/**
* Store a newly created resource in storage.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$validatedData = $request->validate([
'book_id' => 'required',
'reader_id' => 'required',
'maxreturndate' => 'required|date',
'returndate' => 'nullable',
]);
$checkedOut = CheckedOut::create($validatedData);
return redirect('checkedouts')->with('success', 'Buch wurde erfolgreich verliehen!');
}
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function destroy($id)
{
//
}
}
index.blade.php
#extends('layout')
#section('title')
<title>Alle ausgeliehen Bücher</title>
#section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="uper">
#if(session()->get('success'))
<div class="alert alert-success">
{{ session()->get('success') }}
</div><br />
#endif
<table class="table table-hover">
<thead>
<tr>
<td>ID</td>
<td>Titel</td>
<td>Verliehen an</td>
<td>Verleihdatum</td>
<td>Fällig am</td>
<td>Zurückgebracht am</td>
<td colspan="2">Funktionen</td>
</tr>
</thead>
<tbody>
#foreach($checkedOuts as $checkedOut)
<tr>
<td>{{$checkedOut->id}}</td>
<td>{{$checkedOut->book->title}}</td>
<td>{{$checkedOut->reader->name}}</td>
<td>{{$checkedOut->created_at}}</td>
<td >{{$checkedOut->maxreturndate}}</td>
<td>{{$checkedOut->returndate}}</td>
<td></td>
<td>Bearbeiten</td>
<td>Anzeigen</td>
<td>
<form action="{{ route('checkedouts.destroy', $checkedOut->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Löschen</button>
</form>
</td>
</tr>
#endforeach
</tbody>
</table>
<div>
#endsection
Migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCheckedOutsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('checked_outs', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('book_id')->unsigned();
$table->foreign('book_id')->references('id')->on('books')->onDelete('cascade');
$table->bigInteger('reader_id')->unsigned();
$table->foreign('reader_id')->references('id')->on('readers')->onDelete('cascade');
$table->date('maxreturndate');
$table->date('returndate')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('checked_outs');
}
}
create.blade.php
#extends('layout')
#section('title')
<title>Buch verleihen</title>
#section('stylesheets')
<script src="http://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/js/select2.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.0.13/dist/css/select2.min.css" rel="stylesheet" />
#endsection
#section('content')
<style>
.uper {
margin-top: 40px;
}
</style>
<div class="card uper">
<div class="card-header">
Buch verleihen
</div>
<div class="card-body">
<form method="post" action="{{ route('checkedouts.store') }}">
<div class="form-group">
#csrf
<label for="book_id">Buch:</label>
<select name="book_id" class="form-control select2-single <!-- #error('book_id') is-invalid #enderror -->">
#foreach ($books as $book)
<option value="{{ $book->id }}">{{ $book->title }}</option>
#endforeach
</select>
#error('book_id')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="form-group">
<label for="reader_id">Verleihen an:</label>
<select name="reader_id" class="form-control select2-single <!-- #error('reader_id') is-invalid #enderror -->">
#foreach ($readers as $reader)
<option value="{{ $reader->id }}">{{ $reader->name }}</option>
#endforeach
</select>
#error('reader_id')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<div class="form-group">
<label for="maxreturndate">Zurückbringen bis:</label>
<input type="date" class="form-control" name="maxreturndate" />
#error('name')
<div class="alert alert-danger">{{ $message }}</div>
#enderror
</div>
<button type="submit" class="btn btn-primary">Verleihen</button>
</form>
</div>
</div>
<script type="text/javascript">
$(".select2-single").select2();
</script>
#endsection
The relationship between the 3 Models:
Book:
public function checkedOut(){
return $this->hasOne(CheckedOut::class);
}
Reader:
public function checkedOut()
{
return $this->belongsTo(CheckedOut::class);
}
CheckedOut:
public function book(){
return $this->belongsTo(Book::class);
}
public function reader(){
return $this->belongsTo(Reader::class);
}
My suggestion is to set up Books and Readers with a many-to-many relationship. Now, your models could look like this:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Pivot;
class Book extends Model
{
public function readers()
{
return $this
->belongsToMany(\App\Reader::class, 'checked_outs')
->using(\App\Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
class Reader extends Model
{
public function books()
{
return $this
->belongsToMany(\App\Book::class, 'checked_outs')
->using(\App\Checkout::class)
->withPivot(['returndate', 'maxreturndate']);
}
}
class Checkout extends Pivot
{
// this should be named `book_reader` but we override it here
$table = "checked_outs";
$dates = [
"maxreturndate",
"returndate",
];
}
I have created a pivot model which isn't necessary, but allows you to operate directly on the pivot table and cast the extra attributes to dates automatically. Whether this is useful is a matter of opinion. You should rename the checked_outs table to book_reader which is the naming convention that Laravel expects for a pivot table.
Getting the books that aren't checked out is simple enough to do as follows, using the doesntHave method to check for absence of a relationship.
public function create()
{
$books = Book::doesntHave("readers")->get();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}
And "checking out" a book could look like this:
public function store(Request $request)
{
$reader = Reader::find($request->reader_id);
$reader
->books()
->attach(
$request->book_id,
["returndate" => Carbon\Carbon::now()->addDays(7)]
);
}
when a book has the attribute "maxreturndate" set it won't show up
Since you did not specify in your migration, I am going to assume here that you have a maxreturndate nullable field in your books table, then you should be able to simply create a local scope when you want your list of "not rented" books.
Here's an example on creating a notRented scope:
// in your Book model define the local scope
public function scopeNotRented($query){
return $query->whereNotNull('maxreturndate');
}
// in the create method of your controller
public function create()
{
$books = Book::notRented()->get();
$readers = Reader::all();
return view('checkedouts/create', compact('books','readers'));
}

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?

Categories