album-photo laravel gallery. error on updating photos in an album - php

i have been trying to update photos in an album but i cant get it right. i know that i need to get the album id of the photos that i want to update but i cannot get the right logic for the request.
this is the error am getting whenever i request for an update
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'album_id' cannot be null (SQL: update `photos` set `album_id` = , `photo` = IMG-20190527-WA0001_1570703623.jpg, `size` = 275807, `updated_at` = 2019-10-10 10:33:44 where `id` = 197)
the photos model for the application is as shown below
class Photos extends Model
{
protected $fillable = array('album_id', 'description', 'photo', 'title', 'size');
public function album(){
return $this->belongsTo('App\Album');
}
}
this is what i have tried for the update logic in the photosController. i have tried to request for the album id but it does not seem to work
public function edit($id){
$photo = Photos::find($id);
return view('photos/edit')->with('photo', $photo);
}
public function update(Request $request, $id){
$this->validate($request, [
'photo' => 'required | max:15000'
]);
$path = [];
//get filename with extension
$filenameWithExt = $request->file('photo')->getClientOriginalName();
//get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//get extension
$extension = $request->file('photo')->getClientOriginalExtension();
//create new file name
$filenameToStore = $filename.'_'.time().'.'.$extension;
//get file size
$filesize = $request->file('photo')->getClientSize();
$path = $request->file('photo')->storeAs('public/photos'.$request->input('album_id'), $filenameToStore);
$photo = Photos::find($id);
$photo->album_id = $request->input('album_id');
$photo->size = $filesize;
$photo->photo = $filenameToStore;
$photo->save();
return $path;
}
each time i return the path for the photo am updating there is no id for the photo. only happens when i omit the save method
public/photos//IMG-20190527-WA0001_1570706571.jpg
photo edit php view code
{!!Form::open(['action' => ['PhotosController#update', $photo->id], 'method' => 'POST', 'enctype' => 'multipart/form-data'])!!}
{{Form::file('photo')}}
{{Form::hidden('_method','PUT')}}
{{Form::submit('submit')}}
{!! Form::close() !!}
database model for photos table
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->integer('album_id');
$table->string('photo');
$table->string('size');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('photos');
}
help would be appreciated

The error is at this line
$photo->album_id = $request->input('album_id');
You don't have an input in your form with the name album_id
You can either create a hidden one and assign it the value
{!!Form::open(['action' => ['PhotosController#update', $photo->id], 'method' => 'POST', 'enctype' => 'multipart/form-data'])!!}
{{Form::file('photo')}}
{{Form::hidden('_method','PUT')}}
{{-- Here --}}
{{Form::hidden('album_id', $photo->album->id)}}
{{Form::submit('submit')}}
{!! Form::close() !!}
or get it from the relationship like so
$photo->album_id = $photo->album->id;
Note that you're also using that null|empty value here
$path = $request->file('photo')
->storeAs('public/photos'.$request->input('album_id'), $filenameToStore);
So make sure to update that too
Hope this helps

Related

Laravel download files with two tables in database

I hope so im getting close to final stage. I uploading file to storage/files/ and create uniq folder for each upload file with id_message without problem and store file data in table files
Final path of file is /storage/files/{id_message}/{file_name} both variables id_message and file_name are in table files.
FileController function for fileUpload:
function fileUpload(Request $request)
{
$request->validate([
'id_message' => 'required|min:6'
]);
$idParameter = $request->id_message=$request->id_message;
$result=$request->file('file_path')->store('files/'.$idParameter);
$file = new File;
$file->id_message=$idParameter;
$file->file_path=$result;
$file->file_name=$request->file('file_path')->getClientOriginalName();
$file->save();
after upload i have this data in table files:
id id_message file_name
1 000001 Myfile.zip
/storage/app/files/000001/Myfile.zip
FileController : getDownload
public function getDownload($id)
{
$resultFile = DB::table('files')->where('id_message',$id)->first();
$attachment = store_path().'/' . $resultFile->id_message . '/' . $resultFile->file_name;
return response()->download($attachment);
}
route
Route::get('download/{id}/{fileName}', 'FileController#getDownload')->name('downloadFile');
view.blade
<td>Download</td>
error
Undefined variable:resultFile
do i getting closer to finaly download file in laravel ?
controller for view table users
public function postLogin(Request $request)
{
request()->validate([
'id_message' => 'required',
'sms_code' => 'required',
]);
$credentials = $request->only('id_message', 'sms_code');
$request->session()->flash('success','');
if ($user=User::where($credentials)->first()) {
auth()->login($user);
return redirect()->intended('dashboard')->with('success','');
}
return Redirect::to("login")->with(['url_attribute' => $url_attribute,'id_message' => $id_message])->with('error','');
}
public function dashboard()
{
if(Auth::check())
{
return view('dashboard');
}
return Redirect::to("login")->withSuccess('Opps! You do not have access');
}
Leading zeros may be getting stripped if its converted to integer.
Try adding padding to $id once it's passed to getDownload:
str_pad($id, 6, '0', STR_PAD_LEFT);

Laravel - Inserting Empty Value to Database

Hello I would like to insert a null value to my database but i have no clue how to do it is giving an error
How to insert an empty value to input text and set it to null to database, as I do this Im having an error because the rows of the database does not have a value. how can I do this without an error.
here is my error
As you can see I have a foreach loop so inserting 1 input text value returns nothing on the database.
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title'
cannot be null (SQL: insert into awards (title, description,
awards_image, updated_at, created_at) values (, , a:0:{},
2018-11-28 10:29:35, 2018-11-28 10:29:35))
my Controller
public function store(Request $request)
{
$this->validate($request, [
'title' => 'nullable',
'description' => 'nullable',
'awards_image.*' => 'image|nullable|max:1999'
]);
$awards = [];
if ($request->has('awards_image'))
{
//Handle File Upload
foreach ($request->file('awards_image') as $key => $file)
{
// Get FileName
$filenameWithExt = $file->getClientOriginalName();
//Get just filename
$filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $file->getClientOriginalExtension();
//Filename to Store
$fileNameToStore = $filename.'_'.time().'.'.$extension;
//Upload Image
$path = $file->storeAs('public/awards_images',$fileNameToStore);
array_push($awards, $fileNameToStore);
}
$fileNameToStore = serialize($awards);
}
else
{
$fileNameToStore='noimage.jpg';
}
foreach ($awards as $key => $values) {
$awardsContent = new Award;
$awardsContent->title = $request->title[$key];
$awardsContent->description = $request->description[$key];
$awardsContent->awards_image = $values;
$awardsContent->save();
}
}
If you do not want to change the table then try this:
foreach ($awards as $key => $values) {
$awardsContent = new Award;
$awardsContent->title = !empty($request->title[$key]) ? $request->title[$key] : '';
$awardsContent->description = $request->description[$key];
$awardsContent->awards_image = $values;
$awardsContent->save();
}
}
Some more info in empty():
http://php.net/manual/en/function.empty.php
If you are happy to change the table the create a migration where this is in up
Schema::table('awards', function(Blueprint $table) {
$table->string('title')->nullable()->change();
});
of course you will have to change this to what you have already but the important part is ->nullable()->change(); the rest of the line should be the same as your initial migration.
Some more info on migration changes:
https://laravel.com/docs/5.7/migrations#modifying-columns
I hope this helps
Make a new migration
php artisan make:migration fix_title_in_table_awards --table=awards
Then in the migration created first drop the column, and then recreate the column making it nullable..
Schema::table('awards', function (Blueprint $table) {
$table->dropColum('title');
});
Schema::table('awards', function (Blueprint $table) {
$table->string('title')->nullable();
});
Take care of this action because you will lost all the data in that column...maybe you can copy the actual values of title to another column untill you make the change...

"SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'description' cannot be null

I'm using Laravel and trying to build a gallery, i'm testing the upload of a file to a db but i when i click submit i get the error
" Illuminate \ Database \ QueryException (23000)
SQLSTATE[23000]: Integrity constraint violation: 1048 Column
I've set up a GalleryController and the code is as follows
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;
class GalleryController extends Controller
{
// List Galleries
public function index (){
//Render View
return view ('gallery/index');
}
// Show Create From
public function create(){
//Render View
return view ('gallery/create');
}
// Store Gallery
public function store(Request $request){
// Get Request Input
$name = $request->input ('name');
$description = $request->input ('description');
$cover_image = $request->input ('cover_image');
$owner_id = 1;
// Check Image Upload
if($cover_image){
$cover_image_filename = $cover_image->getClientOriginalName();
$cover_image->move(public_path('images'), $cover_image_filename);
} else {
$cover_image_filename = 'noimage.jpg';
}
//Insert Gallery
DB::table('galleries')->insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image,
'owner_id' => $owner_id,
]
);
//Redirect
return \Redirect::route('gallery.index')-> with('message', 'Gallery Created');
}
//Show Gallery Photos
public function show($id){
die ($id);
`
The main.blade.php calls the code using
# if(Session::has('message'))
<div class="alert alert-info">
{{Session::get('message')}}
</div>
# endif;
My .env DB is set to root and password is blank too.
If any more info is needed please advise.
Thanks
I think you have two error:
1) description be null because fo your input was come null or in your view file it has another name
you may do this set default value?
$description = ($request->input ('description')) ? $request->input('description'): "description";
2) your second error is you save temporary image file name
use this instead
//Insert Gallery
DB::table('galleries')->insert(
[
'name' => $name,
'description' => $description,
'cover_image' => $cover_image_filename,
'owner_id' => $owner_id,
]
);

Laravel 5.5 multiple image upload

I try to use dropzoneJS in order to upload multiple image for my products and so far I can save images in database, also in images folder but I have problem with getting product id to relate each image to products.
Here is what I have:
Databases
Products (where my products including info will save)
Images (where my images including product id will save screenshot provided )
Models
Product:
public function images()
{
return $this->morphMany(Image::class, 'imageable');
}
Image:
class Image extends Model
{
protected $fillable = ['name'];
public function imageable()
{
return $this->morphTo();
}
public function product()
{
return $this->belongsTo(Product::class);
}
}
Image Schema
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->increments('id');
$table->integer('imageable_id')->nullable();
$table->string('imageable_type')->nullable();
$table->string('name');
$table->timestamps();
});
}
ImageController
class ImageController extends Controller
{
public function dropzone()
{
return view('dropzone-view');
}
public function dropzoneStore(Request $request)
{
// works
$file = $request->file('file');
$filename = 'product' . '-' . time() . '.' . $file->getClientOriginalExtension();
$filePath = public_path('images/');
$request->file('file')->move($filePath, $filename);
return Image::create([
'name' => $filename,
'imageable_id' => $request->input('imageable_id'),
])->id;
}
}
Product Create (Blade)
// Form
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone mt-20', 'id' => 'my-awesome-dropzone' ]) !!}
<div class="fallback">
<input name="file" type="file" multiple />
</div>
<input type="hidden" name="imageIds[]" value="">
{{Form::close()}}
// Javascript
<script type="text/javascript">
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("form#my-awesome-dropzone", {
headers: {
"X-CSRF-TOKEN": $("meta[name='csrf-token']").attr("content")
},
acceptedFiles: ".jpeg,.jpg,.png,.gif",
dictDefaultMessage: "Drag an image here to upload, or click to select one",
maxFiles: 15, // Maximum Number of Files
maxFilesize: 8, // MB
addRemoveLinks: true,
});
myDropzone.on("success", function (response) {console.log(response.xhr.response); });
</script>
Any idea?
Code for controller:
class ImageController extends Controller
{
public function dropzone($id)
{
$product = Product::find($id);
return view('dropzone-view')
->withProduct($porduct);
}
public function dropzoneStore(Request $request)
{
// works
$file = $request->file('file');
$filename = 'product' . '-' . time() . '.' . $file->getClientOriginalExtension();
$filePath = public_path('images/');
$request->file('file')->move($filePath, $filename);
return Image::create([
'name' => $filename,
'imageable_id' => $request->input('imageable_id'),
])->id;
}
}
Code on blade view:
{!! Form::open([ 'route' => [ 'dropzone.store' ], 'files' => true, 'enctype' => 'multipart/form-data', 'class' => 'dropzone mt-20', 'id' => 'my-awesome-dropzone' ]) !!}
<div class="fallback">
<input name="imageable_id" type="hidden" value="{{$product->id}}" />
<input name="file" type="file" multiple />
</div>
{{Form::close()}}
Try this hope this should get you going. This is one of many way to make this thing work.
this is a morpic relation and this is how you get morphic relation
$post = App\Post::find(1);
foreach ($post->comments as $comment) {
//
}
read about it here polymorphic-relations
What i normally do is,
After you upload a picture, return the ID of the newly created image (you already do that in ImageController)
On your product page, in the dropzone 'success' callback you can read the the image ID and add it to an hidden array input field
In your controller you have to create the new product, and then after saving it , you can attach the images to the correct product, because now you have the id's of the images + the product instance has been made.

Upload file with user id to database

Hi everyone I want to add a file, not an image. There are different types of files in laravel. With the file I need to upload the user id to the database but I don't know how to store it in controller, here are my scripts:
Controller.php:
public function uploaded(Request $request, $id)
{
$client = Client::findOrFail($id);
$path = $request->image->store('storage/uploads','public');
return back();
}
upload.blade.php
{!! Form::open(['action' => ['FileController#upload', $client->id, 'files' => 'true']]) !!}
{!!Form::file('image') !!}
{!!Form::submit('Upload File') !!}
{!! Form::close() !!}
and web.php
Route::post('upload/{id}/', 'FileController#uploaded');
Can you explain me how to do it correctly?
Just change your upload.blade.php as
{!! Form::open(['route' => ['file.upload', $client->id, 'files' => 'true']]) !!}
{!!Form::file('image') !!}
{!!Form::submit('Upload File') !!}
{!! Form::close() !!}
and your web.php to
Route::post('upload/{id}/', 'FileController#uploaded')->name('file.upload');
I little confuse about your question. But I hope my answer can help you with your problem.
First Answer:
If you want to save the file in database I think you can save it with store the file path only in another table, we can call it user_files with this structure:
user_files
| id | user_id | file |
| 1 | 2 | /home/name/file
And the relations between this table and clients table is oneToMany.
so in your Client.php will be have this method:
Client.php
public function files() {
return $this->hasMany(File::class, 'user_id');
}
and your File.php will be have this method:
File.php
public function client() {
return $this()->belongsTo(Client::class, 'user_id');
}
After that, now we move in controller that handle upload method. We should save the file with associate the data from client.
public function uploaded(Request $request, $id)
{
$client = Client::findOrFail($id);
// If you need to upload file not only image, I think you should use $request->file() method;
$file = $request->file('file');
// And then we save the name use this method, maybe you want to save it with change the name and include the user_id
$name = 'User' . '#' . $client->id . '.' . $file->getClientOriginalExtension();
// It will make the file named 'User#2.doc'
// After that we move the file in 'uploads' directory or other public directory you want.
$file->move(public_path('uploads'), $name);
$newFile = new File;
$newFile->file = public_path('uploads') . '/' . $name;
$newFile->client()->associate($client);
$newFile->save();
return back();
}
That if you want to save the file in database with user_id as identifier, and also you can access it as usual, like if you want to access the image file:
<img src="{{$newFile->file}}" />
Second Answer
But if you only want to save the file with the name of user_id you can use only the method in controller:
public function uploaded(Request $request, $id)
{
$client = Client::findOrFail($id);
// If you need to upload file not only image, I think you should use $request->file() method;
$file = $request->file('file');
// And then we save the name use this method, maybe you want to save it with change the name and include the user_id
$name = 'User' . '#' . $client->id . '.' . $file->getClientOriginalExtension();
// It will make the file named 'User#2.doc'
// After that we move the file in 'uploads' directory or other public directory you want.
$file->move(public_path('uploads'), $name);
return back();
}

Categories