@feelsonix is the relationaship between your Post and Image model 1-1 or 1-m ?
and it would help if you could post your models here so we can help you better.
Update other table with relationships
HI,
I'm french sorry for my english. I made a projet with Laravel, brefore i store my image url in my post table with a column url. Now i have make a new table named image, this table have a id and url column. I have make the relatinship in my two Models.
But with the controller i dont know how update the new url of the image i've upload in my image table.
This is my code:
How can i pass the url and the id of my post in my table Image ?
Thank you. Thomas.
@feelsonix PostController.php -- update method
public function update(Request $request, $id)
{
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required',
'category_id' => 'required|integer',
'body' => 'required'
));
// Validate the data
$post = Post::find($id);
$categories = Category::pluck('name','id');
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->category_id = $request->input('category_id');
$post->user_id = Auth::id();
$post->body = $request->input('body');
if ($request->hasFile('featured_img')) {
// Ajoute la nouvelle photo
$image = $request->file('featured_img');
$filename = time() . '.' . $image->getClientOriginalExtension();
$location = public_path('img/' . $filename);
Image::make($image)->fit(1200, 500)->save($location);
$oldFilename = $post->postImage->url;
$post->postImage()->createOrUpdate([
'post_id' => $post->id
],[
'url' => $filename
]);
// Efface l'ancienne photo
Storage::delete($oldFilename);
}
$post->save();
Session::flash('success', "L'article à été correctement mis à jour.");
return redirect()->route('posts.index');
}
PostImage.php -- model
class PostImage extends Model
{
protected $table = 'image';
protected $fillable = ['url','post_id'];
public function post()
{
return $this->belongsTo(Post::class);
}
}
Post.php -- model
class Post extends Model
{
protected $fillable = ['title','description','order'];
public function postImage()
{
return $this->hasOne(PostImage::class);
}
}
adjust the namespace for the models and migrations and you would be good to go... but you need some extra work to delete the image from storage and if save fails you could run the code for update inside a transaction. anyways good luck.
Please or to participate in this conversation.