Laravel - Inserting Empty Value to Database - php

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...

Related

Problem with multiple image upload in laravel 8

I have to make an online shop website and I have to make multiple image uploads inside my product's form and then display it as a slideshow in my view. I tried 5 tutorials or their concepts and nothing works. I'm so frustrated, so if you guys know anything, hit me up. I'm hoping to find simplest and straight-forward way to store images in database and display them. I'm not good in back-end stuff but I'm trying to learn the ropes.
If you wanna know what I've worked so far is i have two tables linked up which are images and foods. then, images table has a foreign key that will get id from the foods table. That will help the system to know which image is referring to which kind of food. Based on the tutorial that I've have tried so far and the best one I've tried, I got it uploaded in database but the filename only showed []. I've checked inside my public folder too, and I couldn't find the files that I uploaded in there. I tried to display it on view and it throws a messed up error. I was really confused and stressed out just because of this function.
this is the code from my controller (getwelcome is my index):
public function getWelcome(Food $foods)
{
$data = Images::all();
return view('welcome', compact('foods', 'data'));
}
public function store(Request $request)
{
$foods = new Food([
'name' => $request->get('name'),
'description' => $request->get('description'),
'price' => $request->get('price'),
// column name => front-end name
]);
$foods->save();
if ($request->hasfile('filename')) {
foreach ($request->file('filename') as $image) {
$name = $image->getClientOriginalName();
$image->move(public_path() . '/images/', $name); // folder path
$data[] = $name;
}
}
$Upload_model = new Images;
$Upload_model->food_id = $foods->id;
$Upload_model->filename = json_encode($data);
$Upload_model->save();
session()->flash('success', 'Food successfully added.');
return redirect()->route('welcome');
}
image migration
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('food_id');
$table->String('filename');
$table->timestamps();
$table->foreign('food_id')
->references('id')
->on('food')
->onDelete('cascade');
});
in my view
#foreach($data as $image)
#foreach(json_encode($image->filename)as $picture)
<div class="mySlides fade">
<img src="{{ asset('/images'.$picture) }}" style="width:295px; height:295px">
</div>
#endforeach
#endforeach
Your mistake is calling json_encode in your view. The field is already a string, you need to "decode" it out of JSON into something PHP can use:
#foreach (json_decode($image->filename) as $image)
...{{ asset('images/'. $image) }}...
if ($files = $request->file('images')) :
foreach ($files as $file) :
$extension = $file->extension();
$imageName = time() . rand(1, 100) . '.' . $extension;
$file->storeAs('/public/image/product/multiple', $imageName);
$arr[] = $imageName;
endforeach;
$image = implode(",", $arr);
$product->m_image = $image;
else :
$image = '';
endif;

Laravel sync makes a duplicate date in pivot table if multiple images selected

Why does sync makes duplicate sync in the pivot table if i selects more than an image ?
In my application when adding a new competition a user can select one or more images/documents and the file path will be saved in the files table and sync the data into the competition_file pivot table.
Here's the create UI
Here's the store function on my controller
public function store($competition, Request $request, Team $team)
{
if ($request->has('photos') && is_array($request->photos)) {
$files = $this->filesRepo->getByUuids($request->photos);
$fileId = $files->pluck('id')->toArray();
if ($files->isNotEmpty()) {
$forSync = array_fill_keys($fileId, ['competition_id' => $competition,'team_id' => $request->team,'type' => $request->type,'share_type' => $request->share_type]);
$team->documents()->sync($forSync);
}
}
return redirect(route('documents.index',$competition))->with('success', 'Document updated.');
}
Here's the relationship codes in my model
public function documents()
{
return $this->belongsToMany(File::class,'competition_file','team_id','file_id')->wherePivot('type', 'document');
}
When i selectes more than one image as below it makes a duplicate in the competition_file table
This is how it saves in the competition_file pivot table with a duplicate data
But if Dump the data before sync while I have selected two images it shows only two array see below codes
public function store($competition, Request $request, Team $team)
{
if ($request->has('photos') && is_array($request->photos)) {
$files = $this->filesRepo->getByUuids($request->photos);
$fileId = $files->pluck('id')->toArray();
if ($files->isNotEmpty()) {
$forSync = array_fill_keys($fileId, ['competition_id' => $competition,'team_id' => $request->team,'type' => $request->type,'share_type' => $request->share_type]);
dd($forSync);
$team->documents()->sync($forSync);
}
}
return redirect(route('documents.index',$competition))->with('success', 'Document updated.');
}
Result
And if I remove the Dump and reloads the same page it syncs correctly
And if I retry without Dump and if I selects two image and save it creates a duplicate ?
I need to know what might be creating the duplicate sync.
I hope my question is clear, can someone please help me out.
Just for the benefit of subsequent visitors.
public function store($competition, Request $request, Team $team)
{
if ($request->has('photos') && is_array($request->photos)) {
$files = $this->filesRepo->getByUuids($request->photos);
$fileId = $files->pluck('id')->toArray();
if ($files->isNotEmpty()) {
$forSync = array_fill_keys($fileId, [
'competition_id' => $competition,
'type' => $request->type,
'share_type' => $request->share_type
]);
//If the implicit route model binding is not working
//if $team is null or you need to explicitly set the team
//selected by user and which is not passed as route param
Team::findOrFail($request->team)->documents()->sync($forSync);
}
}
return redirect(route('documents.index',$competition))
->with('success', 'Document updated.');
}

Laravel Getting value of another table using foreign key on Blade

I have two models Batch and Notices. The foreign key is correctly formed and data is saved in the database. Now I can't show the data on my listing blade.
Notice Migration:
Schema::create('notices', function (Blueprint $table) {
$table->id();
$table->string('noticeTitle');
$table->string('noticeDesc');
$table->string('file')->nullable();
$table->unsignedBigInteger('batch_id');
$table->foreign('batch_id')->references('id')->on('batches');
$table->timestamps();
});
Batch Migration:
Schema::create('batches', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
Data dump from db is:
"id" => 1
"noticeTitle" => "Quae ea est temporib"
"noticeDesc" => "<p>sa</p>"
"file" => null
"batch_id" => 2
"created_at" => "2020-07-27 16:09:52"
"updated_at" => "2020-07-27 16:09:52"
]
Notice model
public function batches()
{
return $this->belongsTo(Batch::class);
}
Batch Model
public function notice()
{
return $this->hasMany(Notice::class);
}
Notice controller
public function index(){
$notices = Notice::all();
return view('admin.notice.list')
->with('notices', $notices);
}
public function store(Request $request)
{
$this->validate($request, [
'noticeTitle' => 'required',
'noticeDesc' => 'required',
]);
$notice = new Notice;
$notice->noticeTitle = $request->input('noticeTitle');
$notice->noticeDesc = $request->input('noticeDesc');
$notice->batch_id = $request->input('targetedGroup');
if($request->hasFile('file')) {
$noticeTitle = $request->input('noticeTitle');
$filename = $request->file->getClientOriginalName();
$request->file->storeAs('public/noticeFile/additionalFiles', $noticeTitle.'_'.$filename);
$path = $noticeTitle.'_'.$filename;
$notice->file = $path;
}
try{
$notice->save();
Session::flash('success', 'Notice Saved');
return redirect()->route('notice.index');
}
catch (\Throwable $th){
Session::flash('danger', 'Something went wrong');
return redirect()->route('notice.index');
}
}
Now I want to get batch name from batch_id
First, you might want to change the function names of your relationships. Your notice has only one batch, so it should be public function batch() and a batch has several notices, so public function notices().
You can acces your relationships like any attribute, so in your blade:
#foreach($notices as $notice)
#php $batch = $notice->batch; #endphp
{{$batch->name}}
#endforeach
Or even shorter (if you don't plan on using the related batch for anything else)
#foreach($notices as $notice)
{{$notice->batch->name}}
#endforeach
This is all explained in the Laravel documentation: https://laravel.com/docs/7.x/eloquent-relationships

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

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

Issues with saving an image with an article

I'm pretty sure this is a noob question, even though I'm used to PHP, but not to Laravel
My goal can't be any more simple, I'd like to be able to write an article and add an image to it, but even though I made the upload system work (that wasn't a piece of cake), I'm having issues with saving the filename itself.
Here's how I proceeded:
use App\Photo;
use Illuminate\Http\Request;
use Intervention\Image\Facades\Image;
public function store(Request $request)
{
$file = $request->file('image');
$originalname = $file->getClientOriginalName();
$path = 'uploads/' . $originalname;
Image::make($file)->save($path);
$product = new Photo(array(
'name' => $request->get('name'),
'image' => $originalname
));
$product->save();
return \Redirect::route('photo.index', array($product->id))->with('message', 'Product added!');
}
And here is my migration file, if this can help:
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('image');
$table->timestamps();
});
}
So I wanted to save the filename as a string inside the database so I could call it later, like with $product->image, however I'm getting the following error:
SQLSTATE[HY000]: General error: 1364 Field 'image' doesn't have a default value (SQL: insert into `photos` (`name`, `updated_at`, `created_at`) values (sisdjfposd, 2017-05-31 22:42:18, 2017-05-31 22:42:18))
So I know what it means, and I don't like it because it was supposed to have a value: if I add die($originalname);before the line $product = new Photo array(, i get my filename so logically the variable isn't empty.
So why would I have this error? Am i missing something?
Thank you in advance
I think you have missed adding image fields into mass assignment.
In your Photo model just add:
protected $fillable = ['name', 'image'];
More info on mass assignment:
https://laravel.com/docs/5.4/eloquent#mass-assignment

Categories