I'm setting up a CRUD, similar to an ecommerce
I uploaded the image, it is stored in the public folder. The name of the image is replaced by the value of an input that the user places. This same value is saved in the database with the image extension.
I was also able to delete the image, but I don't know how to update it. Can someone please give me a light?
project controller:
public function store(Request $request)
{
$nameFile = $request->input('imageName', '');
if($request->file('imageFile')->isValid()){
$nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
$request->file('imageFile')->storeAs('projects', $nameFile);
}
$project = new Project();
$project->name = $request->input('name');
$project->price = $request->input('price');
$project->imageName = $nameFile;
$project->save();
return redirect()->route('ProjectControllerCreate');
}
public function destroy($id)
{
$project = Project::find($id);
// Image
$filePathName = public_path().'/storage/projects/'. $project->imageName;
if( file_exists($filePathName) ){
unlink($filePathName);
}
// Data
if(!$project)
return redirect()->back();
$project->delete();
return redirect()->route('ProjectControllerCreate');
}
public function update(Request $request, $id)
{
$project = Project::find($id);
if(!$project)
return redirect()->back();
$project->update($request->all());
return redirect()->route('ProjectControllerCreate');
}
This is how you can update :
use Illuminate\Support\Facades\Storage;
public function update(Request $request, $id)
{
$project = Project::find($id);
if(!$project)
return redirect()->back();
// Update new image
if($request->file('imageFile')->isValid()){
// Delete old image
$old_image = $project->imageName;
Storage::delete($old_image);
$nameFile = $request->input('imageName', '');
$nameFile .= '.' . $request->file('imageFile')->getClientOriginalExtension();
$request->file('imageFile')->storeAs('projects', $nameFile);
$project->imageName = $nameFile;
}
$project->name = $request->input('name');
$project->price = $request->input('price');
$project->save();
return redirect()->route('ProjectControllerCreate');
}
Related
When i store a new record, Laravel returns the new record. Everything works fine.
When i update a record, Laravel returns the old record. I like to return the updated record.
Controller
public function store(StoreProjectRequest $request)
{
$data = $this->repo->create( $request->all());
return response()->json(new ProjectResource($data));
}
public function update(UpdateProjectRequest $request, Project $project)
{
$data = $this->repo->update($project, $request->all());
return response()->json(new ProjectResource($data));
}
Repository
public function create( $data)
{
$this->model->name = $data['name'];
$this->model->description = $data['description'];
$this->model->sales_order_id = $data['sales_order_id'] ? $data['sales_order_id'] : NULL;
$this->model->project_leader_id = $data['project_leader_id'];
$this->model->project_type_id = $data['project_type_id'];
$this->model->project_status_id = $data['project_status_id'];
$this->model->creator_id = Auth()->id();
$this->model->save();
return $this->model;
}
public function update($model, $data)
{
$model->name = $data['name'];
$model->description = $data['description'];
$model->sales_order_id = $data['sales_order_id'];
$model->project_leader_id = $data['project_leader_id'];
$model->project_type_id = $data['project_type_id'];
$model->project_status_id = $data['project_status_id'];
$model->save();
return $model;
}
When i add $data = Project::find($project->id)i receive the updated model.
But is this the only way?
The reason the $data is returning as the old data is because it still stores the data from when the variable was created. When you call $data->fresh() it will go fetch the new data and return it. Does that make sense?
I have an issue while updating the user. When I try to update the user after clicking the save button then it redirect me to the same page and not throwing me any error but also its not updating anything in the database. Below is my code. I have no idea what's going on here. Help me :)
Controller
public function update(ReportRequest $request, $id)
{
$report = Report::findOrFail($id);
$input = $request->all();
if ($file = $request->file('photo_id')) {
$name = time() . $file->getClientOriginalName();
$file->move('images', $name);
$photo = Photo::create(['file' => $name]);
$input['photo_id'] = $photo->id;
}
$report->update($input);
return redirect()->back();
}
Route
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
'edit'=>'admin.reports.edit',
]]);
Models
class Report extends Model
{
protected $fillable = [
'student_id',
'student_name',
'class_id',
'subject',
'teacher_name',
'report_categories_id',
'total_marks',
'obtained_marks',
'percentage',
'position',
'photo_id',
];
public function photo() {
return $this->belongsTo('App\Photo');
}
public function studentsClass() {
return $this->belongsTo('App\StudentsClass', 'class_id');
}
public function student() {
return $this->belongsToMany('App\Student');
}
}
Make sure you have your $fillable properties in your Photo and Report models, otherwise the create() and update() methods won't work as expected.
Check the $fillable fields in the Model as above. If the error persists check your laravel log on storage/logs/laravel.log.
In controller:
public function update(ReportRequest $request, $id){
$report = Report::findOrFail($id);
$input = $request->all();
try{
if ($request->photo_id != '') {
$path = 'images/';
$file = $request->photo_id;
$name = time() . $file->getClientOriginalName();
$file->move($path, $name);
$photo = Photo::create(['file' => $name]);
$report->update(['photo_id' => $photo->id]);
}
return redirect()->back();
}catch(\Exception $e){
return redirect()->back()->with('error_message', $e->getMessage());
}
}
public function update(Request $request, $id)
{
$house = House::find($id);
$house->name = $request->name;
$house->code = $request->code;
$house->description = $request->description;
$house->address = $request->address;
$house->owner_name = $request->owner_name;
$house->manager_name = $request->manager_name;
if($house->update()){
return redirect()->route('houses')
->with('alert.status', 'success')
->with('alert.message', 'Successfully Updated.');
}
else{
return redirect()->route('houses')
->with('alert.status', 'danger')
->with('alert.message', 'Try Again.');
}
}
Here i want to update all my fields except code when the code already exists in the database.How can i do that please give some solution.Thank you in advance.
You can use the null coalescing operator, available in php version 7.
In short, you can do this:
public function update(Request $request, $id)
{
$house = House::find($id);
$house->code = $house->code ?? $request->code;
$house->save();
}
If $house->code is different from null, this will be used if it will not use $request->code.
https://www.tutorialspoint.com/php7/php7_coalescing_operator.htm
do this way with ternary condition :
public function update(Request $request, $id)
{
$house = House::find($id);
$house->code = !empty($house->code) && $house->code!= NULL ? $house->code : $request->code;
}
Use a if :
public function update(Request $request, $id)
{
$house = House::find($id);
$house->name = $request->name;
if($house->code == NULL)
$house->code = $request->code;
$house->description = $request->description;
$house->address = $request->address;
$house->owner_name = $request->owner_name;
$house->manager_name = $request->manager_name;
$house->save();
if($house->update()){
return redirect()->route('houses')
->with('alert.status', 'success')
->with('alert.message', 'Successfully Updated.');
}
else{
return redirect()->route('houses')
->with('alert.status', 'danger')
->with('alert.message', 'Try Again.');
}
}
You should use the save() method after you made all this changes.
You can check for code existence on database by Eloquent: Mutators like below on your House Model
class House extends Model
{
//your codes
public function setCodeAtrribute($value)
{
if ($this->attributes["code"] != null) $this->attributes["code"] = $value
}
}
You can also check here for more information
I have the following controller whenever i hit submit it redirects me to sales. Where as it should return admin.invoice.index page rather than sale.index. can any one please help?
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$product = new Product;
$product->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$data[]['sales'] = $sales;
$data[]['product'] = $product;
}
$data = [];
if ($request->session()->has('data')) {
$data = $request->session()->get('data');
}
Session::flash('success', 'Sale is successfully');
return view('admin.invoice.index')->with('data', $data);
}
Pass the data with with() through session.
{
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$p = new Product;
$p->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$product = Product::where('id', '=', $request['product_id'][$i])->first();
$data[$i]['sales'] = $sales;
$data[$i]['product'] = $product;
}
Session::flash('success', 'Sale is successfully');
return redirect('/invoice')->with('data', $data);
}
Then, Make a new route -
Route::get('/invoice', function(\Illuminate\Http\Request $request){
$data = [];
if ($request->session()->has('data')) {
$data = $request->session()->get('data');
}
return view('admin.invoice.index')->with('data', $data);
});
#Sohel0415
My Sales Controller is like this.
public function index()
{
$sales = Sale::orderBy('id', 'DESC')->get();
return view('admin.sales.index', compact('sales'));
}
public function create()
{
$products = Product::pluck('name', 'id', 'qty')->toArray();
return view('admin.sales.create', compact('products'));
}
public function store(Request $request)
{
$data = array();
for ($i=0; $i < count($request['product_id']); ++$i)
{
$sales= new Sale;
$sales->product_id = $request['product_id'][$i];
$sales->qty= $request['qty'][$i];
$sales->user_id = Auth::user()->id;
$sales->save();
$product = new Product;
$product->where('id', '=', $request['product_id'][$i])->decrement('stock', $request['qty'][$i]);
$data[]['sales'] = $sales;
$data[]['product'] = $product;
}
Session::flash('success', 'Sale is successfully');
return view('admin.invoice.index')->with('data', $data);
}
admin.invoice.index
#extends('layouts.master')
#section('content')
#foreach($data as $d)
{{$d['sales']}}
{{$d['product']}}
#endforeach
#endsection
My web.php or routes:
Route::resource('categories', 'CategoriesController');
Route::resource('products', 'ProductsController');
Route::resource('sales', 'SalesController');
How do I get an image stored in a field of my database, and put it into a variable for using it in an email message like a signature?
Here is my code:
//Model user_model
function getImage(){
$this->db->select("image");
$this->db->where("$id", user_id);
$query = $this->db->get("users");
if($query->num_rows()>0){
return result();
}else{
return false;
}
}
//Controller user_controller
function image(){
this->load->model("user_model");
$id = $this->session->userdata('id');
$image = $this->user_model->getImage($id);
echo $image;
}
Here is a example
Model user_model
// Pass the id function
function getImage($id){
$this->db->where($id, 'user_id');
$query = $this->db->get("users");
if($query->num_rows()>0){
return $query->row_array();
}else{
return false;
}
}
Controller user_controller
function image(){
$this->load->model("user_model");
$somedata = $this->user_model->getImage($this->session->userdata('id'));
$data['image'] = $somedata['image'];
$this->load->view('someview', $data);
}
On view
<?php echo $image;?>