Example of CRUD with one to one relationship and image upload laravel - php

I am having trouble understanding and knowing how to create a one to one relationship with CRUD and file upload together, is it possible to give me a simple example on how to do it? Because when I tried to do it, for some reason my id and user_id doesn't match at all
Example, in user_info table (jack with id 1) has one userImage table(image uploaded with a user_id = 1).
This is the part that I am having trouble with in my controller:
public function store1(Request $request){
$this->validate($request, [
'input_img' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$user_info = Session::get('data');
$UserImage = new UserImage($request->input()) ;
if($file = $request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalExtension() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create(['file' => $request->file('input_img')]);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
//dd($UserImage);
return redirect('/home');
}

Sample of one to one relationship. I wish it can help you.
Example of table of Column of user table:
id
name
email
password
Example of table of Column of userimage table:
id
user_id
image_link
uploaded
User Model
public function userImage()
{
return $this->hasOne(App\UserImage::class);
}
UserImage Model
public function user()
{
return $this->hasOne(App\User::class);
}
CRUD in controller
public function store(Request $request)
{
$user = new App\User;
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->create([
'image_link' => $request->image,
'uploaded' => $request->date,
]);
return back();
}
public function update(Request $request, $id)
{
$user = App\User::find($id);
$user->name = $request->name;
$user->email = $request->email;
$user->password = $request->password;
$user->save();
$user->userImage->image_link = $request->image;
$user->userImage->uploaded = $request->date;
$user->userImage->save();
return back();
}
public function destroy($id)
{
$user = App\User::find($id)->delete();
return back();
}

Create a foreign key in your user_info table referencing userImage table.
Create unique constraint on the foreign key.

Related

Unable To Upload multiple Photos in Table in Laravel any help would be apricated

this Is the Model which I am using for inserting photos in Photos Table by use of MorphMany Realtions in laravel in Object Model
public function photos(){ return $this->morphMany('App\Photo', 'photoable');}
photable function in Photo model
public function photoable(){
return $this->morphTo();
}
form for adding photos.
<input type="file" name="objectPictures[]" id="objectPictures" multiple><br>
here I am inserting the Object in objects table along with Photos in Photos table. Object inserted successfully but photos are not inserting.
public function saveObjectby(Request $request)
{
$inputs=request()->validate([
'name'=> 'required|min:8|max:255',
'description'=> 'required',
]);
$object = new TouristObject();
$object->user_id = $request->user()->id;
$object->name = $request->input('name');
$object->package_id = $request->input('package_id');
$object->description = $request->input('description');
$object->save($inputs);
if ($request->hasFile('objectPictures'))
{
$this->validate($request, \App\Photo::imageRules($request,'objectPictures'));
foreach($request->file('objectPictures') as $picture)
{
$path = $picture->store('objects', 'public');
$photo = new Photo;
$photo->path = $path;
$object->photos()->save($photo);
}
}
}

Can not retrieve the id of a foreign key [Laravel]

I have 2 tables: User and demands. A User can have as many demands as he wants. Inside the demands table, there is the User foreign key.
When the User completes the form, I put the User & demands information inside those 2 tables.
But I do not know how to have the User id to put it inside the demands table.
Here is the function inside my Controller:
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user ->numStudent= $request->NumStudent;
$user ->role_id = "3";
$user ->Lastname = $request->LastName;
$user ->FirstName= $request->FirstName;
$user ->numero_etudiant = "12345678";
$user ->email = $request->Email;
$user ->password = bcrypt('idk');
$user ->adress= $request->Adress;
$user ->phone = $request->Phone;
$user ->parcours = $request->Parcours;
$demand->status_id= "3";
//problem below
$demand->User_id= $User;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$user ->save();
$demand->save();
return redirect('/demands_list');
}
But it says "Can't use method return value in write context".
Cordially
You have to save first the instance of your user before using its properties. Your code should look like this.
public function store(Request $request){
$demand = new Demand;
$user = new user ;
$user->numStudent= $request->NumStudent;
$user->role_id = "3";
$user->Lastname = $request->LastName;
$user->FirstName= $request->FirstName;
$user->numero_etudiant = "12345678";
$user->email = $request->Email;
$user->password = bcrypt('idk');
$user->adress= $request->Adress;
$user->phone = $request->Phone;
$user->parcours = $request->Parcours;
$user->save();
$demand->status_id= "3";
//problem below
$demand->User_id= $user->id;
//
$demand->time_id = $request->LoanTime;
$demand->creation_date = $request->CreationDate;
$demand->comments = "";
$demand->save();
return redirect('/demands_list');
}
Assuming by your tags that you are looking for an Eloquent (i.e. Laravel) way of doing this.
The short answer: use route model binding and keep your controller methods organized and single-focused.
As already answered, your User needs to be saved first. I would recommend you do this step in its own controller:
// UsersController.php
public function store(Request $request) {
$attributes = $request->validate([
// validation rules
]);
$user = User::create($attributes);
return redirect('/users/' . $user->id);
}
Now that you have a User created, you can then attach related models. Create a separate set of routes pointing to a separate controller for handling the relationship:
// routes/web.php
Route::get('/user/{user}/demands', 'UserDemandsController#index');
Route::post('/user/{user}/demands', 'UserDemandsController#store');
// ^^^^^^
// used with route model binding
Here's where route model binding comes into play, loading the model straight from the route parameters ({user}):
// UserDemandsController.php
public function store(Request $request, User $user) { // <-- ROUTE MODEL BINDING
$attributes = $request->validate([
// validation rules
]);
$user->demands()->create($attributes);
}
The result is very clean, simple code.

Creating default object from empty value laravel 5.7

I have an error in my update user admin form where I want to update the profile that's corresponding to the user if he has a profile. But it throws this error:
Creating default object from empty value
I have set relationships in my model between the User and profile Profile::where('id', $user->profile_id)->first(); but when I dd it's always a null, even if there is a corresponding profile.
User.php
public function profile()
{
return $this->hasOne('App\Profile', 'user_id', 'id');
}
Profile.php
public function user()
{
return $this->belongsTo('App\User');
}
function error is in
public function update(Request $request, User $user)
{
if(\Auth::check()) {
if(\Auth::user()->type == 'admin') {
$validated = $request->validate([
'name' => 'required',
'email' => 'required|email',
'password' => 'confirmed'
]);
if(!empty($validated['password'])){
if(!$user->profile){
//Has no profile
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->update();
} else {
//Has profile
$profile = Profile::where('id', $user->profile_id)->first();
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->update();
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->update();
}
} else {
if(!$user->profile){
//Has no profile
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->update();
} else {
//Has profile
$profile = Profile::where('id', $user->profile_id)->first();
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->update();
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->update();
}
}
}
}
}
on these lines $profile = Profile::where('id', $user->profile_id)->first();
Since you are using user_id as a foreign key in the profiles table, you would expect this as your statement:
Profile::where('user_id', $user->id)->first();
Or, by using the relation:
$user->profile;
You can just use your relation and also compress the logic as :
$user->name = $validated['name'];
$user->email = $validated['email'];
if(!empty($validated['password'])){
$user->password = bcrypt($validated['password']);
$profile = $user->profile;
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->save();
}
$user->save();

Having a problem with a pivot table on Laravel

I have a form with two pivot tables. One of them works just fine but I can't seem to be making the second one work despite them being quite similar. The one not working is for an image table called 'photos' and the form upload in called 'releases'. I called the pivot table 'photo_releases' with the 'photo_id' and a 'release_id' field.
DB Pivot Table
here is the release Modal
class Release extends Model
{
public function photos()
{
return $this->belongsToMany('App\Photo', 'photo_releases', 'release_id', 'photo_id');
}
}
and the photo modal
class Photo extends Model
{
public function releases()
{
return $this->belongsToMany('App\Release', 'photo_releases', 'photo_id', 'release_id');
}
}
and the ReleaseController
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01')) {
$file_name = preg_replace("/[^a-zA-Z0-9.]/", "", $file->getClientOriginalName());
$name = time() . 'photo_01' . $file_name;
$file->move('images', $name);
$input['photo_01'] = $name;
$photo = new Photo();
$photo->url = $input['photo_01'];
$photo->save();
}
$release = Release::create($request->except('release_id'));
dd($request->except('release_id'), $request->get('photo_id', []), $request->get('artiste_id', []));
$release->photos()->attach($request->get('photo_id', []));
$release->artistes()->attach($request->get('artiste_id', []));
return redirect('/admin06000/releases');
}
There is two pivot tables being used in this function. the one using
"$release->artistes()->attach($request->get('artiste_id', []));"
is working correctly but the photos is not. The url is being logged in the correct DB and the image is uploading fine, but the pivot table is not being updated. If anyone could help it would be greatly appriciated.
try This if you need some select in relation ship change
with('photos')
to
with(['photos'=>function($query){$query->where(....)->get();}])...
use Image;
use Illuminate\Support\Facades\Input;
...
public function store(ReleasesCreateRequest $request)
{
$input = $request->all();
$user = Auth::user();
if ($file = $request->file('photo_01'))
{
$image= Input::file('photo_01');
$name = time().'photo_01'.'.'.$image->getClientOriginalExtension();
$path=public_path('/YourPath/'.$name);
Image::make($image->getRealPath())->save($path);
$photo = new Photo();
$photo->url = '/YourPath/'.$name;
$photo->save();
}
$release = Release::create
([
'release_field'=>$amount,
'release_field2'=>$amount2,
....
]);
$release->with('photos')->with(artistes)->get();
}```

How to make Laravel controller store file upload with a relationship

I am trying to store an uploaded file with a relationship to an Employee model. I am unable to retrieve the employee id after uploading the file to save it to the DB table as a foreign key.
Routes:
Route::resource('employees', 'EmployeesController');
Route::post('documents', 'DocumentsController#createdocument')
So I am on a URL that says http://localhost/public/employees/8 when I hit upload it redirects to http://localhost/public/documents and the file does upload but shows error when writing to DB.
Here is my code. How can I do it?
public function createdocument(Request $request, Employee $id)
{
$file = $request->file('file');
$allowedFileTypes = config('app.allowedFileTypes');
$maxFileSize = config('app.maxFileSize');
$rules = [
'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
];
$this->validate($request, $rules);
$time = time(); // Generates a random string of 20 characters
$filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with
$destinationPath = config('app.fileDestinationPath').'/'.$filename;
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if($uploaded){
$employee = Employee::find($id);
$empdoc = new EmpDocuments();
$empdoc->name = $filename;
$empdoc->employee_id = $employee->id;
$empdoc->save();
}
return redirect('employees');
}
These are my models.
Employee.php
public function EmpDocuments()
{
return $this->hasMany('App\EmpDocuments');
}
public function createdocument(){
return $this->EmpDocuments()->create([
'name' => $filename,
'employee_id' => $id,
]);
}
EmpDocuments.php
public function Employee()
{
return $this->belongsTo('App\Employee');
}
With the above models and controller I am now getting error
General error: 1364 Field 'employee_id' doesn't have a default value (SQL: insert into empdocuments.
How do I capture the employee_id?
Managed to fix it, in case someone has similar problem. Ensure you pass the id with the route action for it to be capture in the next request.
Here is the final controller.
public function update(Request $request, $id)
{
$file = $request->file('file');
$allowedFileTypes = config('app.allowedFileTypes');
$maxFileSize = config('app.maxFileSize');
$rules = [
'file' => 'required|mimes:'.$allowedFileTypes.'|max:'.$maxFileSize
];
$this->validate($request, $rules);
$time = time(); // Generates a random string of 20 characters
$filename = ($time.'_'.($file->getClientOriginalName())); // Prepend the filename with
$destinationPath = config('app.fileDestinationPath').'/'.$filename;
$uploaded = Storage::put($destinationPath, file_get_contents($file->getRealPath()));
if($uploaded){
$employee = Employee::find($id);
$empdoc = new EmpDocuments();
$empdoc->name = $filename;
$employee->empdocuments()->save($empdoc);
return redirect('employees/' . $id . '#documents')->with('message','Document has been uploaded');
}
}
Do you have a relationship between Employee and EmpDocuments ??
If I am understanding well EmpDocuments belongsTO Employees right??
I'm trying to help but I need to understand, one employee can have many documents right?? but each document belongs to just one employee right??
If is like that you should make a relationship in your employee model,
` public function employeeDocuments(){
return $this->hasMany(EmpDocuments::class);
}`
Then in the same model
`public function createEmployeeDocuments(){
return $this->employeeDocuments()->create([
'your_db_fields' =>your file,
'your_db_fields' => your other some data,
]);
}`
The id will be inserted automatically
I hope I helped you!!
https://laravel.com/docs/5.3/eloquent-relationships
Are your fillable empty???
To use the Eloquent create method you need to set you fillable array to mass assignment. Try this, if is still not working tell me and I will try to do my best.
protected $fillable = [ 'employee_id', 'Your_db_field', 'Your_db_field', 'per_page', 'Your_db_field', 'Your_db_field' ];

Categories