Asked  9 Months ago    Answers:  5   Viewed   344 times

I am working in Laravel 5.4 and I have a slightly specific validation rules need but I think this should be easily doable without having to extend the class. Just not sure how to make this work..

What I would like to do is to make the 'music_instrument' form field mandatory if program array contains 'Music'.

I found this thread How to set require if value is chosen in another multiple choice field in validation of laravel? but it is not a solution (because it never got resolved in the first place) and the reason it doesn't work is because the submitted array indexes aren't constant (not selected check boxes aren't considered in indexing the submission result...)

My case looks like this:

<form action="" method="post">
    <fieldset>

        <input name="program[]" value="Anthropology" type="checkbox">Anthropology
        <input name="program[]" value="Biology"      type="checkbox">Biology
        <input name="program[]" value="Chemistry"    type="checkbox">Chemistry
        <input name="program[]" value="Music"        type="checkbox">Music
        <input name="program[]" value="Philosophy"   type="checkbox">Philosophy
        <input name="program[]" value="Zombies"      type="checkbox">Zombies

        <input name="music_instrument" type="text" value"">

        <button type="submit">Submit</button>

    </fieldset>
</form>

If I select some of the options from the list of check boxes I can potentially have this result in my $request values

[program] => Array
    (
        [0] => Anthropology
        [1] => Biology
        [2] => Music
        [3] => Philosophy
    )

[music_instrument] => 'Guitar'

Looking at validation rules here: https://laravel.com/docs/5.4/validation#available-validation-rules I think something like his should work but i am literally getting nothing:

  $validator = Validator::make($request->all(),[
        'program'           => 'required',
        'music_instrument'  => 'required_if:program,in:Music'
  ]);

I was hoping this would work too but no luck:

'music_instrument'  => 'required_if:program,in_array:Music',

Thoughts? Suggestions?

Thank you!

 Answers

27

Haven't tried that, but in general array fields you usually write like this: program.*, so maybe something like this will work:

  $validator = Validator::make($request->all(),[
        'program'           => 'required',
        'music_instrument'  => 'required_if:program.*,in:Music'
  ]);

If it won't work, obviously you can do it also in the other way for example like this:

$rules = ['program' => 'required'];

if (in_array('Music', $request->input('program', []))) {
    $rules['music_instrument'] = 'required';
}

$validator = Validator::make($request->all(), $rules);
Wednesday, March 31, 2021
 
AlterPHP
answered 9 Months ago
35

A general solution would be:

function deep_in_array($needle, $haystack) {
    if(in_array($needle, $haystack)) {
        return true;
    }
    foreach($haystack as $element) {
        if(is_array($element) && deep_in_array($needle, $element))
            return true;
    }
    return false;
}

The reason why I chose to use in_array and a loop is: Before I examine deeper levels of the array structure, I make sure, that the searched value is not in the current level. This way, I hope the code to be faster than doing some kind of depth-first search method.


Of course if your array is always 2 dimensional and you only want to search in this kind of arrays, then this is faster:

function in_2d_array($needle, $haystack) {
    foreach($haystack as $element) {
        if(in_array($needle, $element))
            return true;
    }
    return false;
}
Thursday, August 12, 2021
 
Keat
answered 4 Months ago
63

I've created a two-dimensional array that contains 5 rows and 5 columns. The array is an int type and have initialized with a value i*j. Already exists a method that takes a row number and value to search for.

private static Integer[][] myarray = new Integer[5][5];

public static boolean exists(int row, int value) {
    if(row >= myarray.length) return false;
    List<Integer> rowvalues = Arrays.asList(Arrays.asList(myarray).get(row));
    if(rowvalues.contains(value)) return true;
    return exists(row+1, value);
}
Thursday, August 19, 2021
 
Niels
answered 4 Months ago
19

Check your Php info Settings, Json is Enabled.

Sunday, August 29, 2021
 
Pointy
answered 3 Months ago
26

Try this:

$url = "https://cdn.psychologytoday.com/sites/default/files/blogs/38/2008/12/2598-75772.jpg";
$name = 'happy.jpg';

$image = Image::make($url)->encode('jpg');
$headers = [
    'Content-Type' => 'image/jpeg',
    'Content-Disposition' => 'attachment; filename='. $name,
];
return response()->stream(function() use ($image) {
    echo $image;
}, 200, $headers);

Here's what we're doing. We're using Intervention Image to encode that image into the correct file type format for us. Then we're setting the browser headers ourselves to tell the browser what type of file it is and that we want the browser to treat it as a downloadable attachment. Lastly, we return the response using Laravel's stream() method and use a closure. We tell the closure it has access to the encoded data of the image with use ($image) and then we simply echo that raw data onto the page. From there we tell the browser the HTTP code is 200 (OK), and then give it our headers to tell the browser what to do.

Your problem was that Laravel's handy download() method is expecting it to be a file on the file system. So we have to stream it and manually set the headers ourselves.

You will need to write some additional code to handle different file extensions for the encode() method Intervention uses as well as the Content-Type returned. You can find a list of all available mime types here.

I hope this helps.

Edit: Later versions of Laravel introduced the deleteFileAfterSend() method on the response object. If you are okay with temporarily saving the file to the server you can do this:

return response()->download($path)->deleteFileAfterSend();
Wednesday, October 20, 2021
 
Sufi
answered 2 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share