Laravel error must be an instance of.. Chat application - php

I have problem. I use event: https://github.com/musonza/chat/blob/master/src/Messages/MessageWasSent.php
In my controller:
public function sendMessage(Conversation $conversation, Request $request) {
$v = Validator::make($request->all(), [
'message' => 'required|string|max:4000',
]);
$user = User::find(Auth::id());
$conv = Chat::conversation($conversation->id);
Chat::message($request->message)
->from($user)
->to($conv)
->send();
event(new MessageWasSent($request->message));
}
I get error:
Type error: Argument 1 passed to Musonza\Chat\Messages\MessageWasSent::__construct() must be an instance of Musonza\Chat\Messages\Message, string given..
In my app.js:
send(){
if(this.message.length != 0 && this.message.length <= 4000) {
this.chat.message.push(this.message);
this.chat.user.push(this.user);
this.chat.time.push(this.getTime());
axios.post('/sendMessage/' + this.convId, {
message: this.message,
})
.then(response => {
console.log(response);
this.message = '';
})
.catch(error => {
console.log(error);
});
}
}
Routes:
Route::post('sendMessage/{conversation}', 'Chat\ChatController#sendMessage')->name('chatsend');
How I can fix this error?

$message = Chat::message($request->message)
->from($user)
->to($conv)
->send();
event(new MessageWasSent($message));
As the error says the event constructor requires an instance of Musonza\Chat\Messages\Message rather than a string,

Related

validate and saving an array of objects laravel 6, vue, axios

vue function:
sendData() {
this.isLoading = true;
const postData = {
data: this.items,
};
var self = this;
axios.post(this.postUrl, postData).then(function (response) {
console.log(response.data);
self.isLoading = false;
});
this.items = [];
},
Laravel controller:
public function store(request $request)
{
foreach ($request->data as $data) {
$serie = [];
$serie = ['imei' => $data['serie']];
$imei = new Imei([
'imei' => $data['serie'],
'status_id' => 1,
'sucursal_id' => $data['sucursal'],
'equipo_id' => $data['equipo']
]);
$validator = Validator::make($serie, [
'imei' => 'unique:imeis,imei|digits:15',
]);
if ($validator->fails()) {
// Here I need to build the response of every imei with its validation error
} else {
$imei->save();
}
}
return >Here I want to return the errors back to vue
}
my vue app sends to laravel trough axios an array of objects that looks like this [{imei:xxxx,sucursal_id...},{imei:xxxx,sucursal_id...}] I need to validate imei is unique and save it, and if error return errors in the same way [{imei:xxxx,errorMsg: 'already exist in DB'}]. but I can't find the proper way to do it.
Basically you want to customize your errorbag right ? try this one out. Add this inside your fail condition. Let me know if it works.
$err = [{imei:xxxx,errorMsg: 'already exist in DB'}];
foreach ($validator->errors()->toArray() as $error) {
foreach($error as $sub_error) {
array_push($err, $sub_error);
}
}
return ['errors'=>$err];

How can I update a post in laravel using formData?

so I am working in a social network, and I want once a post is done to be able to edit it, but I am having the error:
message: "This action is unauthorized."
is seems something simple to me, I get the info in the component send it throuhg an axios call that goes through a route I have defined and it just goes to the controller and from there to the service, but I must be missing something which I do not know what it is. Any hint is much appreciated as I am getting a bit mad...
this would be the function in the component:
editPost() {
let formData = new FormData();
let headers = { headers: { "Content-Type": "multipart/form-data" } };
let updatedPost = this.post_to_update;
formData.append("post", updatedPost.description);
formData.append("file", this.file);
formData.append("video_link", updatedPost.video_link);
axios
.post("/posts/update/" + updatedPost.id, formData, headers)
.then(response => {
updatedPost.attach_file = response.data.attach_file;
updatedPost.id = response.data.id;
serverBus.$emit("post_edited", updatedPost);
});
this.file = "";
this.post_to_update = {
id: "",
index: null,
description: "",
attach_file: "",
video_link: "",
name: this.profile_info.name,
surname_1: this.profile_info.surname_1,
surname_2: this.profile_info.surname_2,
nick: this.profile_info.nick,
picture: this.profile_info.picture,
id_rol: this.profile_info.id_rol,
time_ago: "0 minutes",
code: this.profile_info.code
};
$("#EditModal").modal("hide");
},
this is the web.php:
########################################################################################################################
# Post Routes
########################################################################################################################
Route::post('/posts/recommend', 'PostController#recommend')
->name('recommendPost');
Route::post('/posts/update/{id}', 'PostController#update');
Route::post('/posts/report', 'PostController#report')
->name('reportPost');
Route::get('/posts/{post}/comments', 'PostController#retrieveComments')
->where('post', '[0-9]+')
->name('commentsByPost');
Route::resource('/posts', 'PostController')
->only(['index', 'store', 'update', 'destroy']);
Route::get('/reportedPosts', 'PostController#reportedPosts');
The controller:
public function update(StorePostRequest $request, $post_id)
{
return $this->postService->updatePost($request, $post_id);
}
and the service:
public function updatePost(StorePostRequest $request, $post_id)
{
$post_to_update = Post::where('id', $post_id)->first();
$post_to_update->description = $request->post;
$post_to_update->attach_file = $request->file ? $filename = sha1(time()) : null;
$post_to_update->file_name = $request->file ? $request->file->getClientOriginalName() : null;
$post_to_update->file_type = $request->file ? $request->file->getClientOriginalExtension() : null;
$post_to_update->save();
if ($request->file) {
Storage::disk('s3')->putFileAs('storage/user_uploads/post_files/' . $post_to_update->id, $request->file, $filename, 'public');
Storage::disk('local')->putFileAs('public/user_uploads/post_files/' . $post_to_update->id, $request->file, $filename, 'public');
}
return $post_to_update;
}
I think StorePostRequest class cause the block of user authorization.
Try add following lines at StorePostRequest to pass the authorization check.
public function authorize()
{
return true; //Default false;
}

How to check if user is entering correct information for a login?

I'm trying to make a login page where if the username or password is wrong that I tell the person trying to login that it's the wrong username or password.
This is my login function in the LoginController, I tried adding an if statemente with a Auth::attempt but I get errors because I'm sending an object instead of an array, is there a way to validate and check at the same time. The examples I've seen don't validate at all?
protected function validateLogin(Request $request)
{
$request->validate([
$this->username() => 'required|string',
'password' => 'required|string',
]);
if(Auth::attempt($request)) {
return redirect()->intended('dashboard');
}
}
In my Login.vue I have the rules setup like this:
rules: {
username: {required: true, message: 'Required', trigger: 'blur',},
password: {required: true, message: 'Required', trigger: 'blur'},
},
How would I do both?
To show the errors this is my code.
<el-row v-if="errors && Object.keys(errors).length > 0" class="mb-2">
<el-col :span="24">
<el-alert
v-for="(value, key, index) in errors"
v-bind:key="index"
:title="value[0]"
type="error"
center
:closable="false"
effect="dark">
</el-alert>
</el-col>
</el-row>
And in my script
export default {
props: {
errors: Object,
}
}
Ideally I want to send a custom message through since my page is in another language. Maybe there is a way in the submit method in the vue?
submit() {
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post('/login', {
scard: this.form.scard,
password: this.form.password,
}).then(() => this.loading = false);
} else {
return false;
}
});
},
Your code is really close! The problem is that $request is, indeed, an object. If, however, you use $request->all(), you'll have an array with all of the data in the current request:
protected function validateLogin(Request $request)
{
$request->validate([
'username' => 'required|string',
'password' => 'required|string',
]);
if(Auth::attempt($request->all())) {
return redirect()->intended('dashboard');
}
return response()->json(['error' => 'Oops! Your login failed. Verify your username & password and try again.'], 401);
}
UPDATE
Seeing your frontend code is helpful. Here's how to handle the failed login:
submit() {
this.$refs.form.validate((valid) => {
if (valid) {
this.loading = true;
this.$inertia.post('/login', {
scard: this.form.scard,
password: this.form.password,
})
.then(() => this.loading = false)
.catch(() => {
this.errors = {
'credentials' => ['Your login failed! Please verify your credentials and try again.']
};
});
} else {
return false;
}
});
},

Vuejs display Laravel errors in flash component

In controller I have a method, where I validate request. I have and custom error, see please code:
public function createComment(Request $request) {
$request->validate(['body' => 'string|min:10', 'type' => 'integer']);
if($this->lastComment(Auth::user()->id)) {
return response()->json(['errors' => 'Please try after 24 hours..'], 422);
} else {
$comment = Comment::create($request->all());
return $comment;
}
}
In vue I have axios:
axios.post('/createReview', {
body: this.body,
user_id: this.user_id,
type: this.type,
}).then(response => {
this.$emit('created', response.data);
}).catch(error => {
this.isLoading = false;
this.flash(error.response.data, 'error');
});
How I can correctly send these errors on component flash? When I get error on component I get [Object object]. I use this flash package: https://www.npmjs.com/package/vue-flash-message
That component will only render one message at a time and you are passing it an object.
this.flash(error.response.data.errors, 'error');

Action CourseController#publish not defined error while that is defined

I defined a custom function to a resource controller like this :
public function publish (Request $request, $post_id = NULL)
{
if (!is_null($post_id)) {
$result = $this->update($request, $post_id);
} else {
$result = $this->store($request);
}
if ($result['success']) {
return ['success' => true, 'msg' => $result['msg']];
} else {
return ['success' => false, 'msg' => $result['msg']];
}
}
And in a blade template I want to link to it like so:
$('#publishBtn').click(function () {
$.post('{{action('CourseController#publish')}}', $('#createCourseForm').serialize() + '&post_status=published', function (data) {
data.success ? location.href = '/admin/course' : showMsg(data.msg, 'danger');
});
});
but after opening page error below is shown while really that method exists :
Action App\Http\Controllers\CourseController#publish not defined.
(View: D:\wamp\www\lms\resources\views\admin\pages\course\course-create.blade.php)
Just before CourseController Resource route add a route for publish method
Route::post('publish', [
'uses' => 'CourseController#publish',
'as' => 'publish'
]);
....
Route::resource('course', 'CourseController');
Then in your template
$('#publishBtn').click(function () {
$.post('{{route('publish')}}', $('#createCourseForm').serialize() + '&post_status=published', function (data) {
data.success ? location.href = '/admin/course' : showMsg(data.msg, 'danger');
});
});
You need to create a route for that as well.

Categories