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

I'm working with Laravel on my school project (beginner in programming), and I have an error that I don't know how to solve.
So when I try to add/update something in my table, the following error occurs:
Insomnia POST
the table, model and controller are as follows:
Schema::create('TblAnunUsuario', function (Blueprint $table) {
$table->engine = 'InnoDB';
$table->id('idAnunUser');
$table->string('TituloAnunUser');
$table->string('DescAnunUser');
$table->integer('PrecoAnunUser');
$table->string('RequisitosAnunUser');
$table->string('ImgAnunUser');
$table->char('StatusAnunUser', 1);
$table->dateTime('DataAnunUser');
$table->unsignedBigInteger('idUserAnunUser')->unsigned();
$table->foreign('idUserAnunUser')->references('idUser')->on('TblUsuario');
$table->unsignedBigInteger('idTipoServAnunUser')->unsigned();
$table->foreign('idTipoServAnunUser')->references('idTipoServ')->on('TblTipoServico');
use HasFactory;
public $timestamps = false;
protected $primaryKey = 'idAnunUser';
protected $table = 'TblAnunUsuario';
protected $fillable = ['TituloAnunUser', 'DescAnunUser', 'PrecoAnunUser', 'RequisitosAnunUser','ImgAnunUser', 'StatusAnunUser', 'DataAnunUser', 'idUserAnunUser', 'idTipoServAnunUser'];
public function addAnunUsuario(Request $request)
{
$anunuser = New TblAnunUsuario();
$anunuser->TituloAnunUser = $request->TituloAnunUser;
$anunuser->DescAnunUser = $request->DescAnunUser;
$anunuser->PrecoAnunUser = $request->PrecoAnunUser;
$anunuser->RequisitosAnunUser = $request->RequisitosAnunUser;
$anunuser->ImgAnunUser = $request->ImgAnunUser;
$anunuser->StatusAnunUser = $request->StatusAnunUser;
$anunuser->DataAnunUser = $request->DataAnunUser;
$anunuser->idUserAnunUser = $request->idUserAnunUser;
$anunuser->idTipoServAnunUser = $request->idTipoServAnunUser;
$result = $anunuser->save();
if($result)
{
return response()->json([
'status'=>'200',
'message'=>'Anúncio inserido com sucesso',
]);
} else {
return response()->json([
'status'=>'400',
'message'=>'Falha ao inserir o anúncio',
]);
}
}

first option you have : $table->string('DescAnunUser')->nullable(); and run migration again
And second option you have:
public function addAnunUsuario(Request $request)
{ $request->validate([
'DescAnunUser' => 'required'
]);
$anunuser = New TblAnunUsuario();
$anunuser->TituloAnunUser = $request->TituloAnunUser;
$anunuser->DescAnunUser = $request->DescAnunUser;
$anunuser->PrecoAnunUser = $request->PrecoAnunUser;
$anunuser->RequisitosAnunUser = $request->RequisitosAnunUser;
$anunuser->ImgAnunUser = $request->ImgAnunUser;
$anunuser->StatusAnunUser = $request->StatusAnunUser;
$anunuser->DataAnunUser = $request->DataAnunUser;
$anunuser->idUserAnunUser = $request->idUserAnunUser;
$anunuser->idTipoServAnunUser = $request->idTipoServAnunUser;
$result = $anunuser->save();
if($result)
{
return response()->json([
'status'=>'200',
'message'=>'Anúncio inserido com sucesso',
]);
} else {
return response()->json([
'status'=>'400',
'message'=>'Falha ao inserir o anúncio',
]);
}
}

Related

i wanna check if client name doesn't repeat but doesn't work

public function insertclients(Request $request)
{
$client = new Clients();
$client->client_name = $request->input('client_name');
$client->client_society = $request->input('client_society');
$client->client_email = $request->input('client_email');
$client->client_address = $request->input('client_address');
$client->client_phone = $request->input('client_phone');
$client->client_fix = $request->input('client_fix');
if ($this->nameclient($request->input('client_name')) < 1) {
$client->save();
return response()->json($client);
} else {
return response()->json('error', 'Client name already exists'); }
// return redirect('clients')->with('flash_message', 'Client Addedd!');
}
public function nameclient(Request $request)
{
//check count of client name
$count = Clients::where('client_name', $request->input('client_name'))->get();
$clicount = $count->count();
return $clicount;
}
I have this method for add new client but i wanna check if the name don't repeat so i create other function who check the name of client and i call it in the ferst but doesn't work.
You are already sending the input with $this->nameclient($request->input('client_name')
so change your method to accept a string variable
public function nameclient($clientName)
{
return Clients::where('client_name', $clientName)->count();
}
Bonus:
Maybe this way it would be more readable
public function insertclients(Request $request)
{
if ($this->nameclient($request->input('client_name')) {
return response()->json('error', 'Client name already exists');
}
$client = new Clients();
$client->client_name = $request->input('client_name');
$client->client_society = $request->input('client_society');
$client->client_email = $request->input('client_email');
$client->client_address = $request->input('client_address');
$client->client_phone = $request->input('client_phone');
$client->client_fix = $request->input('client_fix');
$client->save();
return response()->json($client);
// return redirect('clients')->with('flash_message', 'Client Addedd!');
}
You can also use laravel Validation instead of using the method nameclient and add the other validation rules in it like required fields and such.
public function insertclients(Request $request)
{
$request->validate([
'client_name' => 'required|unique:clients|max:255',
]);
$client = new Clients();
$client->client_name = $request->input('client_name');
$client->client_society = $request->input('client_society');
$client->client_email = $request->input('client_email');
$client->client_address = $request->input('client_address');
$client->client_phone = $request->input('client_phone');
$client->client_fix = $request->input('client_fix');
$client->save();
return response()->json($client);
// return redirect('clients')->with('flash_message', 'Client Addedd!');
}

how to fix 500 internal server error in postman using laravel

service provider detail:
class ServiceProviderDetail extends Model {
protected $fillable = [
'working_status', 'booked', 'title', 'experience',
];
public function user()
{
return $this->belongsTo('App\User', 'user_id');
} }
add_booking:
class BookingController extends Controller {
public function addBooking(Request $request) {
//return $request;
$serviceman = ServiceProviderDetail::where('user_id', $request->service_provider_id)->first();
/********* Check if the serviceman is on duty ********/
if($serviceman->working_status !=1){
return response()->json([
'status'=> 0,
'message' => "Sorry pro has logged off duty",
'data' => []
], 200);
}
$serviceman->booked = '1';
if($request->input('subservice_id') == ''){
$service_id = $request->input('service_id');
} else {
$service_id = $request->input('subservice_id');
}
$booking = new Booking;
$booking->customer_id = $request->input('customer_id');
$booking->service_id = $service_id;
$booking->service_provider_id = $request->input('service_provider_id');
$booking->latitude = $request->input('latitude');
$booking->longitude = $request->input('longitude');
$booking->polyline = $request->input('polyline');
$booking->servicing_address = $request->input('servicing_address');
$booking->service_name = $request->input('service_name');
$booking->service_code = $request->input('service_code');
$booking->service_mobile = $request->input('service_mobile');
$booking->service_email = $request->input('service_email');
$booking->service_date = $request->input('service_date');
$booking->service_time = $request->input('service_time');
$booking->status = $request->input('status');
SendNotification::instance()->sendNotification('You have a new service request.',$booking->service_provider_id);
if($booking->save()) {
$serviceman->save();
return response()->json([
'status'=> 1,
'message' => 'Service booked successfully',
'data' => array(
$booking
),
], 200);
}
}
error_log:
emphasized textproduction.ERROR: Trying to get property 'working_status' of non-object {"exception":"[object] (ErrorException(code: 0): Trying to get property 'working_status' of non-object ...../BookingController.php:25)
[stacktrace]
$serviceman = ServiceProviderDetail::where('user_id', $request->service_provider_id)->first();
This is returning null. check if $serviceman is null before caling values

Array to string conversion Laravel upload multiples images

I'm trying to save multiple images of my property, a property can have several images, but I get this error
I would like to know what it produces if you can help me here I leave my controller in the store function
code upload image
public function store(Request $request)
{
/*--from this session you start to save the properties with all their attributes --*/
$properti = new Propertie;
$detail = new Detail;
$detail->antiquity = $request->antiquity;
$detail->furnished = $request->furnished;
$detail->floor = $request->floor;
$detail->save();
$properti->details_id = $detail->id;
$properti->name = $request->name;
$properti->price = $request->price;
$properti->description = $request->description;
$properti->departaments_id = $request->departaments;
$properti->municipalities_id = $request->municipalities;
$properti->property_type_id = $request->type_property;
$properti->offer_type_id = $request->type;
$properti->details_id = $detail->id;
$properti->images = $request->images;
$properti->lat = $request->lat;
$properti->lng = $request->lng;
$properti->address = $request->address;
if (isset($request->property_id)) {
$property_type = $request->property_id;
} else {
$property_type = null;
}
$images=array();
if($files=$request->file('images')){
foreach($files as $file){
$name=$file->getClientOriginalName();
$file->move('image',$name);
$images[]=$name;
}
}
$properti->save();
$piso_id = $properti->id;
$space = new Space;
$space->property_id = $piso_id;
$space->bedrooms = $request->bedrooms;
$space->bathrooms = $request->bathrooms;
$space->parking = $request->parking;
$space->area = $request->area;
$space->save();
$properti->spaces_id = $space->id;
foreach ($request->input('characteristic') as $characteristic) {
$charc = new Characteristic;
$charc->property_id = $piso_id;
$charc->characteristic = $characteristic;
$charc->save();
}
Session::flash('message', 'Se ha registrado su propiedad De forma exitosa');
return redirect()->action('PropertyController#index');
// return view('properties.index',compact('properties'));
}
Migration - Properties
public function up()
{
Schema::create('properties', function (Blueprint $table) {
$table->id();
$table->string('name')->nullable;
$table->string('price')->nullable;
$table->text('description')->nullable;
$table->unsignedBigInteger('property_type_id')->nullable();
$table->unsignedBigInteger('offer_type_id')->nullable();
$table->unsignedBigInteger('spaces_id')->nullable();
$table->unsignedBigInteger('departaments_id')->nullable();
$table->unsignedBigInteger('municipalities_id')->nullable();
$table->unsignedBigInteger('details_id')->nullable();
//$table->unsignedBigInteger('characteristics_id')->nullable();
$table->unsignedBigInteger('images_id')->nullable();
$table->decimal('lat', 8, 5)->nullable;
$table->decimal('lng', 8, 5)->nullable;
$table->string('address')->nullable;
$table->timestamps();
$table->foreign('property_type_id')->references('id')->on('property_type');
$table->foreign('offer_type_id')->references('id')->on('offer_type');
$table->foreign('spaces_id')->references('id')->on('spaces');
$table->foreign('departaments_id')->references('id')->on('departaments');
$table->foreign('municipalities_id')->references('id')->on('municipalities');
$table->foreign('details_id')->references('id')->on('details');
$table->foreign('images_id')->references('id')->on('images');
//$table->foreign('characteristics_id')->references('id')->on('characteristics')->onDelete('cascade');
});
}
Migration images
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->unsignedBigInteger('property_id');
$table->timestamps();
});
}
my property model
public function Images()
{
return $this->hasMany('App\Image', 'images_id');
}
model images
class Image extends Model
{
protected $fillable = ['name', 'property_id'];
public function properties()
{
return $this->belongsTo('App\Properties');
}
}
I don't know if I have something wrong with my controller but it gives me the error before saving it
This is assigning an array to images:
$properti->images = $request->images;
You are then calling $properti->save() which is trying to save that array, which it can't; it will try to convert it to a string, which it can't. So you can comment/remove this line.
If you want to save these via the relationship you can try something like this:
$properti->save();
foreach($files as $file) {
$name=$file->getClientOriginalName();
$file->move('image',$name);
// create a new Image and relate it to the property
$properti->images()->create(['name' => $name]);
}

How to save a JSON response in Database with Laravel Eloquent, I'm getting an error "Array to string conversion"

** Error: "Array to string conversion" **
I'm trying to save a JSON(string) with Eloquent into the database but
I'm getting an error: "Array to string conversion"
I try to add in my model:
protected $casts = ['payload' => 'array'];
or
protected $casts = ['payload' => 'json'];
but is not working!
Controller
try{
if( $type == 'b2c'){
$searchEnquiry = B2CSearchEnquiry::find($enquiryID);
$data = $this->searchInDataSource($searchEnquiry);
$repuveConsult = new B2cRepuveConsult;
$repuveConsult->search_enquiry_id = $enquiryID;
$repuveConsult->payload = (string)$data;
$repuveConsult->saveOrFail();
}
}catch(\Exception $e){
return $e->getMessage();
}
Model
class B2cRepuveConsult extends Model
{
protected $table = ['b2c_repuve_consults'];
protected $fillable = ['search_enquiry_id','information'];
protected $casts = [
'information' => 'array',
];
}
Migration
public function up()
{
Schema::create('b2c_repuve_consults', function (Blueprint $table) {
$table->increments('id');
$table->integer('search_enquiry_id')->unsigned();
$table->longText('payload')->nullable();
$table->timestamps();
});
Schema::table('b2c_repuve_consults', function($table) {
$table->foreign('search_enquiry_id')
->references('id')
->on('b2c_search_enquiries')
->onDelete('cascade');
});
}
A raw query works but is not a good practice since I'm using Laravel
DB::insert('insert into b2c_repuve_consults (search_enquiry_id,payload) values (?, ?)', [$enquiryID, $data]);
I assumed that you've put "payload_Array[]" in view file to get the array or somehow you create array in create method.
B2cRepuveConsult::create([
'....' => '....',
'payload' => json_encode($request->get('payload_Array')); // This is how you save json
'....' => '....',
]);
Reference : https://www.php.net/manual/en/function.json-encode.php
From you're code
try{
if( $type == 'b2c'){
$searchEnquiry = B2CSearchEnquiry::find($enquiryID);
$data = $this->searchInDataSource($searchEnquiry);
$repuveConsult = new B2cRepuveConsult;
$repuveConsult->search_enquiry_id = $enquiryID;
$repuveConsult->payload = json_encode($data); // update this
$repuveConsult->saveOrFail();
}
}catch(\Exception $e){
return $e->getMessage();
}

How to add and update table row in same method using Laravel 5.2

I need to insert data and update a table row in one method in My Controller using Laravel 5.2. My table name is "permission". Here is My method:
public function addPermission(Request $request, $id, Permission $permission)
{
if ($permission = Permission::findOrFail($id));{
$this->validate($request, [
'status' => 'required'
]);
$permission = new Permission;
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$values = $request->all();
$permission->fill($values)->save();
return redirect()->back()->with('info','Permission has been updated to your Collaborator successfully');
}
else {
$this->validate($request, [
'status' => 'required'
]);
$permission = new Permission;
$permission->status = $request->input('status');
$permission->project_id = $id;
$permission->collaborator_id = $request->input('cid');
$permission->save();
return redirect()->back()->with('info','Permission has been added to your Collaborator successfully');
}
}
I get the following error
syntax error, unexpected 'else' (T_ELSE)
What am I doing wrong?
For syntax Erorr
if ($permission = Permission::findOrFail($id)); { ......
Just remove ";"
if ($permission = Permission::findOrFail($id)) { .....

Categories