POST http://127.0.0.1:8000/broadcasting/auth 403 (Forbidden) ,How i can resolve this error - javascript

app.js :
import './bootstrap';
Echo.private('App.Models.Company.' + companyId)
.notification((notification) => {
console.log(notification);
});
channel.php :
Broadcast::channel('App.Models.Company.{id}', function ($company, $id) {
return (int) $company->id === (int) $id;
});
blade page :
<script>
let companyId = '{{ Auth::id() }}';
</script>
#vite(['resources/js/app.js'])

This problem has been solved, because I am using guards in my system, it does not recognize any guards other than the default guard
I defined the guard in the channel route such as :
Broadcast::channel('App.Models.Company.{id}', function ($company, $id) {
return (int) $company->id === (int) $id;
},['guards'=>['company']]);

Related

Parameter returning undefine and php select by id returning null

someone should pls help me out on this.
I need to select and update data by id from SQL database but i am not getting the appropriate result.
The php file is returning null. When i checked from my developer tool, i realised that the params code, this.props.match?.params.id is showing undefined. I guess it is not able to send the id parameter to the "$id" in the edit.php code.
Someone should please help me look into the codes. I want to be able to select and edit based on specific id from the database.
Thank you
Here is my code;
edit.php
<?php
require 'connect.php';
include_once("Core.php");
$id = $_GET['id'];
//Get by id
$sql = "SELECT * FROM `visitors` WHERE `id` ='{$id}' ";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_assoc($result);
// print_r($row)
echo $json = json_encode($row);
exit;
The update code is bellow
update.php
<?php
include_once("Core.php");
require 'connect.php';
//Get the posted data
$postdata = file_get_contents("php://input");
if(isset($postdata) && !empty($postdata))
{
// Extract the data
$request = json_decode($postdata);
print_r($request);
// Sanitize
$id = $_GET['id'];
$lastName= $request -> lastName;
// Update
$sql = "UPDATE `visitors` SET `lastName` = '$lastName' WHERE `id` = '{$id}' LIMIT 1";
if(mysqli_query($con, $sql))
{
http_response_code(201);
}
else
{
http_response_code(422);
}
}
For the edit code
edit.js
import React, { Component } from "react";
import "./Edit.css";
import "react-datepicker/dist/react-datepicker.css";
import Axios from "axios";
export default class Edit extends Component {
constructor(props) {
super(props);
this.onChangeLastName = this.onChangeLastName.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
firstName: "",
lastName: "",
};
}
componentDidMount() {
Axios.get(
"http://localhost/testing/edit.php?id=" + this.props.match?.params.id
)
.then((response) => {
this.setState({
firstName: response.data.firstName,
lastName: response.data.lastName,
});
})
.catch(function (error) {
console.log(error);
});
}
// }
onChangeLastName(e) {
this.setState({
lastName: e.target.value,
});
}
onSubmit(e) {
e.preventDefault();
const obj = {
lastName: this.state.lastName,
};
Axios.post(
"http://localhost/testing/update.php?id=" + this.props.match?.params.id,
obj
).then((res) => console.log(res.data));
this.setState({
lastName: "",
});
}
render() {
return (
<div className="edit">
<form onSubmit={this.onSubmit}>
<div className="edit__text">Date & Time Out:</div>
<label>
Last Name:
<input
name="last"
type="text"
value={this.state.lastName}
onChange={this.onChangeLastName}
/>
</label>
<button>Submit</button>
</form>
</div>
);
}
}
this.props.match.id
This code is no longer valid in react,
It has been replaced by useParams hook
...
const id = useParams();
componentDidMount() {
Axios.get(
"http://localhost/testing/edit.php?id=" + id;
)
...
This should work, and you need to import the hook too.

Multilevel Login in php&mysqli with codeigniter

i have 3 user with different access page, i have try create login form standart with no limit access. now i'm confussed where i must place new code multiple login.
( i use php&mysqli database with codeigniter framework )
Please help me,
thk u before
database image
code image
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Welcome extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('m_rental');
}
public function index(){
$this->load->view('login');
}
function login(){
$username = $this->input->post('username');
$password = $this->input->post('password');
$this->form_validation->set_rules('username','Username','trim|required');
$this->form_validation->set_rules('password','Password','trim|required');
if($this->form_validation->run() != false){
$where = array(
'admin_username' => $username,
'admin_password' => $password,
);
$data = $this->m_rental->edit_data($where,'admin');
$d = $this->m_rental->edit_data($where,'admin')->row();
$cek = $data->num_rows();
if($cek > 0){
$session = array(
'id'=> $d->admin_id,
'nama'=> $d->admin_nama,
'status' => 'login'
);
$this->session->set_userdata($session);
redirect(base_url().'admin');
}else{
redirect(base_url().'welcome?pesan=gagal');
}
}else{
$this->load->view('login');
}
}
}
Try to add level to your session and read it later on dashboard page:
$session = array(
'id'=> $d->admin_id,
'nama'=> $d->admin_nama,
'status' => 'login',
'level' => $d->level
);
And on dashboard page
if($this->session->userdata["level"] === "superadmin")
{
// Code if level = superadmin
}

return back laravel function not working on server

I have problem with my laravel project, when validator false return back function run well on localhost, but on the server it return to root url , somebody may help me figure it out?
My controller like this:
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('employees.form_edit', ['user' => User::find($id)]);
else {
$rules = [
'name' => 'required',
'full_name' => 'required',
'id_number' => 'required',
'date_of_birth' => 'required',
'avatar' => 'mimes:jpeg,jpg,png,gif|max:2048'
];
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
return redirect()->back()
->withErrors($validator)
;
}
$user = User::find($id);
$user->name = $request->name;
$user->position = $request->position;
$user->full_name = $request->full_name;
$user->id_number = $request->id_number;
$user->date_of_birth = $request->date_of_birth;
$user->status = $request->status;
$img_current = 'upload/avatar/' .$request->input('img_current');
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$user->image = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
echo "no file";
}
$user->save();
return redirect('listEmployees');
}
}
My route:
Route::group(['prefix' => 'listEmployees'], function () {
Route::match(['get', 'post'], 'update/{id}', 'EmployeesController#update');
});
Try this code I have
CONTROLLER
public function update(Request $request, $id)
{
if ($request->isMethod('get'))
return view('employees.form_edit', ['user' => User::find($id)]);
else {
$_data = $request->validate([
'name' => ['required'].
'full_name' => ['required'],
'id_number' => ['required'],
'date_of_birth' => ['required'],
'avatar' => ['mimes:jpeg,jpg,png,gif', 'max:2048'],
'position' => ['nullable'],
'status' => ['nullable']
])
$img_current = 'upload/avatar/' .$request->input('img_current');
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$data['image'] = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
echo "no file";
}
$user = User::find($id);
$user->update($_data);
return redirect('listEmployees');
}
}
VIEW
#if ($errors->any())
<div class="alert alert-warning">
#foreach ($errors->all() as $error)
{{$error}} <br>
#endforeach
</div>
#endif
Before you go further with this problem you need to clean up your code a little bit.
First of all you dont need to check the request->method if you have already made the route "Route::update" (laravel takes care of it).
Second: use laravel form-request and make your controller much more cleaner and readable(php artisan make:request ModelNameRequest)
Third: you dont need to redirect user to manually if you want to redirect to back(), again laravel takes care of it, it will redirect back() if the validator fails with and array of $errors.
any ways this is the code that may work:
public function update(Request $request, $id)
{
$rules = [
'name' => 'required',
'full_name' => 'required',
'id_number' => 'required',
'date_of_birth' => 'required',
'avatar' => 'mimes:jpeg,jpg,png,gif|max:2048'
];
// if the validation failes, laravel redirects back with a collection of $errors
$this->validate($request->all(), $rules);
// you probably want to use User::create($request->only('input1', 'input2', ...);
$user = User::find($id);
$user->name = $request->name;
$user->position = $request->position;
$user->full_name = $request->full_name;
$user->id_number = $request->id_number;
$user->date_of_birth = $request->date_of_birth;
$user->status = $request->status;
$img_current = 'upload/avatar/' .$request->input('img_current');
// use a good package for storing your files like Mediable to make it easy.
if (!empty($request->file('avatar'))) {
$file_name = $request->file('avatar')->getClientOriginalName();
$user->image = $file_name;
$request->file('avatar')->move('upload/avatar/',$file_name);
if (File::exists($img_current)) {
File::delete($img_current);
}
}else{
//TODO: you should not echo some thing here, you should use session()->flash()
session()->flash('message', 'You did not select any file.');
}
$user->save();
return redirect('listEmployees');
}
i solve this problem by change redirect function to
return redirect()->action(
'EmployeesController#update', ['id' => $id]
)
thank all guy

Trying to implement a comments system with laravel

Trying to implement a comments system using pusher on my laravel project. Everything seems to be in order, however every post request which is meant to send the input data to the database returns with error 500.
Used F12 on firefox to monitor what gets sent to /tip/select, it seems that it passes the text of the comment just fine, so it could be the issue with the controller.
Routes
Route::get('/tip/select','TipController#select');
Route::post('/tip/select', 'TipController#addComment');
Comment model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Zttp\Zttp;
use App\model\User;
use App\Tip;
class Comment extends Model
{
protected $guarded = [];
protected $table='comments';
//protected $fillable=['tip_id','user_id','body'];
public static function moderate($comment)
{
$response = Zttp::withoutVerifying()->post("https://commentator.now.sh", [
'comment' => $comment,
'limit' => -3,
])->json();
if ($response['commentate']) {
abort(400, "Comment not allowed");
}
}
public function tip(){
return $this->belongsTo('App\Tip');
}
public function user(){
return $this->belongsTo('App\model\User');
}
}
Controller
use Pusher\Laravel\Facades\Pusher;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Input;
use DB;
use Image;
use App\Tip;
use App\model\User;
use App\Subcategories;
use App\Category;
use App\City;
use App\Comment;
use App\CityAreas;
//use App\Http\Requests\TipFormRequest;
class TipController extends Controller
{
public function select(){
//$db=DB::table('tips')->orderBy('created_at','desc');
$data=Tip::get();
$url = Storage::disk('s3');
//$data=Tip::paginate(10);
//$data=$db->get();
// dd($data);
$comments = Comment::orderBy('id')->get();
return view('tip', compact('data', 'url','comments'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function create(){
$categories=Category::all();
$cities=City::all();
return view('tip.create',compact('categories','cities'));
}
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function store(Request $request, City $city, Category $category){
$this->validate($request, [
'image' => 'image|nullable|max:1999']);
$tipsnew = new Tip;
$tipsnew->title = $request->title;
$tipsnew->description = $request->description;
$tipsnew->category_id = $request->category;
$tipsnew->city_id = $request->city;
$tipsnew->user_id = auth()->id();
$tipsnew->url = $request->url;
if ($request->hasFile('image')) {
try{
$file = $request->file('image');
$name = time() . '.' . $file->getClientOriginalExtension();
$img = \Image::make($file->getRealPath());
$img->fit(1080);
$img->stream();
Storage::disk('s3')->put('tip'.'/'.$name, $img->__toString());
$tipsnew->image = 'tip'.'/'.$name;
}
catch (\Exception $e)
{
$response = [
'information' => 'Error. Something went wrong. Please try again',
];
$statusCode = 400;
return response()->json($response, $statusCode);
}
}
$tipsnew->save();
return redirect ('tip/create')->with('status','your tip is created');
}
public function edit($id){
$tip=Tip::whereId($id)->firstOrFail();
$categories=Category::all();
$selectedCategories=$tip->categories->lists('id')->toArray();
return view('tip.edit',compact('tip','categories','selectedCategories'));
}
public function search(Request $request, City $city, Category $category, User $user){
$q = $request->get('q');
if ($q != ""){
$tips = Tip::where('title','LIKE','%'.$q.'%')
->orWhere('description','LIKE','%'.$q.'%')
->orWhereHas('user', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('city', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->orWhereHas('category', function($id) use($q){
return $id->where('name', 'LIKE','%'.$q.'%');
})
->get();
if(count($tips) > 0)
return view('tip.search', ['tips' => $tips]);
}
}
public function addComment(Request $request)
{
$data = $request;
Comment::moderate($data['text']);
$comment = Comment::create($data);
Pusher::trigger('comments', 'new-comment', $comment, request()->header('X-Socket-Id'));
//add creation of new comment to DB
$commentnew = new Comment;
$commentnew->user_id = Auth::user()->id();
//$commentnew->tip_id= $request->post(['tip_id']);
$commentnew->body = $request->text;
$commentnew->save();
return $comment;
}
}
Snippet of the blade
<h3>Comments</h3>
<form onsubmit="addComment(event);">
<input type="text" placeholder="Add a comment" name="text" id="text" required>
<input type="hidden" name="tip_id" id="tip_id" value="{{$val->tip_id}}">
<input type="hidden" name="username" id="username" value="{{Auth::user()->name}}">
<button id="addCommentBtn">Comment</button>
</form>
<div class="alert" id="alert" style="display: none;"></div>
<br>
<div id="comments">
#foreach($comments as $comment)
<div>
<small>{{ $comment->username }}</small>
<br>
{{ $comment->text }}
</div>
#endforeach
</div>
<!--jQuery script used to be here -->
<script>
function displayComment(data) {
let $comment = $('<div>').text(data['text']).prepend($('<small>').html(data['username'] + "<br>"));
$('#comments').prepend($comment);
}
function addComment(event) {
function showAlert(message) {
let $alert = $('#alert');
$alert.text(message).show();
setTimeout(() => $alert.hide(), 4000);
}
event.preventDefault();
$('#addCommentBtn').attr('disabled', 'disabled');
var data = {
text: $('#text').val(),
username: $('#username').val(),
tipid: $('#tip_id').val(),
};
fetch('/tip/select', {
body: JSON.stringify(data),
credentials: 'same-origin',
headers: {
'content-type': 'application/json',
'x-csrf-token': $('meta[name="csrf-token"]').attr('content'),
'x-socket-id': window.socketId
},
method: 'POST',
mode: 'cors',
}).then(response => {
$('#addCommentBtn').removeAttr('disabled');
displayComment(data);
showAlert('Comment posted!');
})
}
</script>

Sending data from Angular to Laravel

Ok, so I'm stuck again. I'm doing an todo-list application, using Laravel and Angular. I can fetch data from the database via the Laravel- and Angular controllers but when I try do write data, I can't get it working.
So I have a form, whing uses ng-submit to post the data. When I - in the Angular controller - log the data to the console, the data from the form is correct. But when I try to pass it on to the Laravel Controller, I get stuck.
I can't find out whats wrong and browing the web for answers hasn't helped me.
Laravel routes:
<?php
Route::get('/', function () {
return view('index');
});
Route::get('/notes', 'NoteController#index');
Route::delete('/notes', 'NoteController#destroy');
Route::post('/notes', 'NoteController#store');
//Route::post('/notes', 'NoteController#update');
Route::get('/projects', 'ProjectController#index');
Route::get('/users', 'UserController#index');
Route::group(['middleware' => ['web']], function () {
//
});
?>
Laravel controllers:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Note;
use App\User;
use App\Project;
use Input;
use Response;
use Redirect;
class NoteController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$notes = Note::where('removed', 0)->get()->toArray();
$response = [];
foreach ($notes as $note) {
$user = User::find($note['user_id']);
$project = Project::find($note['project_id']);
$this_row = array(
'id' => $note['id'],
'user' => $user['uname'],
'project' => $project['pname'],
'content' => $note['content'],
'completed' => $note['completed'],
'removed' => $note['removed'],
'created' => $note['time_created'],
'deadline' => $note['time_deadline']
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
public function store()
{
$note = Input::json()->get()->toArray();
var_dump($note);
/*
$note->user_id = $note['user'];
$note->project_id = $note['project'];
$note->content = $note['content'];
$note->time_deadline = $note['deadline'];
$note->save();*/
}
}
class ProjectController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$projects = Project::orderBy('pname', 'asc')->get()->toArray();
$response = [];
foreach ($projects as $project) {
$this_row = array(
'id' => $project['id'],
'name' => $project['pname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
class UserController extends Controller
{
public function index()
{
try {
$statusCode = 200;
$users = User::orderBy('uname', 'asc')->get()->toArray();
$response = [];
foreach ($users as $user) {
$this_row = array(
'id' => $user['id'],
'name' => $user['uname'],
);
$response[] = $this_row;
}
} catch (Exception $e) {
$statusCode = 400;
} finally {
return Response::json($response, $statusCode);
}
}
}
Angular controller:
angular.module('todoApp', []).controller('MainController', function($scope, $http) {
var thisApp = this;
$http({method : 'GET', url : 'http://localhost:8000/notes'})
.then (function(response) {
thisApp.todos = response.data;
}, function() {
alert("Error getting todo notes");
});
$http({method : 'GET',url : 'http://localhost:8000/users'})
.then(function(response) {
thisApp.users = response.data;
}, function() {
alert("Error getting users");
});
$http({method : 'GET', url : 'http://localhost:8000/projects'})
.then(function(response) {
thisApp.projects = response.data;
}, function() {
alert("Error getting projects");
});
thisApp.addTodo = function(note) {
console.log($scope.note);
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.note),
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
});
};
});
HTML:
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<script src="/js/MainController.js"></script>
</head>
<body ng-controller="MainController as myControl">
<h2>Todo</h2>
<div>
<table>
<tr>
<th>Note:</th>
<th>Author:</th>
<th>Project:</th>
<th>Created:</th>
<th>Deadline:</th>
</tr>
<tr ng-repeat="todo in myControl.todos">
<td> {{ todo.content }} </td>
<td> {{ todo.user }} </td>
<td> {{ todo.project }} </td>
<td> {{ todo.created }} </td>
<td> {{ todo.deadline }} </td>
<td><button>Update</button></td>
<td><button>Delete</button></td>
</tr>
</table>
</div>
<h2>Add new:</h2>
<div>
<form ng-submit="myControl.addTodo()">
User:<br/>
<select ng-model="note.user">
<option ng-repeat="user in myControl.users" value="{{ user.id }}">{{ user.name }}</option>
</select><br/>
Project:<br/>
<select ng-model="note.project">
<option ng-repeat="project in myControl.projects" value="{{ project.id }}">{{ project.name }}</option>
</select><br/>
Note:<br/>
<textarea rows="5" cols="30" ng-model="note.content"></textarea><br/>
Deadline (format YYYY-MM-DD HH:MM):<br/>
<input type="text" ng-model="note.deadline" /><br/>
<input type="submit" value="Add" />
</form>
</div>
</body>
</html>
The result can be seen in this image: http://imgur.com/60hIzSb
I have no idea what I'm doing wrong. I guess my problem is in the Angular controller in the addTodo function, but I really don't know. Any suggestions?
I also wonder if anyone knows if I have to do anything else than change method : 'POST' to method : 'PUT' if I want to use the PUT method for creating new notes?
I feel like it has something to do with this:
$note = Input::json()->get()->toArray();
var_dump($note);
In angular you are sending form encoded data not json. And I believe Laravel automatically decodes received json anyway, so this should work:
$note = Input::all();
var_dump($note);
If it is the CSRF token then inject the CSRF TOKEN to your view
angular.module("todoApp").constant("CSRF_TOKEN", '{!! csrf_token() !!}');
and to your addTodo function in the headers pass the token....
thisApp.addTodo = function(note) {
console.log($scope.note);
$http({
method : 'POST',
url : 'http://localhost:8000/notes',
data : $.param($scope.note),
headers : {'Content-Type': 'application/x-www-form-urlencoded',
'x-csrf-token': CSRF_TOKEN}
});

Categories

Resources