Action CourseController#publish not defined error while that is defined - php

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.

Related

XHR 500 Internal Server Error when Posting Data using Vue in Laravel

I'm having problem in storing data in laravel, what I have done is created a request for using php artisan make:request and add fillable to my Model then added the process to the Vue component.
I also add v-model="form.name" and #click="submit" to the button for the form process.
In the end I am getting this 505 internal server error
I have also added <meta name="csrf-token" content="{{ csrf_token() }}"> to my app.blade.php
Is there a way to fix this and post my data successfuly?
Vue:
<script>
export default {
data(){
return{
form: {
job_name: null,
job_description: null,
vacants: 0
}
}
},
methods: {
submit(){
axios.post('/job_postings', this.form)
.then(function (response){
console.log(response);
})
.catch(function (error){
console.log(error);
});
}
}
}
</script>
Controller:
public function store(JobPostingRequest $jobPostingRequest, JobPosting $jobPosting)
{
$posting = $jobPosting::create($jobPostingRequest->all());
return response()->json(['message' => 'Job Posting has been successfully saved', 'data' => $posting]);
}
Requests:
public function authorize()
{
return true;
}
public function rules()
{
return [
'job_name' => 'required',
'job_description' => 'required',
'vacants' => 'required'
];
}
Model:
class JobPosting extends Model
{
use HasFactory;
protected $fillable = [
'job_name',
'job_description',
'vacants'
];
}
Routes/Web.php:
Route::resource('job_postings', JobPostingController::class);
You can get all values from your request with ->validated() method and create JobPosting from there.
use App\Models\JobPosting;
if($posting = JobPosting::create($jobPostingRequest->validated())){
return response()->json(['message' => 'Job Posting has been successfully saved', 'data' => $posting]);
}
return response()->json(['message' => 'Job posting failed.']);
Try this instead your store function.

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

Laravel error must be an instance of.. Chat application

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,

How Can I retrieve logged in user details in router [Laravel 5]?

I have created my router block like this:
Route::group(['middleware' => 'access.routeNeedsPermission:view-backend'], function() {
Route::group(['namespace' => 'Hospital'], function () {
Route::resource('hospital','HospitalController',
['except' => app('\App\Http\Controllers\Backend\Access\Hospital\HospitalController')->allowed_actions()]);
Route::post('hospital/locations', 'HospitalController#locations');
});
}
);
And I am writing the method like this
public function allowed_actions(){
$page_access = Pageaccess::where('page_id','hospital-management')->firstOrFail();
$roles = unserialize($page_access->role_id);
$views = unserialize($page_access->view);
$read = unserialize($page_access->read);
$write = unserialize($page_access->write);
$common_variable = Auth::check() ? Auth::user()->id : 0;
$actions = ['create'];
return $actions;
exit;
}
But the Auth::check() returns 0 and I cannot access anything in Auth::user(). Am I missing something?

Redirecting to the same route /user/{{username}} Laravel 4+

I am newbie who wants to make before filter which will check what I want and return redirect with error or success to the same /user/{{username}} profile.
So here is my filter before function
Route::filter('test', function()
{
$param = Request::segment(2);
if($para = 'username')
{
Session::flash('error', 'blabla!');
return Redirect::route('profile-public');
}
else
{
Session::flash('secces', 'xxx!');
return Redirect::route('profile-public');
}
});
here is my route
Route::group(array('before' => 'test'), function()
{
Route::get('/user/{username}', array('as' => 'profile-public','uses' => 'ProfileController#user'));
});
and my ProfileController public function
public function user($username)
{
$user = User::where('username', '=', $username);
if($user->count()){
$user = $user->first();
return View::make('profile.user')
->with('user', $user);
}
return App::abort(404);
}
So my problem is how to get those redirection work, I tried to search google etc and I could not find any answers. Sorry for the mess in the post it's my first post here and sorry for my english.
Example go to public profile of /user/admin --> filter check --> redirect to /user/admin with error or success.
You don't need a redirect here, just use this filter :
Route::filter('test', function()
{
$param = Request::segment(2);
if ($para = 'username')
{
Session::flash('error', 'blabla!');
}
else
{
Session::flash('secces', 'xxx!');
}
});

Categories