I wanna know that it is correctly to something like this. In my database i have table with users and photos. Every one user has exactly one picture. I have one view with form which is route post to UsersController to store method.
UsersController
public function store(Request $request)
{
// some validation
$user = new Users();
$user->name = $request->input('name')
.....
if($user->save())
{
if($request->hasFile('photo'))
{
$photo = new Photos();
....
$photo->save();
return redirect......
}
}
}
It is correctly to insert data from one controller to muliple tables. In this example it's only one additional table but every know there may be more of them.
If you aren't going to use the images for other models, it is better to have an image column directly in the users table to avoid the extra work that seems unnecessary to me.
Or if you need to have a different table for images, I suggest you should use Eloquent OneToOne
polymorphic relationships.
Schema for photos table:
photos
id - integer
url - string
photoable_id - integer
photoable_type - string
And in your Photo
model:
public function photoable()
{
return $this->morphTo();
}
And in your User
model:
public function photo()
{
return $this->morphOne('App\Photo', 'photoable');
}
Now in your controller:
$user = new Users();
$user->name = $request->input('name')
if($user->save())
{
if($request->hasFile('photo'))
{
// Save the file to disk and get it's URL as $photoUrl
$user->photo()->create([
'url' => $photoUrl
]);
}
}
Now once the photo is saved, you can get the photo for the user using photo
property on user object, i.e. $user->photo
. The benefit of this architecture is that you can use the same table to store photos for other models too when needed. You will just need to copy the photo()
method from User
model to your other models where you intend to have the photos.
Apart from all this, I see that you have used Photos
name for the model, but in Laravel, you should always use singular names for models, not the plural ones. So I'd suggest that you should change your model name from Photos
to Photo
in order to ensure that you flawlessly use the power of Eloquent without any headache.