changing Unauthenticated message - laravel-5

when i ajax call a route with auth middleware i get (while not logged in)
{"message":"Unauthenticated."}
i want to change this to something like
{"stat" : 'er' , 'msg' : 'Unauthenticated' }
it seems to be somewhere deep inside vendor ... how can i have this message outside vendor and change it ?
i have to add some extra text to able to post the question so here it is apparently its too short : some text some text some text some text some text some text some text some text
some text some text some text

No not inside vendor you need to go to Handler Class in App\Exceptions
and in render function put this before return:
if ($request->expectsJson() && $exception instanceof AuthenticationException)
return response()->json(["stat" => 'er' , 'msg' => 'Unauthenticated' ], 401);

Related

Stop Laravel 9 from redirecting if AJAX validation fails

I have a Laravel 9 application and I am using Vue 3 and Filepond to create an image uploader experience.
<template>
<file-pond
max-files="1"
name="images"
server="/api/images"
accepted-file-types="image/jpeg, image/png, image/gif, image/webp"
:files="file"
/>
</template>
<script setup>
import vueFilePond from 'vue-filepond'
import 'filepond/dist/filepond.min.css'
const file = ''
</script>
It is very straightforward, it's basically sending the uploaded file to the server at the API endpoint to '/api/images' which is the API endpoint of my Laravel application and it works as expected.
However when I try to validate the request in the Laravel controller, I always get a 302 redirect reponse back in my Vue 3 application. This is how my validator looks like:
public function upload(Request $request)
{
$request->validate(
[
'image' => 'required|image|dimensions:min_width=1,max_height=1|max:4000',
]
);
if ($request->fails())
{
dd('Request failed. App should stop here.');
}
}
I deliberately set the "max_height" to 1 so the validatior fails, for testing. However the app doesn't go to "Request failed.." it just simply redirects (302) the user instead of returning the errors.
I am assuming that Laravel doesn't recognize this as an AJAX request for some reason. Because these request validations always work perfect if I do a simple Vue Axios form submit. I always get the errors in JSON format. But here it's not the case.
I have tried doing this and it was successfully giving me the "Validation fails message":
$validator = Validator::make($request->all(),
[
'image' => 'required|image|dimensions:min_width=1,min_height=1|max:4000',
]);
if ($validator->fails())
{
dd('Validator fails.');
}
However I would want to use a Form Request validation here (so I can put the contents of the validation logic into it's spearate file.)
What I want is: when the image validation fails -> Laravel should return a JSON response with all the errors. Just like when a form validation fails.
What am I missing though? Why isn't it working like it's supposed to in the first situation?
You are mostly just missing the header accept = application/json
That header is the only real difference between an ajax call and a normal request regardless of the route containing "api" or not.
Since the request expects a json response, the exception handler will not send a redirection, it will instead return a json of the error. albeit a validation exception error response or any exception error.

Inertia.JS reload props after post request

I am currently pretty confused why Inertia.js is not reloading or rerendering my page.
I have a form that could be filled, once submitting this will execute:
Inertia.post("/ban", ban);
This will redirect to a POST in the web.php of my Laravel.
That looks like this:
Route::post("/ban", [Speler::class, "ban"]);
This redirects to a class called "Speler", in there is a function called "ban".
Once done some SQL statements it will execute this return:
return Redirect::route("speler", [$steam])->with("success", "Ban doorgevoerd!");
This will go back to the web.php, and go to the route speler with the session data "success".
That redirect goes into the web.php:
Route::get("/speler/{steam}", [PageLoader::class, "speler"])->name("speler");
This one goes to the PageLoader controller, and execute the "speler" function.
But here it gets weird, this will return a Inertia::render of the same page the person was on, but would need to add another prop, or change the prop. (so i can show a popup with te text that it succeeded)
return Inertia::render("Panel/Speler",
["steamNaam" => $steamNaam, "discord" => $discord, "karakterAantal" => $karakterAantal, "karakters" => $karakters, "sancties" => $sanctiesReturn, "punten" => $aantalPunten, "steamid" => $steamid, "success" => $melding]
);
The "success" prop contains $melding that simply contains a string.
But for some reason it doesn't seem to re-render the page, the form stays filled, and the props are the same.
Does someone have a solution?
If you setup your form with the form helper, you can reset the form on a successful post like this:
form.post('/ban', {
preserveScroll: true,
onSuccess: () => form.reset(), // reset form if everything went OK
})
The success message, which you set with
return Redirect::route("speler", [$steam])->with("success", "Ban doorgevoerd!");
is usually taken care of by the Inertia middleware and made available as 'Shared data'. See this docs page on how to configure that. Shared data is rendered in $page.props variable. That is where you can find the Ban doorgevoerd! message. You can show these to the user as follows:
<div v-if="$page.props.flash.message" class="alert">
{{ $page.props.flash.message }}
</div>
Depending on your implementation, you would need to watch this property. See the FlashMessages component on the pingCRM demo app for an example implementation.

Laravel and Images validation

I have a little question about Laravel ...
I have a big form with which it is possible to send images.
I did a "PageStoreRequest" with my validation rules and everything works fine.
Depending on the length of the form, I would like that if an image is not valid, it is simply "deleted" (or "ignored") from the form and that the rest of the form is treated correctly ... So that the rest of the images are not to be sent again ...
I wonder if there is a method that would check a single field?
(like my Image Field)
And if it is not valid, delete it?
(knowing that the other fields must also pass to the Validator)
Thanks for your ideas :)
You can validate image field.
$request->validate([
'image' => 'mimes:jpeg,jpg,png'
]);
And then field is validated;
if ($request->hasFile('image') && $request->file('image')->isValid()) {
// Make something
}

How to repopulate form after form validation and also keep the URI?

I have a problem repopulating my form after validation fails. Problem is my url contains an additional uri which I access by clicking a link. This is what it looks like:
http://www.example.com/admin/trivia/add/5
At first trouble was that the segment 4 of the uri completely disappeared, so even though the validation errors showed and the form was repopulated, I lost my added uri.
Then I found in another question that the solution was to set form open like this:
echo form_open(current_url());
Problem is now it isn't showing any validation errors and the form is not repopulated. Is there a way to achieve this?
This is what my controller looks like:
function add()
{
$data = array('id' => $this->uri->segment(4));
if($_POST)
{
$this->_processForm();
}
$this->load->view('admin/trivia_form', $data);
}
And inside _processForm() I got all the validation rules, error message and redirecting in case success.
[edit] Here is my _processForm() :
function _processForm()
{
$this->load->library('form_validation');
//validation rules go here
//validation error messages
$this->form_validation->set_rules($rules);
$this->form_validation->set_error_delimiters('<div style="color:red">', '</div>');
if ($this->form_validation->run())
{
//get input from form and assign it to array
//save data in DB with model
if($this->madmin->save_trivia($fields))
{
//if save is correct, then redirect
}
else
{
//if not show errors, no redirecting.
}
}//end if validation
}
To keep the same url, you can do all things in a same controller function.
In your controller
function add($id)
{
if($this->input->server('REQUEST_METHOD') === 'POST')// form submitted
{
// do form action code
// redirect if success
}
// do your actual stuff to load. you may get validation error in view file as usual if validation failed
}
to repopulate the form fields you are going to need to reset the field values when submitting it as exampled here and to meke it open the same page you can use redirect() function as bellow:
redirect('trivia/add/5','refresh');
i don't know what you are trying to do, but try this to repopulate the form with the values user entered
<?php
echo form_input('myfield',set_value('myfield'),'placeholder="xyz"');
?>

codeigniter with MVC pattern

I am working on ci and when i am going to delete my data then i want to generate a confirm message box on click delete link and my code is this.
view.php
id);?>">Delete
controller.php
function delete($id)
{
$this->include_user->delete($id);
redirect(site_url('admin_controller/fetch'));
}
Model.php
function delete($id)
{
$this->db->delete("user",array('id' => $id));
}
If you want to show confirmation message that either user really want to delete, then you can use jquery confirm box plugin and when click on delete anchor then on delete show the confirm box.
e.g: in js code
jConfirm('Do you really want to delete?', 'Delete Confirmation', function(r) {
if (r == true) {
}
}
In my case I am using jquery confirm box.
And in case if you want to show success message then you can send back a flag when record is deleted to controller, then checking the flag, if successfully record is deleted then pas success message to your message controller or wise failure message.

Resources