One to one relationship while doing CRUD (create part) - php

I am having some trouble doing a one to one relationship with user_info table and userImage table. When I try to upload my image, it didn't save into my database and it user_id is 0. I managed to successfully do a one to many and one to one relationship in the past but not with CRUD together. Can anyone help me? Best to give me some example for me to refer or advice on what should I do. Thanks in advance
Here are my current codes:
createController:
public function create1(){
return view('create1');
}
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($request->hasFile('input_img')) {
$file = $request->file('input_img');
$fileName = $file->getClientOriginalName();
$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() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->userImage!!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>

You need to check out Laravel relations to clean up that code and simplify a lot of steps.
Change this line
$UserImage->user_infos()->associate($user_info);
For this
$UserImage->user_id = $user_info;
Take in mind that you're overriding the value of $UserImage inside that method.

Related

Record is not added in to the database codeigniter 4

i am a begineer of codeigniter 4.i had a problem is Record is not added in to the database. i got the url link like this http://localhost:8080/index.php/usersCreate error said Whoops!
We seem to have hit a snag. Please try again later... . i don't know how to solve problem what i tried so far i attached below.
View
User.php
<form method="post" id="add_create" name="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="empid" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<Button class="btn btn-success" style="width: 80px;">Submit</Button>
</div>
</form>
Controller
User.php
public function index()
{
return view('User');
}
// insert data
public function store() {
$userModel = new UserModel();
$data = [
'fname' => $this->request->getVar('fname'),
'lname' => $this->request->getVar('lname'),
];
$userModel->insert($data);
return $this->response->redirect(site_url('users'));
}
UserModel
<?php
namespace App\Models;
class UserModel extends Model
{
protected $table = 'records';
protected $primaryKey = 'id';
protected $allowedFields = ['fname', 'lname'];
}
Routes
$routes->get('/', 'User::index');
$routes->post('usersCreate', 'User::store');
I don't know CodeIgniter per se, but you should figure out how to get more meaningful data. Is your environment set to development environment? Usually you will get more info than Whoops! We seem to have hit a snag. Please try again later... and get more details on the error.
But I see you're trying to go to the page, where you add a user. There's 2 ways to methods to reach that page, GET (this is when you just go to the page as usual) and POST (this is when you submit the form).
But the request data will only be available if you submit the form. Thus you have to differentiate between the 2 methods. In your Controller you need to do something like
if ($this->request->getMethod() === 'post') { ... }
which is when you submit the form.
Check out https://codeigniter.com/user_guide/tutorial/create_news_items.html which should have more info. Snippet
public function create()
{
$model = new NewsModel();
if ($this->request->getMethod() === 'post' && $this->validate([
'title' => 'required|min_length[3]|max_length[255]',
'body' => 'required'
]))
{
$model->save([
'title' => $this->request->getPost('title'),
'slug' => url_title($this->request->getPost('title'), '-', TRUE),
'body' => $this->request->getPost('body'),
]);
echo view('news/success');
}
else
{
echo view('templates/header', ['title' => 'Create a news item']);
echo view('news/create');
echo view('templates/footer');
}
}
I normally use a short method to get data and then submit it to the database. Here is what id do. check this. I am just updating your code
// insert data
public function store() {
$userModel = new \App\Models\UserModel();
$data = [
'fname' => $this->request->getPost('fname'),
'lname' => $this->request->getPost('lname'),
];
$userModel->insert($data);
return redirect()->to(site_url('users'));
}
then check you html file you are missing the firstname name
Try this one
<form method="post" id="add_create" action="<?php echo site_url('usersCreate');?>">
<div class="form-group col-md-6">
<label>First Name</label>
<input type="text" name="fname" class="form-control" id="fname" placeholder="fname">
</div>
<div class="form-group col-md-6">
<label>Last Name</label>
<input type="text" name="lname" class="form-control" id="lname" placeholder="lname">
</div>
<div class="form-group col-md-6" align="center">
<button type="submit" class="btn btn-success" style="width: 80px;">Submit</button>
</div>
</form>
For the check your model i think is not configured well check this one
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'users';
protected $primaryKey = 'id';
protected $returnType = 'object';
protected $useSoftDeletes = false;
protected $allowedFields = ['fname', 'lname', 'email']; // did you add this side of the site model
protected $useTimestamps = false;
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
protected $validationRules = [];
protected $validationMessages = [];
protected $skipValidation = false;
}
Check my code if it did not help you call my attentions okay. I am still ready to help

Unable to submit binary image into database in laravel

I am trying to submit an image into the database but I keep getting this error: Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, null given, called in C:\xampp\htdocs\Evaluation\app\Http\Controllers\ImageController.php on line 24.
I checked with other questions in StackOverflow and mostly they said it was the fault of the saving part where they put something like this, $post but I have checked and there is nothing wrong with it. The relationship doesn't seem to have any problem as well but why is it still not working? The error also return me a null when I upload image. The null is returning at the part here, $UserImage = $request->input('UserImage'); So could my problem be in image1.blade.php?
ImageController:
public function test(personal_info $user){
return view('image1',compact('user'));
}
public function test1(Request $request){
$UserImage = new Image;
$personal_info = new personal_info;
$UserImage = $request->input('UserImage');
$id = $request->user_id;
$id = personal_info::find($id);
$id->Images()->save($UserImage);
return redirect('/summary');
}
image1.blade.php (where i submit the form)
<form class="form-horizontal" method="post" action="{{ url('/Upload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="UserImage">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2" style="padding-left: 30px">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
Image.php:
public function personal_infos() {
return $this->belongsTo('App\personal_info', 'user_id', 'id');
}
personal_info.php:
public function Images() {
return $this->hasOne('App\Image','user_id');
}
public function test1(Request $request)
{
// make new instance of Image Model
$imageModel = new Image;
// find personal_info Model by id
$personal_info = personal_info::findOrFail($request->input('user_id'));
// UploadedFile
$image = $request->file('UserImage');
// get the file contents?
$imageModel->content = ...
// save the relationships, pass a model instance to `save`
$personal_info->Images()->save($imageModel);
return redirect('/summary');
}

Undefined variable:user laravel

I keep on getting this error whenever I try to enter the upload page.
Can anybody help?
I have already done the compact part to make sure that the variable is being passed to the view and also my route should be ok I think.
I tried using dd but all it does is keep on showing me the error
Error: Undefined variable: user (View: C:\xampp\htdocs\Evaluation\resources\views\upload.blade.php)
Here are my codes:
upload.blade.php
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{$user->id}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
UploadController:
public function upload(){
return view(‘upload’);
}
public function store(Request $request,$id){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
var_dump('has file '.$request->hasFile('file'));
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id;
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
// $Image->user_id = $id;
//$Image->save();
$user->find($id);
dd($user);
$user->Images()->save($Image);
}
return redirect('/home');
}
public function test(){
$user = user_information::where('id')->get();
return view('upload', compact('user'));
}
Route: (this are my route)
Route::get('/UploadUser/upload','UploadController#upload’);
Route::post('/UploadUser','UploadController#store');
Route::post('/UploadUser/upload', 'UploadController#test');
Another question: I keep on getting this error when i try to upload a file, so what should I do?
Here is the error:
SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or
update a child row: a foreign key constraint fails (form.images,
CONSTRAINT images_user_id_foreign FOREIGN KEY (user_id) REFERENCES
usere_information (id)) (SQL: insert into images (name,
size, user_id, updated_at, created_at) values (download.png,
4247, 1, 2017-10-25 08:54:57, 2017-10-25 08:54:57))
Image model:
class Image extends Model
{
protected $fillable = array('name','size','user_id');
public function user_informations() {
return $this->belongsTo('App\user_information', 'user_id', 'id');
}
}
Images table:
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('size');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('user_informations');
$table->timestamps();
});
User_information table:
Schema::create('user_informations', function (Blueprint $table) {
$table->increments('id');
$table->engine = 'InnoDB';
$table->binary('signature');
$table->String('Name');
$table->timestamps();
});
User_information model:
class user_information extends Eloquent
{
protected $fillable = array('signature', 'Name');
protected $table = 'user_informations';
protected $primaryKey = 'id';
public function Images() {
return $this->hasOne('App\Image','user_id');
}
}
How to get the image?
Here is the view folder:
#foreach ($data as $object)
<b>Name: </b>{{ $object->Name }}<br><br>
Edit<br>
#foreach ($data3 as $currentUser)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endforeach
#if($data3->count())
#foreach($data3 as $currentUser)
<a href="{!! route('user.upload.image', ['id'=>$currentUser->user_id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
</a>
#endforeach
#else
<a href="{!! route('user.upload.image', ['id'=>$object->id]) !!}">
<button class="btn btn-primary"><i class ="fa fa-plus"></i>Upload Images</button>
#endif
#endforeach
HomeController:
public function getInfo($id) {
$data = user_information::where('id',$id)->get();
$data3=Image::where('user_id',$id)->get();
return view('test',compact('data','data3'));
Because you didn't pass the user to your upload view, try to pass it like this :
public function upload(){
$id = 1 //The wanted user or if the user is authenticated use Auth::id()
$user = User::find($id);
return view('upload')->withUser($user);
}
Or if the user is authenticated use Auth in the view :
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<input type="hidden" name="user_id" value="{{auth()->id()}}">
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input type="file" name="file">
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
For the second problem it's because in the route you have
Route::post('/UploadUser','UploadController#store');
and the your store method signature is
public function store(Request $request,$id){
The $id parameter that did the problem because it's not defined in the route so simply remove it from the method signatre
public function store(Request $request){
$this->validate($request, [
'file' => 'required|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
if ($request->hasFile('file')) {
$image = $request->file('file');
$name = $image->getClientOriginalName();
$size = $image->getClientSize();
$id = $request->user_id; // here id is declared no need for the parameter
$destinationPath = public_path('/images');
$image->move($destinationPath, $name);
$Image = new Image;
$Image->name = $name;
$Image->size = $size;
$Image->user_id = $id;
$Image->save();
}
return redirect('/home');
}
For the third case you have to change the routes from :
Route::get('/UploadUser/upload','UploadController#upload’);
to
Route::get('/UploadUser/{user}/upload','UploadController#upload’)->name('user.upload.image');
And in the view add the id in the upload button url maybe like this :
{!! route('user.upload.image', ['user'=>$currentUser->id]) !!}
Then in the upload method :
public function upload(user_information $user){ // route model binding here
// dd($user); //for testing only :)
return view('upload')->withUser($user);
}
In the view change
<input type="hidden" name="user_id" value="{{auth()->id()}}">
To
<input type="hidden" name="user_id" value="{{$user->id()}}">
And you are good to go ;)
#foreach ($data as $currentUser)
<b>Name: </b>{{ $currentUser->Name }}<br><br>
Edit<br>
#if($currentUser->Image)
<img src="{{ asset('public/images/' . $currentUser->Image->name ) }}">
#endif
<a href="{!! route('user.upload.image', ['id'=>$currentUser->id]) !!}">
#endforeach
You have miss to pass id in your where condition,
public function test(){
$user = user_information::where('id',$id)->first();
return view('create1', compact('user'));
}
and you have to pass your user data into this,
public function upload(){
$user = user_information::where('id',$id)->first();
return view(‘upload’,compact('user'));
}
Hope it helps,
On your upload function, you have to pass the user variable because you use the $user in the view. So the controller will be
public function upload() {
$user = Auth::user();
return view('upload', compact('user'));
}
do not forget to change the $user based on your need.
You have to pass an $id variable into your test() method. Then please comment below what's the error next so I can follow you through.
Update
Since you don't want to pass an id. You can use:
public function test(){
$u = Auth::user();
$user = user_information::where('id', $u->id)->get();
return view('upload', compact('user'));
}
OR
Try to use first() instead of get().
More option:
I have noticed, you're using the upload() method here, why not passing the $user there? like so:
public function upload(){
$user = Auth::user();
return view(‘upload’, compact('user'));
}

Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in laravel

I'm trying to post an image from a one to many relationship while also doing the CRUD (create part), but I am having some trouble doing it. I keep on getting this error
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Builder::create() must be of the type array, object given, called in
Whenever I try to use associate to define the relationship together with user_info with user_image table. I have already used the array function to make it into an array but it still gave me this error. So what should I do?
createController:
public function create1(){
return view('create1');
}
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 = array();
$file = $request->file('input_img') ;
$fileName = $file->getClientOriginalName() ;
$destinationPath = public_path().'/images' ;
$file->move($destinationPath,$fileName);
$UserImage->userImage = $fileName ;
$UserImage = UserImage::create($file);
$UserImage->user_infos()->associate($user_info);
}
$UserImage->save() ;
return redirect('/home');
}
HomeController(this is where I print out my information)
public function getInfo($id) {
$data = personal_info::where('id',$id)->get();
$data3=UserImage::where('user_id',$id)->get();
return view('test',compact('data','data3'));
blade.php (how I show the image in view)
#foreach ($data3 as $object9)
<img width="100" height="100" src="{!! $object9->signature !!}">
#endforeach
UserImage model(in table I used binary format to store in DB)
class UserImage extends Eloquent
{
protected $fillable = array('userImage','user_id');
public function user_infos() {
return $this->belongsTo('App\user_info', 'user_id', 'id');
}
class user_info extends Eloquent
{
protected $fillable = array('Email', 'Name');
protected $table = user_infos';
protected $primaryKey = 'id';
public function UserImages() {
return $this->hasOne('App\UserImage','user_id');
}
}
create1.blade.php(this is how I upload the image)
<form class="form-horizontal" method="post" action="{{ url('/userUpload')}}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imageInput" class="control-label col-sm-3">Upload Image</label>
<div class="col-sm-9">
<input data-preview="#preview" name="input_img" type="file" id="imageInput">
<img class="col-sm-6" id="preview" src="" ></img>
</div>
</div>
<div class="form-group">
<div class="col-md-6-offset-2">
<input type="submit" class="btn btn-primary" value="Save">
</div>
</div>
</form>
You should give an array while passing data to create method like this. Currently, you are passing the file object.
$UserImage = UserImage::create(['file' => $request->file('input_img')]);

Laravel: How to create a data with a requirement of a foreignkey without using URI parameters in a form?

I have a 2 tables, Courses and Lessons:
Course:
id, user_id, title
Lessons:
id, course_id , title
And I have updated their Eloquent Relationship.
Now my problem is, how to create a lesson without using a parameters in the form? Because i think it's not a good practice and prone to security issues, like editing the html tag.
<form method="POST" action="{{url('/lesson/store/3')}}" class="form-horizontal" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label class="control-label col-sm-2" for="title">Title:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="title" name="title" placeholder="Enter title">
</div>
</div>
</form>
From my route:
Route::group(['prefix' => 'lesson'] , function(){
Route::get('create/{course_id}' , 'LessonController#create');
Route::post('store/{course_id}' , 'LessonController#store');
});
And my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Course;
use App\Lesson;
class LessonController extends Controller
{
public function create($course_id)
{
$course = Course::find($course_id);
return view('lesson.create' , compact('course'));
}
public function store(Request $request, $course_id)
{
$lesson = new Lesson;
$lesson->title = $request->title;
$lesson->course_id = $course_id;
$lesson->description = $request->description;
$lesson->episode = $request->episode;
if($request->hasFile('video'))
{
$file = $request->file('video');
$extension = $file->getClientOriginalExtension();
$video = 'course' . $course_id . '_ep' . $request->episode . $extension;
$destinationPath = public_path() . '/uploads/lessons/';
$file->move($destinationPath, $video);
$lesson->video = $video;
}
$lesson->save();
return redirect('course/show/' . $course_id);
}
}
and also, hidden input is not also advisable.
Another option is to have a hidden input with the id which will be passed with the form submission to your controller.

Categories