I am currently building a CRUD application using Laravel. It requires me to upload images and information but seems like there are some problems on storing the images to the localdisk folder.
Here is my controller code:
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
// $record = new Admin;
// return view('students.create');
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image'))
{
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->storeAs('public/images',$fileNameToStore);
// $file = $request->file('image');
// $extension =$file->getClientOriginalExtension();//getting image extensionimage
// $filename=time() ."." .$extension;
// $file->move('uploads',$filename->getClientOriginal);
// //getting from data base
}
else
{
// $lostitem->image = "";
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $request->image ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
The other information is saved. I hope to get help.
Change Your controller code to this:
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->move(public_path('images/'),$fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $request->image ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
And then access your image in the blade like this
<img src="{{ asset('images/'.$item->image) }}">
And make sure that you do have an folder named "images" in the public directory
Save the path of image in database
public function store(Request $request)
{
$lostitem =new Admin();
$this->validate($request, [
'date' => 'required',
'TimeFound' => 'required',
'AreaWhereFound' => 'required',
'image' => 'required',
'Remark' => 'required',
'DateClaimed' => 'required',
'TimeClaimed' => 'required',
'CategoryID'=>'required'
]);
$uuid = Str::uuid()->toString();
$lostitem->code = $uuid;
$lostitem->date = $request->date;
$lostitem->TimeFound = $request->TimeFound;
$lostitem->AreaWhereFound = $request->AreaWhereFound;
$lostitem->image = $request->image;
if($request->hasfile('image')){
$filenameWithExt=$request->file('image')->getClientOriginalName();
$filename=pathinfo($filenameWithExt,PATHINFO_FILENAME);
$extension =$request->file('image')->getClientOriginalExtension();
$fileNameToStore=$filename.'_' .time().'.'.$extension;
$path=$request->file('image')->move(public_path('images/'),$fileNameToStore);
}
else{
$fileNameToStore='noimage.jpg';
}
$lostitem->image = $path ;
$lostitem->Remark = $request->Remark;
$lostitem->DateClaimed = $request->inputDateClaimed;
$lostitem->TimeClaimed = $request->TimeClaimed;
$lostitem->CategoryID = $request->CategoryID;
$lostitem->save();
return redirect(route('LostItem_add'))->with('successMsg', 'Record added!');
}
& show it
<img src="{{ asset('images/'.$item->image) }}">
Related
I have a big struggle about adding file uploading to an existing laravel 6 form.
I want to add the file url to database for future to be displayed (or downloaded).
When i try to do something nothing is happaning, nothing in DB nothing in file dir.
Here is my model:
protected $fillable = [
'age',
'last_rab',
'names',
'email',
'phone',
'last_pos',
'cv',
'msg',
'status'
];
Here is my Controller:
public function store(Request $request)
{
$request->validate([
'names' => 'required',
'age' => 'required',
'last_rab' => 'required',
'last_pos' => 'required',
'phone' => 'required',
'cv' => 'required|mimes:doc,docx,pdf,txt|max:2048',
'msg' => 'required'
]);
if ($request->captcha != 58) {
return redirect()->back()->withInput()->with('warning', 'Wrong');
}
$karieri = new Karieri;
$karieri->age = $request->age;
$karieri->last_rab = $request->last_rab;
$karieri->names = $request->names;
$karieri->email = $request->email;
$karieri->phone = $request->phone;
$karieri->last_pos = $request->last_pos;
if ($request->hasfile('cv')) {
$file = $request->file('cv');
$name = time().'.'.$file->extension();
$file->move(public_path() . '/storage/app/public', $name);
$data = $name;
$karieri->cv = json_encode($data);
}
$karieri->msg = $request->msg;
$karieri->status = 0;
$karieri->save();
return redirect()->back()->with('success', 'Thanks');
}
Can somebody say how to do this?
i am new for laravel, i am not able to save the files in database on update function can any one help me for this,I have two related tables where one is a ticekt table and the other a one a documents table. In the documents table are the columns id, doc_name,doc_path,user_id and service_id. I'm trying to edit multiple images when editing a service. documents table not updating remaining things update successful
Cread service code
public function store(Request $request)
{
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$validator = Validator::make($request->all(),$rules);
if($validator->fails()){
return back()->with('warning','please Fill manadatory fields');
} else {
//$dates = ;
//dd($dates);
$ticket = new Ticket([
'user_id' => Auth::user()->id,
'ticket_id' => strtoupper(str_random(10)),
'email'=>$request->input('email'),
'typeofservice' => $request->input('typeofservice'),
'companyname' => $request->input('companyname'),
'representative' => $request->input('representative'),
'phone' => $request->input('phone'),
'services' => $request->input('services'),
'applicant' => $request->input('applicant'),
'remark' => $request->input('remark'),
'ticket_submit_date' => date('d-M-Y'),
'status' => "1",
]);
//dd($ticket);
$ticket->save();
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($ticket) {
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
//return $last_id;
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
$users = User::where('id','=',$ticket_details->user_id)->first();
$ticketid = $ticket_details->ticket_id;
$username = $users->first_name.' '.$users->last_name;
$mdata = ['ticketid'=>$ticketid,'name'=>$username];
$user['to']= $users->email;
Mail::send('emails.user_create_application',$mdata,function($message) use ($user){
$message->to($user['to']);
$message->subject('User Create Application');
});
return back()->with("success","Service Requiest Created Successfully! your tracking id:#$ticket->ticket_id" );
}
}
}
For uddate function given below
public function udateuserticket(Request $request, $id){
$rules = [
'email' => 'required|string|max:255',
'typeofservice' => 'required',
'companyname' => 'required',
'representative'=> 'required',
'phone' => 'required',
'services' => 'required',
'applicant' => 'required',
//'document' => 'required',
//'document.*' => 'required',
'remark' => 'required',
];
$email = $request->email;
$typeofservice = $request->typeofservice;
$companyname = $request->companyname;
$representative = $request->representative;
$phone = $request->phone;
$services = $request-> services;
$applicant = $request->applicant;
$remark = $request->remark;
$updateuserticket = Ticket::where('id','=',$id)->update([
'email' => $email,'typeofservice' =>$typeofservice, 'companyname' => $companyname, 'representative' => $representative,'phone' => $phone,'services' => $services, 'applicant' => $applicant, 'remark' => $remark ]);
$userId = Auth::id();
$last_id = DB::getPdo()->lastInsertId();
if($updateuserticket){
if($request->hasfile('documents')) {
foreach($request->file('documents') as $doc)
{
$name = $doc->getClientOriginalName();
$destinationPath = 'public/documets/';
if(File::exists($destinationPath)){
File::delete($destinationPath);
}
$documentPath = date('YmdHis') . "." . $doc->getClientOriginalExtension();
$doc->move($destinationPath, $documentPath);
Document::create([
'doc_name' => $name,
'doc_path' => $documentPath,
'user_id' => $userId,
'ser_id' => $last_id,
]);
}
}
$ticket_details = DB::table('ticket')->where('id','=',$last_id)->first();
//$users = User::where('id','=',$ticket_details->user_id)->first();
//$ticketid = $ticket_details->ticket_id;
//$username = $users->first_name.' '.$users->last_name;
return redirect('showtickets')->with('success','Ticket Updated Successfully!');
}
}
for view
#foreach( $documents as $doc )
<div class="col-md-6">
<input id="documents" type="file" class="form-control" name="documents[]" value="" required>
<img src="{{ url('/') }}/public/documets/{{ $doc->doc_path }}" alt="user-img" class="img-width" style="width:30px;height:30px;">
</div>
#endforeach
This one update only details not able to update documents can you please guid anyone where i am wrong
I updated and image is showed after that, but i need to delete the previous image (from folder) after updating with the new one.
//update
public function edit ($id)
{
$user = User::find($id);
// $user = User::where('id', $id)->first();
// $user = DB::table('users')->where('id', $id)->first();
return view('edit', compact('user'));
}
public function postEdit (Request $request) {
request()->validate([
'email' => 'required',
'fullname' => 'required',
'birthday' => 'required',
'address' => 'required|min:10',
]);
$image = $request->image;
// dd($image);
$id = $request->id;
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$birthday = $request->birthday;
$country = $request->country;
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$img = $file_name.".".$image->getClientOriginalExtension();
User::where('id',$id)->update([
'image' => $img,
'email' => $email,
'fullname' => $fullname,
'birthday' => $birthday,
'address' => $address,
'country' => $country,
]);
return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
}
You can use File facade to delete a file:
use Illuminate\Support\Facades\File;
$pathToFile = base_path('public/img/'.$user->image);
File::delete($pathToFile);
You should first find the user and determine if he already has an image, sou you can delete it from the storage. Do it like this:
public function postEdit (Request $request) {
request()->validate([
'email' => 'required',
'fullname' => 'required',
'birthday' => 'required',
'address' => 'required|min:10',
]);
$user = User::where('id', $request->id)->first();
if($user->image){ //Check if user has image and delete it from storage
if (Storage::exists($user->image)) {
Storage::delete( $user->image ); //Dont forget to use your real paths. $user->image should be a path to an image.
}
}
$image = $request->image;
$id = $request->id;
$email = $request->email;
$fullname = $request->fullname;
$address = $request->address;
$birthday = $request->birthday;
$country = $request->country;
//Insert new image
$image = $request -> file('image');
$destination = base_path().'/public/img';
$file_name = rand(100,1).date('h-i-s');
$image->move($destination, $file_name.".".$image->getClientOriginalExtension());
$img = $file_name.".".$image->getClientOriginalExtension();
//Now update user
$user->update([
'image' => $img,
'email' => $email,
'fullname' => $fullname,
'birthday' => $birthday,
'address' => $address,
'country' => $country,
]);
return Redirect::to("dashboard")->withSuccess('Great! You have Successfully edited');
}
I'm trying to make two functions in controller that have post action and that are in the same page.
My Controller
public function store(Request $request)
{
$status = DB::table('analytics')->where('dienstleistung', '!=', '')->get();
//Save data
$rules = [
'site_id' => 'required',
'dienstleistung' => 'required',
'objekt' => 'required',
'zimmer' => 'required',
'vorname' => 'required',
'name' => 'required',
'strasse' => 'required',
'ort' => 'required',
'plz' => 'required',
'tel' => 'required',
'email' => 'required|email',
'reinigungstermin' => 'required',
'gekommen' => 'required',
'message' => 'required',
'status' => 'required',
'answer' => 'required',
'notiz' => 'required',
'userId' => 'required',
];
$validator = Validator::make(Input::all(), $rules);
if($validator->fails()) {
return Redirect::to('anfrage')
->withErrors($validator)
->withInput();
}
else {
$anfrage = new Analytic();
$anfrage->site_id = Input::get('site_id');
$anfrage->dienstleistung = Input::get('dienstleistung');
$anfrage->objekt = Input::get('objekt');
$anfrage->zimmer = Input::get('zimmer');
$anfrage->vorname = Input::get('vorname');
$anfrage->name = Input::get('name');
$anfrage->strasse = Input::get('strasse');
$anfrage->ort = Input::get('ort');
$anfrage->plz = Input::get('plz');
$anfrage->tel = Input::get('tel');
$anfrage->email = Input::get('email');
$anfrage->reinigungstermin = Input::get('reinigungstermin');
$anfrage->gekommen = Input::get('gekommen');
$anfrage->message = Input::get('message');
$anfrage->status = Input::get('status');
$anfrage->answer = Input::get('answer');
$anfrage->notiz = Input::get('notiz');
$anfrage->userId = Input::get('userId');
try {
$anfrage->save();
flash()->success(trans('app.success'));
return Redirect::to('anfrage');
} catch (\Exception $e) {
Log::writeException($e);
return Redirect::to('anfrage')
->withErrors($e->getMessage())
->withInput();
}
}
}
public function editItem(Request $request) {
$anfrages = Analytic::find($request['id'] );
$anfrages->status = $request->status;
$anfrages->answer = $request->answer;
$anfrages->notiz = $request->notiz;
$anfrages->save();
return response ()->json( $anfrages );
}
My route:
Route::post('anfrage', 'AnfrageController#store');
Route::post ( 'anfrage', 'AnfrageController#editItem' );
EditItem function is OK, it makes changes when I want to edit data, but when I want to store data, message being displayed is:
creating default object from empty value
So, I need to leave active only one of these function, both are not working.
I have a 2 table user and reports
Report model
public function user() {
return $this->belongsTo('App\User', 'author_id');
}
User model
public function reports() {
return $this->hasMany('App\Report', 'author_id');
}
In User model there is a column called "sum_sales"
In Report model there is a column called "total"
Ho can I pass the sum(total) from my Report model to 'sum_total' inside my User model?
My report controller
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$field_total = $request->input('total');
$sum_total = $report->sum('total');
$totalSum = $field_total + $sum_total;
$report->author_id->sum_sales = $totalSum;
$report->save();
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}
With this the browser say:
Indirect modification of overloaded property App\Report::$author_id has no effect
How can I figure out?
solved by Giedrius Kiršys
public function store(Request $request)
{
$this->validate($request, ['title' => 'required',
'date' => 'required|date_format:d/m/Y|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/',
'image_1' => 'required|mimes:png,jpeg',
'products' => 'required',
'total' => 'required',
'time' => 'required|min:2',
'location' => 'required',
'sub_location' => 'required',
]);
$user = Auth::user()->id;
$report = new Report($request->all());
$report->author_id = $user;
$image = $request->file('image_1');
$destinationPath = 'uploads/reports';
$ext = $image->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$ext;
$report->image_1 = $image->move($destinationPath, $fileName);
$report->save();
$sumUserTotal = User::find($user)->reports->sum('total');
Auth::user()->update(['sum_sales' => $sumUserTotal]);
Session::flash('flash_message', 'Report added!');
return redirect('dash/reports');
}