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

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,
]
);

Related

Cannot call to a public function of Model (Laravel)

I just started learning Laravel, I'm newbie. I've got a problem, I'm watching Laravel Course for beginners and learning, was doing exactly the same as in he tutorial, but still ended up with a problem. I hope to find a solution soon. I'll explain it a little bit.
The project is kind of a clone of Instagram. Users can post images to page.
I have this function in User model
User.php
public function posts()
{
return $this->hasMany(Post::class);
}
And I'm trying to access it from my PostsController
PostsController.php
class PostsController extends Controller
{
public function create()
{
return view('posts.create');
}
public function store()
{
$user = auth()->user();
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image']
]);
auth()->user()->posts()->create($data);
\App\Models\Post::create($data);
dd(request()->all());
}
}
I'm doing exactly as in tutorial, but for some reason this line is failing at posts() call.
auth()->user()->posts()->create($data);
I'm getting that it's undefined method. But it is indeed defined in User.php
EDIT:
Exact error I'm getting is:
Illuminate\Database\QueryException
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: posts.user_id (SQL: insert into "posts" ("caption", "image", "updated_at", "created_at") values (Caption, C:\xampp\tmp\php2E32.tmp, 2021-05-19 12:16:08, 2021-05-19 12:16:08))
And foreign key is user_id.
Actually I just checked my posts table and it seems it is stored in database, so it's working, but how to get rid of this error then?
this is a silly mistake of you..you are adding same post twice. once with relationship association and again from post model.
auth()->user()->posts()->create($data);
\App\Models\Post::create($data); //this is causing the issue here.
with relationship association auth()->user()->posts()->create($data), post is inserted to the database. as the foreign key user_id is coming from relationship. but in the next line \App\Models\Post::create($data), your $data array is missing user_id and thus the NOT NULL constraint failed error occurs. you can't insert a row with user_id being null. and this line is actually adding duplicate data. remove this line. use either one of the method.
with relationship association
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image']
]);
auth()->user()->posts()->create($data);
or using model directly
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image']
]);
$data['user_id'] = auth()->user()->id; //added user_id in the validated data array
\App\Models\Post::create($data);
and vs code always don't know all of your functions. depending on vs code to find a problem is not the best way.
Note:: you need to use Post Model and you can directly create data Using Post::create() method.
//Import Data
use Illuminate\Http\Request;
use App\Modes\Post;
class PostsController extends Controller
{
public function create()
{
return view('posts.create');
}
public function store(Request $request)
{
//Check Validation
$data = request()->validate([
'caption' => 'required',
'image' => ['required', 'image']
]);
//Get Login User Data in $user variable
$user = auth()->user();
//Store user id into $data variable which we can pass into $data Variable.
$data[‘user_id’] = $user->id;
//Create Data Using create() method.
$post = Post::create($data);
//Final Save Your Data
if( $post->save() ) {
dd(“data save successfully”);
}else{
dd(“something went wrong”);
}
}
}

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);

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

SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value laravel 5.5

I'm staring with Laravel and I'm having troubles trying to make a simple insert, but It seems that all of my fillable fields are not being included. This is the error:
SQLSTATE[HY000]: General error: 1364 Field 'name' doesn't have a default value
(SQL: insert into `addresses` (`updated_at`, `created_at`)
values (2017-12-25 09:31:49, 2017-12-25 09:31:49))
As you can see, only created_at and updated_at are about to be inserted, I thought that maybe I forgot my fillable vars, but this is my Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model
{
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
}
And the Controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Addresses;
use App\Customers;
class AddressesController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function store(Request $request){
$create = Addresses::create([
'name' => request('name'),
'city' => request('city'),
'suburb' => request('suburb'),
'street' => request('street'),
'o_number' => request('o_number'),
'i_number' => request('i_number'),
'postal_code' => request('postal_code'),
'phone_s' => request('phone_s'),
'email_s' => request('email_s'),
'google_map' => request('google_map'),
'customer_id' => Customers::where('code',$request->session()->get('customer_code'))->first()->id
]);
$success = $create ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
}
}
Echo the request() values works! So I'm missing right now, I have some other Models and Controller working good in the same way. Please Help!
This error show because you the NAME field is required on your database. Try to edit your migration script and put default value on this field or make it nullable.
eg.
$table->string('name')->nullable();
OR
$table->string('name')->default('');
Then run a migration refresh.
Goto "phpmyadmin" >> "Variables" then find "sql_mode" edit and remove "STRICT_ALL_TABLES or STRICT_TRANS_TABLES"
It is working for me.
Hope it will help for All.
This is late answer for this question, but it might help for others.
This error can be occurred due to error in $fillable data in modal.
You can try using
protected $guarded = []
instead of
protected $fillable = [
'name',
'city',
'suburb',
'street',
'o_number',
'i_number',
'postal_code',
'phone_s',
'email_s',
'google_map',
'customer_id'
];
But You have to validate the data that you passed within the controller.
The error occurs due to the strict mode of MYSQL5.7. Please change your config/database.php in the connections.mysql section by putting 'strict' => false.
I solved it using save()
$addresses = new Addresses;
$customer_id = Customers::where('code',$request->session()->get('customer_code'))->first()->id;
$addresses->name = $request->name;
$addresses->city = $request->city;
$addresses->suburb = $request->suburb;
$addresses->street = $request->street;
$addresses->o_number = $request->onumber;
$addresses->i_number = $request->inumber;
$addresses->postal_code = $request->postal_code;
$addresses->phone_s = $request->phone_s;
$addresses->email_s = $request->email_s;
$addresses->google_map = $request->map;
$addresses->customer_id = $customer_id;
$success = $addresses->save() ? $request->session()->flash('success', '¡Registro exitoso!') : $request->session()->flash('success', 'Ooops! Algo salio mal :(');
return redirect('addresses/'.$request->session()->get('customer_code'));
It's working properly
When you use the nullable() method on a field, that field will default to NULL.
For example, add this to your migration file:
$table->string('name')->nullable();
Update:
You can add:
$table->string('name')->nullable()->default(null);
You can check Null option in table structure, like this -
Make sure request() has key 'name'.Replace request('name') to random string and try again.
In my case I forgot to change - this is my code on my Controller
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->name = $request->input('message');
$message->save();
}
I made a duplication of the 'name' that's why it happened and made this
public function store(Request $request)
{
$message = new Message();
$message->name = $request->input('name');
$message->message = $request->input('message');
$message->save();
}
This way the solution to the problem.
I was having this problem because I didn't add a correct column under $fillable list.
class Chirp extends Model
{
use HasFactory;
protected $fillable = [
'message', // This line should be added.
];
}

PHP Laravel Framework Uploading Image Form Processing

I'm trying to learn to an process image form that uploads images to a database and lets users view the image on the website, this is done using Laravel 4. I must have some sort of bug, because the view doesn't have any errors, but when I select an image to upload and hit the "save" button on my form, nothing happens other than it looks like the form has been refreshed because the file is gone.
Routes
// This is for the get event of the index page
Route::get('/', array(
'as' => 'index_page',
'uses' => 'ImageController#getIndex'
));
// This is for the post event of the index page
Route::post('/', array(
'as' => 'index_page_post',
'before' => 'csrf',
'uses' => 'ImageController#postIndex'
));
ImageController.php
class ImageController extends BaseController {
public function getIndex()
{
// Let's first load the form view
return View::make('tpl.index');
}
public function postIndex()
{
// Let's validate the form first with the rules which are set at the model
$input = Input::all();
$rules = Photo::$upload_rules;
$validation = Validator::make($input, $rules);
// If the validation fails, we redirect the user to the index page, with errors
if ($validation->passes()) {
// If the validation passes, we upload the image to the database and process it
$image = Input::file('image');
// This is the original uploaded client name of the image
$filename = $image->getClientOriginalName();
// Because Symfony API does not provide filename
// without extension, we will be using raw PHP here
$filename = pathinfo($filename, PATHINFO_FILENAME);
// We should salt and make an url-friendly version of the file
$fullname = Str::slug(Str::random(8) . $filename) . '.' .
$image->getClientOriginalExtension();
// We upload the image first to the upload folder, then
// get make a thumbnail from the uploaded image
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
// If the file is now uploaded we show a success message
// otherwise, we show an error
if ($upload) {
// image is now uploaded, we first need to add column to the database
$insert_id = DB::table('photos')->insertGetId(
array(
'title' => Input::get('title'),
'image' => $fullname
)
);
// Now we redirect to the image's permalink
return Redirect::to(URL::to('snatch/'.$insert_id))
->with('success', 'Your image is uploaded successfully!');
}
else {
// Image cannot be uploaded
return Redirect::to('/')->withInput()
->with('error', 'Sorry, the image could not be uploaded.');
}
}
else {
return Redirect::to('/')
->withInput()
->withErrors($validation);
}
}
Image Model
class Photo extends Eloquent {
// the variable that sets the table name
protected $table = 'photos';
// the variable that sets the table name
protected $fillable = array('title', 'image');
// the timestamps enabled
public $timestamps = true;
// Rules of the image upload form
public static $upload_rules = array(
'title' => 'required|min:3',
'image' => 'required|image'
);
}
The view for the form
#extends('frontend_master')
#section('content')
{{ Form::open(array('url' => '/', 'files' => true )) }}
{{ Form::text('title', '', array(
'placeholder' => 'Please insert your title here')) }}
{{ Form::file('image') }}
{{ Form::submit('save', array('name' => 'send')) }}
{{ Form::close() }}
#stop
Let me know if you can find any bugs, I'm pretty sure something must be going wrong in my ImageController#postIndex
Thanks for any insights
2 things you need to check out.
1st off, once you updated your composer.json to include the Intervention/Image package. you should run composer dump-autoload to refresh the autoload file.
2ndly, there's a logical error in your controller.
Image::make(Config::get('image.thumb_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
should be
Image::make(Config::get('image.image_folder').'/'.$fullname)
->resize(Config::get('image.thumb_width'), null, true)
->save(Config::get('image.thumb_folder').'/'.$fullname);
because you've already moved the image file to image_folder with the code below:
$upload = $image->move
(Config::get('image.upload_folder'), $fullname);
Hope this helps.

Categories