Insert posts and images into a single record
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 pre-check 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 what is inserted are 2 records instead of one.
I would like to use eloquent
for this.
I have done 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 me 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'];
}
1 answers
I think your problem is that not being saved the"Model"
I give you an example of how I have done it, and you tell me if it suits you:
$validator = \Validator::make($request->all(), (new DirectoriosRequest)->rules($request));
if ($validator->fails()) {
\Redirect::back()->withErrors($validator->messages())->withInput();
}
$directorio = new Directorio();
$directorio->categoria = $request->categoria;
$directorio->subcategoria = $request->subcategoria;
$directorio->nombre = $request->nombre;
$directorio->descripcion = $request->descripcion;
$destinationPath = env('DIRECTORIO_UPLOAD_DIR', 'admin/directorios');
$extension = $request->archivo->getClientOriginalExtension();
$fileName = pathinfo($request->archivo->getClientOriginalName(), PATHINFO_FILENAME)."_archivo_".rand(11111,99999).'.'.$extension;
$request->archivo->move($destinationPath, $fileName);
$directorio->archivo = $fileName;
if (isset($request->thumbnail)) {
$destinationPath = env('DIRECTORIO_UPLOAD_DIR', 'admin/directorios');
$extension = $request->thumbnail->getClientOriginalExtension();
$fileName = pathinfo($request->thumbnail->getClientOriginalName(), PATHINFO_FILENAME)."_thumbnail_".rand(11111,99999).'.'.$extension;
$request->thumbnail->move($destinationPath, $fileName);
$directorio->thumbnail = $fileName;
}
$directorio->save();
return \Redirect::to(action('Admin\DirectorioController@index'));
In my case the validator
:
Public function rules()
{
$rules = [
'categoria' => 'required|string',
'nombre' => 'required|string',
'descripcion' => 'required|string',
'archivo' => 'required',
];
return $rules;
}
}
With that I check that for sure it has to exist, without telling it it has to be an image, that I do directly with HTML5 in the input.
In your case I don't see the save()
of the Model
Edit: you are creating two records because the second create
does not have an Associated ID, therefore for Eloquent in a new "model". Give that create
the same ID and then it won't create a new record.