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?
Related
I have a textarea where a user can bulk add clients. In the textarea they would add the clients like this
client 1,client1#domain.com,client username 1
client 2,client2#domain.com,client username 2
client 3,client3#domain.com,client username 3
Here is what I have so far
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$name = $split_row[0];
$email = $split_row[1];
$username = $split_row[2];
$validate = Validator::make($email, [
$email => 'email',
$username => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
What I would like to know is how can I validate that $email is an email or that $username is unique.
The first param of Validator::make should be an array and the second is the rules for the keys of the array.
public function bulkClients()
{
$bulk = request('bulk_clients');
$split = explode("\n",$bulk);
foreach($split as $row)
{
$split_row = explode(",", $row);
$client['name'] = $split_row[0];
$client['email'] = $split_row[1];
$client['username'] = $split_row[2];
$validate = Validator::make($client, [
'email' => 'email',
'username' => 'unique:App\User,username'
]);
if($validate->fails())
{
$messages = $validate->messages();
return response()->json([
'messages' => $messages
]);
}
}
}
You find all available rules in the docs:
$validate = Validator::make([ 'email' => $split_row[1],
'username' => $split_row[2]
], [
'email' => 'string',
'username' => 'unique:App\User,username'
]);
However, for email, I would rather check if its a valid email instead of a string. Thus,
'email' => 'email'
would be recommended.
I would suggest using the validator for the whole array instead of validating it row by row:
$clients = Str::of(request()->get('bulk_clients'))
->explode("\n")
->map(fn ($value) => Str::of($value)->explode(','))
->toArray();
$validator = Validator::make(compact('clients'), [
'clients' => 'array',
'clients.*.0' => 'required|string',
'clients.*.1' => 'required|email',
'clients.*.2' => 'required|unique:App\User,username',
]);
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) }}">
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');
}
Here's my store function. I've tried playing with it a few different ways. For some reason I thought maybe putting the $post->save(); inside the if would at least change the profile image, but no. Not even that works. I initially tried return redirect()->route('profile')->withUser($user); and that didn't work either. This is my latest attempt. And still no luck so I thought to post it here. Thanks in advance! Using: Laravel 5.4
public function store(Request $request)
{
$this->validate($request, array(
'description' => 'required|string',
'projects' => 'required|string',
'experience' => 'required|string',
'links' => 'required|string',
'status' => 'required|string',
));
$userInfo = new User_Info;
$user_id = Auth()->user()->id;
$user = User::find($user_id);
$userInfo->user_id = $user_id;
$userInfo->description = $request->input('description');
$userInfo->projects = $request->input('projects');
$userInfo->experience = $request->input('experience');
$userInfo->links = $request->input('links');
$userInfo->status = $request->input('status');
$userInfo->save();
return redirect()->route('profile')->withUser($user);
}
public function settings($id)
{
$user = User::find($id);
return view("profile.settings")->withUser($user);
}
public function update(Request $request, $id)
{
$user_id = Auth()->user()->id;
$this->validate($request, array(
'first_name' => 'required|string|max:255',
'last_name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'type' => 'required|string',
'description' => 'required|string',
'projects' => 'required|string',
'experience' => 'required|string',
'links' => 'required|string',
'status' => 'required|string'
));
if($request->hasFile('avatar')){
$avatar = $request->file('avatar');
$filename = time() . '.' . $avatar->getClientOriginalExtension();
Image::make($avatar)->resize(300, 260)->save( public_path('/images/uploads/avatars/' . $filename ) );
$user = Auth::user();
$user->avatar = $filename;
}
$user = User::find($id);
$user->first_name = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $request->input('email');
$user->type = $request->input('type');
$user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
$user_info->description = $request->input('description');
$user_info->projects = $request->input('projects');
$user_info->expereince = $request->input('experience');
$user_info->status = $request->input('status');
$user->save();
$user_info->save();
return view('profile.profile')->withUser($user);
}
You don't get existing object, so change this:
$user_info = DB::select("SELECT * FROM user_infos WHERE user_id = $user_id");
To something like this:
$user_info = UserInfo::where('user_id', $user->id)->first();
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');
}