I'm trying to pass data (more precisely an object,$product) to and from a FormRequest class, StoreImageRequest. After failing validation, the StoreImageRequest redirects to the image upload view, which depends on the model $product being passed (originally from the controller). As I am not sending any data back to the view, it reads $product as null.
I need the whole object ($product) to pass back to the view. I'm not sure if the model exists in the context of the class, and don't know how I can retrieve it AND pass it on to the redirected view to be used there. Laravel docs point to protected $redirectRoute = 'route_name'; but give no clue on data. I guess I'm trying to achieve something in the fashion of return redirect()->route('images.create')->with(['product' => $product] which works in the controller context.
How can I pass the model again to the view?
StoreImageRequest:
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'picture1' => 'mimes:jpeg,bmp,png,jpg|max:1000',
'picture2' => 'mimes:jpeg,bmp,png,jpg|max:1000',
'picture3' => 'mimes:jpeg,bmp,png,jpg|max:1000',
];
}
public function messages()
{
return [
'picture1.mimes' => "Los formatos de archivos soportados son .jpg, .bmp, .png",
'picture1.max' => "Peso de imagen maximo 1MB",
'picture2.mimes' => "Los formatos de archivos soportados son .jpg, .bmp, .png",
'picture2.max' => "Peso de imagen maximo 1MB",
'picture3.mimes' => "Los formatos de archivos soportados son .jpg, .bmp, .png",
'picture3.max' => "Peso de imagen maximo 1MB",
];
}
uploadimage.blade.php
<div style="margin-top: 50px">
<h1>Seleccione las imagenes del producto</h1>
<p> Producto: {{ $product->name }}</p>
<p> Id: {{ $product->id }}</p>
<p> Marca: {{ $product->brand }}</p>
<form id="image_form" action="{{ route('store.images', $product->id) }}" method="post" enctype="multipart/form-data">
@csrf
<div >
<input type="file" name="picture1">
</div>
<div >
<input type="file" name="picture2">
</div>
<div >
<input type="file" name="picture3">
</div>
<button type="submit">Subir imagenes</button>
</form>
CodePudding user response:
You can define a getRedirectUrl() method in your FormRequest class.
<?php
/**
* Get the URL to redirect to on a validation error.
*
* @return string
*/
protected function getRedirectUrl()
{
$product_id = $this->route()->parameter('product_id');
return 'store/' . $product_id . '/images'; // Or whatever your route name is
}
CodePudding user response:
Found a workaround. If the data comes from a Session beforehand, it is possible to retrieve the session in the context of the FormRequest and reflashing it with:
/**
* Get the session associated with the request.
*
* @return \Illuminate\Session\Store|null
*/
public function getSession()
{
return $this->session;
$this->session()->reflash();
}
After that the session (and object $product within it) will be available for the view to use in the form of
{{ session()->get('product') }}
