You can create 2 routes and pass the model to a PhotoRepository that handles the actual storing and attaching logic and inject that in each controller;
You'll need a way to tell the Photo what kind of model you're attaching it to.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,I have simply 3 models: Photo,User,Place,
a user and a place can have photos.
I have created polymorphic relations and all tables and models, etc.
Right now I wanna upload a photo,but here's the problem:
Should I create 2 routes for two kinds of uploading image or can I get done with just one I mean:
route::get('place/{placeid}/addphoto',PlacesController@addPhoto') //for Places
route::get('user/{userid}/addphoto',UsersController@addPhoto') //for Users
Is there a way to upload a photo (save a file and create a record in photos table)
with just one route?
@Mithridates Repository (also known as the Repository Pattern) is a class which is usually a collection of query methods for a specific entity (model or database table or maybe something else). All your queries stay in this class, you write them once and you can call them anywhere in your application where you need to query something from the database. It keeps your code DRY (Don't Repeat Yourself).
Example:
class UserRepository
{
public function getAllUsers()
{
return User::all();
}
public function getUserByUsername($username)
{
return User::where('username', $username)->first();
}
public function getUserById($userId)
{
return User::find($userId);
}
public function createNewUser(array $userDetails)
{
return User::create($userDetails);
}
}
class UsersController extends Controller
{
protected $userRepository;
public function __construct(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function index()
{
$users = $this->userRepository->getAllUsers();
return view('users.index', compact('users'));
}
public function create(Request $request)
{
$this->userRepository->createNewUser($request->all());
return redirect('users');
}
}
Not the best code (it can be improved) but I just wrote it to give you an idea of what a repository is. It is simple if you understand how Object Oriented Programming (in PHP) works.
Please or to participate in this conversation.