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();
}```
Related
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);
}
}
}
A user can register/sign up as either a Job Seeker or an Employer. If he is a Job Seeker, he can create a profile on the create profile page. On the form their are 4 inputs with the file type, among other inputs.
See screenshot below.
I have a Table called job_seeker_profiles, there are several columns in there, but only these 4 are relevant to my issue.
resume_id, video_one_id, video_two_id, video_three_id
I also have 2 Tables, Resumes and Videos, each have one column called 'file'.
This is working, the file paths are being inserted into the database.
In my public folder, I created 2 directories resumes and videos. This is where I want to store the files. This part is also working, when I upload a resume only (No Videos, they are optional) and click Create Profile, The file appears in the /resumes folder within my public folder.
The problem is, in the resume_id column in the job_seeker_profiles Table, I get this value inserted into my database "/Applications/XAMPP/xamppfiles/temp/phpx6Dmr" instead of the id of the file from the Resumes Table.
I think maybe it's a problem with my relationships?
Here is my code.
AdminJobSeekerProfilecontroller.php file:
public function store(JobSeekerCreateRequest $request)
{
if($file = $request->file('resume_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('resumes', $name);
$resume = Resume::create(['file'=>$name]);
$input['resume_id'] = $resume->id;
}
$input = $request->all();
if($file = $request->file('video_one_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('videos', $name);
$video = Video::create(['file'=>$name]);
$input2['video_one_id'] = $video->id;
}
$input2 = $request->all();
if($file = $request->file('video_two_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('videos', $name);
$video = Video::create(['file'=>$name]);
$input3['video_two_id'] = $video->id;
}
$input3 = $request->all();
if($file = $request->file('video_three_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('videos', $name);
$video = Video::create(['file'=>$name]);
$input4['video_three_id'] = $video->id;
}
$input4 = $request->all();
JobSeekerProfile::create($input, $input2, $input3, $input4);
return redirect('/admin/job-seeker/profile/create');
}
Resume.php Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Resume extends Model
{
protected $uploads = '/resumes/';
protected $fillable = ['file'];
//create an accessor
public function getFileAttribute($resumes){
return $this->uploads . $resumes;
}
}
JobSeekerProfile.php Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class JobSeekerProfile extends Model
{
protected $dates = ['date_of_birth'];
protected $fillable = [
'user_id',
'photo_id',
'resume_id',
'video_one_id',
'video_two_id',
'video_three_id',
'first_name',
'last_name',
'email',
'full_or_part_time',
'additional_skills',
'file'
];
public function user(){
return $this->belongsTo('App\User');
}
public function resume(){
return $this->belongsTo('App\Resume');
}
public function video(){
return $this->belongsTo('App\Video');
}
}
On a side note, I know I should store the video files on something like amazon s3, but I want to get it working this way for now. And if you have any recommendations for Laravel and hosting files on a cloud based system that would be great as well.
Thank you Tpojka. This worked for me now:
$input = $request->all();
$user = Auth::user();
if($file = $request->file('resume_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('resumes', $name);
$resume = Resume::create(['file'=>$name]);
$input['resume_id'] = $resume->id;
}
$user->jobseekerprofile()->create($input);
return redirect('/admin/job-seeker/profile/create');
I want to upload a photo along with a text
But the photo path is not saved inside the table, but the photo is uploaded to the directory
Controller code
namespace App\Http\Controllers;
use App\Http\Requests\singlereq;
use App\infouser;
class singleupload extends Controller
{
public function uploadform()
{
return view('singleupload.upload_form');
}
public function uploadSubmit(singlereq $request)
{
$file = $request->file('imgs');
$file->move('img', $file->getClientOriginalName());
$product = infouser::create($request->all());
return 'OK Upload successful!';
}
}
Used below code. to get the image name and set the table column (your_file) your is column name in your table.
$file = $request->file('imgs');
$file->move('img', $file->getClientOriginalName());
$input = $request->all();
$name = $file->getClientOriginalName();
$input['your_file'] = $name;
$product = infouser::create($input);
return 'OK Upload successful!';
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' ];
I use Laravel 4 and my store function in controller is :
public function store()
{
$validation = new Services\Validators\Speaker;
if($validation->passes())
{
$file = Input::file('image');
$imageName = time().'_'.$file->getClientOriginalName();
$file->move('photos/',$imageName);
$input = Input::all();
$speaker = $this->speaker->create(Input::all());
return Redirect::route('speaker.index');
}
The uploaded photo is moved to the specified place and named correctly. But in the database, the image file name is not correctly saved. "C:\xampp\tmp\php2B7D.tmp" this kind of data is saved. I want to save image name and path. Any ideas. Thanks in advance.
I found solution. here the code
public function store()
{
$validation = new Services\Validators\Speaker;
if($validation->passes())
{
$file = Input::file('image');
$imageName = time().'_'.$file->getClientOriginalName();
$file->move('photos/',$imageName);
$input = array('name'=>Input::get('name'),
'image'=> 'photos/'.$imageName,
'desc'=>Input::get('desc')
);
$speaker = $this->speaker->create($input);
return Redirect::route('speaker.index');
}