I have a post table that has an image field, and I have a problem, when I try to insert the field, I have to check previously that the user has posted an image, and if so insert it. This worked perfectly for me when the image was in a separate table, but if I want to insert it next to the initial post, I insert the post first and then the image, with which it is inserted are 2 records instead of one. I would like to use eloquent for this.
I have made a test of doing a function inside another function to determine if the image field exists and insert one thing or another but it does not recognize the request so this solution I think is not viable.
I pass the code to you.
public function store(Request $request)
{
/*******************************************************VALIDACIONES CAMPOS*********************************/
$validador = \Validator::make($request->all(),
array('titulo' => 'required',
'contenido' => 'required',
// 'imagen' => 'required|image'
),
array(
'required' => 'El campo :attribute es requerido ahora mismo',
)
);
if ( $validador->fails()) :
return redirect()->back()->withErrors($validador);
endif; /*******************************************************FIN VALIDACIONES CAMPOS*********************************/
/*******************************************************CREACION POST*********************************/
$nombreimagen = 'mesteban_'.time().'.'.$request->file('imagen')->getClientOriginalExtension();
function devuelveImagen()
{
if( $request->HasFile('imagen')):
return $nombreimagen;
else:
return 'ruta de imagen personalizada_'.rand(10000,20000);
endif;
}
devuelveImagen();
$datosaInsertar =
array(
'titulo' => $request->titulo,
'imagen' => $this->devuelveImagen(),
'contenido' => $request->contenido,
'url' => str_slug($request->titulo),
);
$creandoPost = \App\modelos\post::create($datosaInsertar);
\Session::flash('estado','El post de nombre ..:: '.$request->titulo.' ::.. ha sido creado correctamente');
/*******************************************************FIN CREACION POST*********************************/
/*******************************************************CREACION IMAGEN*********************************/
$ruta = public_path('ima\posts\');
if($nombreimagen):
$request->file('imagen')->move($ruta,$nombreimagen);
//USANDO LIBRERIA INTERVENTION PARA REDIMENSIONAR IMAGEN;
\Image::make($ruta.$nombreimagen)->resize(300,300)->save();
// \App\modelos\post::create(array('imagen'=> $nombreimagen));
endif;
/*******************************************************FIN CREACION IMAGEN*********************************/
return redirect()->to('/admin/posts');
}
POST MODEL
<?php
namespace App\modelos;
use Illuminate\Database\Eloquent\Model;
class post extends Model
{
protected $table = 'posts';
protected $fillable = ['titulo','contenido','imagen','url'];
}