image isn't saving into db in laravel - laravel

hi m trying to save data into db data saves but image isn't saving how to save it in db:
controller:
public function store(Request $request)
{
// dd($request->all());
$request->validate([
'category_name' => 'required',
'category_description' => 'required',
'category_slug' => 'required',
'category_image' => 'required|image',
]);
DB::table('categories')->insert([
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'category_slug' => $request->category_slug,
'category_image' => $request->category_image,
]);
$path = $request->file('category_image');
$path->getClientOriginalName();
$path->move(public_path('images/backend_images/category_images');
return back();
}

Well... In your portion of code, there is no var.save(); so how will eloquent store any data without the given instruction?
Per example do something like this:
$userImage = new UserImage;
$UserImage->save();

public function store(Request $request)
{
// dd($request->all());
$request->validate([
'category_name' => 'required',
'category_description' => 'required',
'category_slug' => 'required',
'category_image' => 'required|image',
]);
$path = $request->file('category_image');
$nameImage = $path->getClientOriginalName();
$path->move(base_path('public/images/backend_images/category_images'), $nameImage);
DB::table('categories')->insert([
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'category_slug' => $request->category_slug,
'category_image' => $nameImage,
]);
return redirect()->back();
}
code in my project and its work!
if ($request->hasFile('image')) {
$file = $request->file('image');
$filename = date('mdYHis') .str_random(5).'.'.$file->extension();
$request->image->move(base_path('public/images/rooms'), $filename);
$request->merge(array('image' => $filename));;
}

I think this would help. But you can browse for more answers.
Save to public directory
$path = 'images/backend_images/category_images';
$file = $request->file('category_image');
$filename = $file->getClientOriginalName();
$file->move(public_path($path), $filename);
And the, save to database
DB::table('categories')->insert([
'category_name' => $request->category_name,
'category_description' => $request->category_description,
'category_slug' => $request->category_slug,
'category_image' => $filename
]);

Related

how to save pdf with original file name (Laravel)

How can i upload a file and save the file using using original file name ?
Here my controller code ?
public function store(Request $request)
{
//Validate request data
$request->validate([
'name' => 'required',
'file' => 'required|mimes:pdf|max:50000',
'category' => 'required',
'year' => 'required|integer'
]);
$file = $request->file
$filename = Storage::disk('public')->putFile('regulations', $file);
Document::create([
'name' => $request->name,
'file' => $filename,
'category' => $request->category,
'year' => $request->year
]);
//redirect with success
return redirect()->back()->with('success', 'Done!');
}
Try this
$file = $request->file('file');
$file->getClientOriginalName();

laravel multiple images update function

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

Find duplicates in Laravel Eloquent

The following code I have on the controller is below.
public function add(Request $request)
{
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = new ProjectResearchers();
$researcherToProject->user_id = $request->userSelected;
$researcherToProject->project_id = $request->projectSelected;
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
return new ProjectsResearchersResource($researcherToProject);
}
Should I make another validation or create a function?
Ex: I create a user id "5" with project id "13" and user id "2" with project id "17". If I try creating again a user id "5" with project id "13" it allows me, so I get two times the same data in the database. How do I avoid duplicate entries?
You can do it using updateOrCreate method, the first array is the unique values that you are looking for, if not found it will create the entry, if it finds them it will just update the fields in the second array so do this instead:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::updateOrCreate(
['user_id' => $request->userSelected, 'project_id' => $request->projectSelected],
['created_at' => Carbon::now(), 'updated_at' => Carbon::now()]
);
return new ProjectsResearchersResource($researcherToProject);
}
or if you don't want to update at all, you can just check if it exists before storing:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = new ProjectResearchers();
if( ! ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->exists()) {
$researcherToProject = new ProjectResearchers();
$researcherToProject->user_id = $request->userSelected;
$researcherToProject->project_id = $request->projectSelected;
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
} else {
$researcherToProject = ProjectResearchers::where('user_id', $request->userSelected)->where('project_id', $request->projectSelected)->first();
}
return new ProjectsResearchersResource($researcherToProject);
}
Additionaly to #nakov answer:
firstOrCreate() can combine 2 ways and looks cleaner:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::firstOrCreate([
'user_id' => $request->userSelected,
'project_id' => $request->projectSelected
]);
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
return new ProjectsResearchersResource($researcherToProject);
}
Or if you don't want to update:
public function add(Request $request){
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
$researcherToProject = ProjectResearchers::firstOrCreate([
'user_id' => $request->userSelected,
'project_id' => $request->projectSelected
]);
if(!$researcherToProject->id){
$researcherToProject->created_at = Carbon::now();
$researcherToProject->updated_at = Carbon::now();
$researcherToProject->save();
}
return new ProjectsResearchersResource($researcherToProject);
}
change the following:
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required',
]);
to
$request->validate([
'userSelected' => 'required',
'projectSelected' => 'required|unique:ProjectResearchers,project_id,NULL,id,user_id,'.$request->userSelected
]);
this will work check if the combination of user-project already exists inthe table called ProjectResearchers.
for more information about the unique validation rule visit the Laravel Documentation.

How to assign the value of $filenameTosTor for my 'photo' which is a database column?

What to here ?
how to assign the value of $filenameTosTor for my 'photo' which is a database column?
public function update(Request $request, User $user)
{
$filenameWithExt = $request->file('profile_pic')->getClientOriginalName();
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
Get the Extention
$extention = $request->file('profile_pic')->getClientOriginalExtension();
$filenameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('profile_pic')->storeAs('public/profile_image', $filenameToStore);
$userupdate = User::where('id', $user->id)->update
([
'name' => $request->input('name'),
$user->profile_pic =$filenameToStore;
'photo'=> $request->($filenameToStore);
'last_name' => $request->input('last_name'),
'phone_number' => $request->input('phone_number'),
'address' => $request->input('address'),
'facebook_link' => $request->input('facebook_link'),
'twittr_link' => $request->input('twittr_link'),
'youtube_link' => $request->input('youtube_link'),
'Biography' => $request->input('Biography'),
]);
$userupdate->save();
return redirect('user.index');
}
Just use this variable like this:
'photo' => $filenameToStore,

laravel 5.2 - store multiple value with sum

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');
}

Resources