move() function not working in laravel 5.2 while editing/updating pictures - laravel

I have a founder page where the user can upload name, information and image of the founder.
In my view when I edit pictures and upload a new one, the name of the pictures gets stored in the database but the image is not being uploaded. There must be some problem in my controller but i can't seem to find out what. Any help would be appreciated.
Below are my model, controller and view.
Founder Model
class Founder extends Model
{
protected $fillable = ['name','information', 'image'];
public function getImageAttribute()
{
if (! $this->attributes['image']) {
return 'noimage.jpg';
}
return $this->attributes['image'];
}
public function getCreatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
public function getUpdatedAtAttribute($date)
{
return Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $date)->format('Y-m-d');
}
Founder Controller
public function update(Request $request, $id)
{
$founder = Founder::find($id);
$input = $request->all();
if($file=$request->file('image'))
{
$name = $file->getClientOriginalName();
$file->move('/images/', $name);
$input['image']= $name;
}
$founder->update($request->all());
return redirect()->route('founder.view');
}
Founder View Edit Form
<form class="form-horizontal" action="/founders/{{$founder->id}}" method="POST">
{{csrf_field()}}
<input type="hidden" name="_method" value="PUT">
<div class="form-group">
<label class="col-md-12">Name</label>
<div class="col-md-12">
<input type="text" name="name" class="form-control" value="{{$founder->name}}">
</div>
</div>
<div class="form-group">
<label class="col-md-12">Information</label>
<div class="col-md-12">
<textarea class="form-control" name="information" rows="3" value="{{$founder->information}}">{{$founder->information}}</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-12">Change Image</label>
<div class="col-md-12">
<input type="file" name="image" class="form-control" value="{{$founder->image}}">
</div>
</div>
<button type="submit" name="submit" class="btn btn-success waves-effect waves-light m-r-10">Submit</button>
</form>

Try to use rename:
rename ('current/path/to/foo', 'new/path/to/foo');
Documentation: http://php.net/rename
UPDATE:
Or use variable $destinationPath:
$file->move($destinationPath, $chooseYourFileName);

Use This Method This Will Work 100%
if($request->hasFile('filename')){
$file = $request->filename;
$file_new_name = $file->move("upload/posts/", $file->getClientOriginalName());
$post->filename = $file_new_names;
}
Remember filename is your < img name="filename" >

Related

Get product id to store attachments accordingly

I currently have the add attachment button for each product on the product list page. After clicking the button, will proceed to add attachment form. How do I get the current product ID from the product table in order to store the attachment data into the attachment table?
Route
Route::post('/store/{product}', 'AttachmentController#store')->name('attachment.store');
Product Model
public function attachment()
{
return $this->hasMany(Attachment::class, 'product_id', 'id');
}
Attachment Model
public function product()
{
return $this->belongsTo(Product::class, 'product_id');
}
Controller
public function create()
{
return view('document.create', ['prod' => Product::select('id', 'name')->get()]);
}
public function store(Request $request, Product $product) {
$data['product_id'] = $product->id;
$data = $request->validate([
'file' => 'required',
'file.*' => 'mimes:csv,xlsx,pdf,docx',
]);
$attachmentData = [];
if($request->hasFile('file'))
{
foreach($request->file('file') as $file) {
$path = public_path('storage/attachments/'.$request->product_id);
$fileName = time().'-'.$file->getClientOriginalName();
$file->move($path, $fileName);
$attachmentData[] = $fileName;
}
$data['file'] = json_encode($attachmentData);
}
$attachment = Attachment::create($data);
return redirect()->route('product.index')->with('success','Attachment added successfully');
}
Blade View
<form method="POST" action="{{route('attachment.store')}}" enctype="multipart/form-data">
#csrf
<h3><b>Add Attachment</b></h3>
<input type="submit" class="btn btn-primary mr-2" value="Save">
<div class="row">
<h4 class="card-title">General</h4>
<input type="text" name="product_id" value="{{ $product->id ?? '' }}" hidden>
<div class="form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" required>
</div>
<div class="form-group">
<label>Attachment </label>
<div class="input-group-append">
<label for="attachment" class="btn btn-info">Upload</label>
<input id="attachment" type="file" name="file[]" multiple required>
</div>
</div>
</div>
</form>
You have to use form action like below
<form method="POST" action="{{route('attachment.store',['product'=>$product->id])}}" enctype="multipart/form-data">

laravel 6 : Call to a member function store() on null

I am trying to attach a file to a blog type post. For this i have an file field and 2 buttons, one saves the fields to the database and the other uploads the file. standalone the file upload works as intended. However in the form i get Call to a member function store() on null. I have changed the menthod from put to post, but that doesnt seem have any effect.
Below my post forms and the function in the controllers.
The Form:
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">New/Edit Blog</div>
<div class="card-body">
#if($data)
<form … action = "{{Route ('post.update', $data->_id)}}" method="post", enctype = 'multipart/data'>
#csrf
#method('POST')
<div class="form-group">
<label for="usr">Title:</label>
<input type="text" class="form-control" name="title" value = "{{$data->title}}" >
</div>
<div class="form-group">
<label for="shorttext">Shorttext:</label>
<input type="text" class="form-control" name="shorttext" value = "{{$data->shorttext}}" >
</div>
<div>
<input id="x" type="hidden" name="content" value ="{{$data->content}}">
<trix-editor input="x" ></trix-editor>
</div>
<div class="form-group">
<label for="created_by">Created By:</label>
<input type="text" class="form-control" name="created_by" value = "{{$data->created_by}}" readonly>
</div>
<input type="file" name="attachment" enctype="multipart/form-data"/>
<p align="center">
<input type="submit" btn btn-primary class="btn btn-primary" id="save" name="action" value="save">
<input type="submit" btn btn-primary class="btn btn-primary" id="upload" name="action" value="upload">
The functions in the controller:
Store:( this one is the function that determines which button is pressed)
public function store(Request $request, $_id = false, $attachment = false){
//check which submit was clicked on
if($request->action == 'upload'){
//
$this->upload($request);
return redirect()->route('home');
} elseif($request->action == 'save') {
//echo 'save pressed';
//run function save all form fields
$this->update($request, $_id);
return redirect()->route('home');
} else {echo "error";}
}
Upload function:
function upload(Request $request){
$path = $request->file('attachment');
// $original = $request->file('attachment')->getClientOriginalName();
$path->store('/public');
Update function:
public function update (Request $request, $_id){
//$this->upload($request);
/*
$path = $request->file('attachment');
$path->storeas('/public','123'); */
$data = post::findOrFail($_id);
$data->title = $request->title;
$data->content = $request->content;
$data->shorttext = $request->shorttext;
$data->created_by = $request->created_by;
$data->text3 = $request->text3;
$data->attachment = $request->attachment;
$data->save();
if($data){
return redirect()->route('home');
}else{
return back();
}
}
The route is:
Route::post('/post/update/{_id}', 'PostController#store')->name('post.update');
As mentioned, the save function in the complete form works. In a standalone form ( and a standalone controller) the upload works (and i can, if i wish, manipulate the filename), but how do i bring the 2 together? At first i thought it was because the update form had a PUT method, but changing everything to post doesnt seem to have any effect and i still get the Null error.
For completeness the standalone solution:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Te7aHoudini\LaravelTrix\Pipes\AttachmentInput;
class UploadController extends Controller
{
//
function upload(Request $req){
$path = $req->file('attachment');
$original = $req->file('attachment')->getClientOriginalName();
$path->storeas('/public',$original);
echo $original;
}
}
The standalone form:
<html>
<head>
<title>Upload</title>
</head>
</html>
<form action="upload" method="POST" enctype="multipart/form-data">
<input type="file" name="attachment" />
#csrf
<button type="submit">file upload</button>
</form>
In your form element Change enctype = 'multipart/data' to enctype="multipart/form-data"
<form … action = "{{ Route ('post.update', $data->_id) }}" method="post", enctype="multipart/form-data">
Hope this solves your problem.

How to edit image and update in laravel

I have a table called Services, now this table has the following -
-id
-title
-body
-image
-slug
-timestamps
And in administrator, services page I created for Add, Edit, Delete it.
My problem is edit and update a image. A strange problem is that, when I change the of image to aaaaa field in the service table (database), Nothing happens. should happen. because I changed rename of image to aaaaa.
web.php
Route::resource('services', 'ServiceController');
ServiceController.php
public function edit(Service $service)
{
return view('Admin.services.edit', compact('service'));
}
public function update(Request $request, Service $service)
{
$service->title = $request->title;
$service->body = $request->body;
if($request->has('image')) {
$image = $request->file('image');
$filename = $image->getClientOriginalName();
$image->move(public_path('images/services'), $filename);
$service->image = $request->file('image')->getClientOriginalName();
}
$service->update();
return redirect()->route('services.index');
}
edit.blade.php
<form class="form-horizontal" action="{{ route('services.update', $service->id) }}" method="post" enctype="multipart/form-data">
{{ csrf_field() }}
{{ method_field('PATCH') }}
#include('Admin.layouts.errors')
<div class="form-group">
<label for="title">عنوان</label>
<input type="text" class="form-control" id="title" name="title" placeholder="عنوان" value="{{ $service->title ? : old('title') }}">
</div>
<div class="form-group">
<label for="body">متن</label>
<textarea class="form-control" rows="10" id="body" name="body" placeholder="متن">{{ $service->body ? : old('body') }}</textarea>
</div>
<div class="form-group">
<label for="images">تصویر</label>
<div class="custom-file">
<input type="file" class="custom-file-input" id="images" name="images">
<label class="custom-file-label" for="images">تصویر محصول</label>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">ذخیره</button>
</div>
</form>
Service.php
protected $fillable = [
'title',
'body',
'image',
'slug',
];
I even changed the controller in the update method as follows, nothing happened.
$service->save();
I think one of efficient way to edit image in laravel.
add this at top of the controller
use File;
First of get your bannerId in a variable
$bannerId = $request->banner_id;
get object of that id by find ().
$bannerData = FrontEndBanner::find($bannerId);
check if file exist and check if file already exist then delete that file else same name will inserted in imageName variable
if ($request->hasFile('banner_image')){
$image_path = public_path("/uploads/resource/".$bannerData->banner_name);
if (File::exists($image_path)) {
File::delete($image_path);
}
$bannerImage = $request->file('banner_image');
$imgName = $bannerImage->getClientOriginalName();
$destinationPath = public_path('/uploads/resource/');
$bannerImage->move($destinationPath, $imgName);
} else {
$imgName = $bannerData->banner_name;
}
$bannerData->title = $request->banner_title;
$bannerData->banner_name = $imgName;
$bannerData->save();
If anyone have issue then comment
In the html you have:
<input type="file" class="custom-file-input" id="images" name="images">
and in Controller: $request->file('image').
Replace
<input type="file" class="custom-file-input" id="images" name="images">
with
<input type="file" class="custom-file-input" id="images" name="image">

Update on "user" and "technicien" with one to one connection

I have two tables user and technician with one to one connection, technician inherits from user. After editing technician information through edit form and saving no update happens on tables user and technician. and no errors as well.
Here is my code:
Controllers
public function edit($id)
{
$technicien=technicien::find($id);
$user = $technicien->user;
return view('technicien.edit',['technicien'=>$technicien])->with('user',$user);
}
public function update(Request $request, $id)
{
// do some request validation
$technicien=technicien::find($id);
$technicien->update($request->all());
$technicien->user->update($request->get('user'));
$user->nom = $request->update('nom');
return redirect('/technicien');
}
View
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien->technicien ) }}" method="update">
{{csrf_field()}}
{{ method_field('PATCH') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control" name="user[nom]" value="{{$user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control" name="user[prenom]" value="{{$user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form- control" name="user[email]" value="{{$user->email}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="moyenne_avis" class="form-control" value ="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="actif" class="form-control" value ="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-control btn btn-primary">
</div>
</div>
</form>
</div>
</div>
#endsection
Route.php
Route::get('/technicien/{id}/edit', 'TechnicienController#edit');
Route::patch('/technicien/{id}', 'TechnicienController#update')->name('technicien.update');
Model1
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class technicien extends Model
{
protected $fillable = [
'moyenne_avis', 'actif',
];
use SoftDeletes;
protected $guarded = [];
protected $dates = ['deleted_at'];
public function zoneintervention()
{
return $this->belongsToMany('App\zoneintervention','technicien_zone','technicien_id','zoneintervention_id');
}
public function metier()
{
return $this->belongsToMany('App\metier','technicien_metier','technicien_id','metier_id');
}
public function user()
{
return $this->belongsTo('App\User');
}
public function tarificationtache()
{
return $this->belongsToMany('App\tarificationtache','technicien_tarificationtache','technicien_id','tarificationtache_id');
}
}
Model2
<?php
namespace App;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public function technicien()
{
return $this->hasOne('App\technicien');
}
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'email', 'password','nom','prenom','tel','mobil','role',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
controler
public function edit($id)
{
// better to use findOrFail (it will throw an exception about missing
objects)
$technicien = technicien::findOrFail($id);
return view('technicien.edit', compact('technicien'));
}
public function update(Request $request, $id)
{
$technicien=technicien::findOrFail($id);
$technicien->user->update($request->get('user'));
$technicien->update($request->get('technicien'));
return redirect('/technicien');
}
and the view
#extends('Layouts/app')
#extends('Layouts.master')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-10">
<h1>Modifier Technicien</h1>
<form action="{{ route('technicien.update', $technicien ) }}"
method="post">
{{csrf_field()}}
{{ method_field('patch') }}
<div class="form-group">
<label for="nom">Nom</label>
<input id="nom" type="text" class="form-control"
name="user[nom]" value="{{$technicien->user->nom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[prenom]" value="{{$technicien->user->prenom}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[tel]" value="{{$technicien->user->tel}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[mobil]" value="{{$technicien->user->mobil}}" >
</div>
<div class="form-group">
<label for="prenom">Prenom</label>
<input id="prenom" type="text" class="form-control"
name="user[role]" value="{{$technicien->user->role}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control"
name="user[email]" value="{{$technicien->user->email}}" >
</div>
<div class="form-group">
<label for="prenom">Email</label>
<input id="prenom" type="text" class="form-control"
name="user[password]" value="{{$technicien->user->password}}" >
</div>
<div class="form-group">
<label for="">moyenne Avis</label>
<input type="text" name="technicien[moyenne_avis]"
class="form-control" value="{{$technicien->moyenne_avis}}" >
</div>
<div class="form-group">
<label for="">Etat Technicien</label>
<input type="text" name="technicien[actif]"
class="form-control" value="{{$technicien->actif}}" >
</div>
<div class="form-group">
<input type="submit" value="enregistrer" class="form-
control btn btn-primary">
</div>
</form>
</div>
</div>
</div>
#endsection
Try to do with One to One relation.
Make relation for user table and technician table, then try to do update.
Try this in controller
$user = User::with('technicien')->find($id);
$data['id'] = $id;
$data = $this->validate($request, [
'moyenne_avis' => 'required',
]);
$user->technicien()->whereUserId($data['id'])->update(['moyenne_avis' => $data['moyenne_avis']
]);
return redirect('/technicien')->with('Success', 'Records updated');
Also change form method as below in ur view.blade
<form action="{{ action('TechnicienController#update', $user->id) }}" method="post">
also, instead of {{ method_field('PATCH') }} use this <input name="_method" type="hidden" value="PATCH">
Note: Table name should be plural for controller and model name.
eg: Table name: users
Controller name: UserController
Model name: User
Make sure this same in urs too.

How to display selected value and image in edit page to perform update operation using laravel

Hello,
I am new learner in Laravel and my first post in Stackoverflow so applogy to me for my mistake and English language.
I can create a project shoppingcart & perform CRUD operation where create product information such as product name, brand, description, price & image. I can done create & read operation easily. Below my product list that can be show in browser
enter image description here
When I click edit button browser can show like that below image to perform edit operation
enter image description here
where brand name & image can't shown edit product form
My productController code below like that
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\brand;
use App\Product;
use Illuminate\Support\Facades\DB;
class productController extends Controller
{
public function index(){
$product = DB::table('products')
->join('brands','products.brandID','=','brands.brandID')
-> select('products.*','brands.brandName')
->get();
return view('admin.product.productList',compact('product'));
}
public function create()
{
$product = brand::pluck('brandName','brandID');
return view('admin.product.createProduct',compact('product'));
}
public function store(Request $request)
{
// image upload
$product = $request->except('image');
$image = $request->image;
if ($image) {
$imageName = $image->getClientOriginalName();
$image->move('images', $imageName);
$product['image'] = $imageName;
}
Product::create($product);
return view('admin.product.productList', compact('product'));
}
public function show($id)
{
$product = Product::find($id);
return view('admin.product.editProduct',compact('product'));
}
public function edit($id)
{
}
public function delete($id){
$product= Product::find($id);
$data=$product->delete();
return view('admin.product.productList',compact('data'));
}
}
my editProduct.blade file code below like that
#extends('layouts.master')
#section('content')
<div class="container" align="center">
<div class="col-md-6 col-md-offset-3">
</div>
</div>
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-heading">Edit Product
</div>
<div class="panel-body">
<form action="edit" class="form-horizontal" method="POST>
{{csrf_field()}}
<div class="form-group">
<label for="name" class="col-md-4 control-label">Product Name :</label>
<div class="col-md-6">
<input id="name" type="text" class="form-control" value="{!! $product->productName !!}" name="name" required autofocus>
</div>
</div>
<div class="form-group">
<label for="name" class="col-md-4 control-label">Brand :</label>
<div class="col-md-6">
<select name=" " class="form-control" >
<option>
</option>
</select>
</div>
</div>
<div class="form-group">
<label for="description" class="col-md-4 control-label">Description:</label>
<div class="col-md-6">
<input id="description" class="form-control" name="description" value="{!! $product->description !!}" required>
</div>
</div>
<div class="form-group">
<label for="price" class="col-md-4 control-label">Price:</label>
<div class="col-md-6">
<input id="price" value="{!! $product->price !!}" class="form-control" name="price" required>
</div>
</div>
<div class="form-group">
<label for="image" class="col-md-4 control-label">Image:</label>
<div class="col-md-6">
<input id="image" type="file" value="{!! $product->image !!}" class="btn-btn-default" name="image" value="Upload" required>
</div>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4">
<button type="submit" class="btn btn-primary">
ADD
</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
#endsection
Here, brand name can be selected by HTML select attribute and value get another model Brand & the data can be retrieve from Brand model using join query which is included productController index method.
So how can I show brand name & image to edit in the editProduct blade file. Pls help me
There are couple of ways, here's 1 way.
In your controller.
public function edit($id)
{
$product = Product::find($id);
$data = [
'product_info' => $product
];
return view('your.edit.view.here', $data);
}
And inside your view, inside the FORM Tag, do the looping.
#foreach($product_info as $info)
// data info here
<input id="description" value="{{ $product->description }}" required>
#endforeach
EDIT::
Use Laravel Encryption, you need it especially web apps like shopping cart.
URL:: http://localhost:8000/product/show/encrypted_id_here
public function show($id) {
$id = decrypt($id);
}

Resources