I'm building an API, i'm getting the following error while updating and deleting from table i'm using postman to test my api
//update error
QueryException in Connection.php line 770:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'title' cannot be null (SQL: update `lessons` set `title` = , `body` = , `completed` = , `updated_at` = 2017-01-03 09:14:10 where `id` = 11)
//delete error
FatalErrorException in LessonsController.php line 80:
Call to a member function delete() on null
My controller LessonsController
<?php
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
class LessonsController extends ApiController {
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer) {
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index() {
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//fetch by id
public function show($id) {
$lesson = Lesson::find($id);
if(! $lesson) {
return $this->respondNotFound();
}
return $this->respond([
'data' => $this->lessonTransformer->transform($lesson)
]);
}
public function store() {
if (! input::get('title') or ! input::get('body')) {
return $this->respondBadRequest();
}
Lesson::create(input::all());
return $this->respondCreated();
}
public function update(Request $request, $id) {
$ulesson = Lesson::find($id);
$ulesson->title = $request->input('title');
$ulesson->body = $request->input('body');
$ulesson->completed = $request->input('completed');
$ulesson->save();
return "Sucess updating user #" . $ulesson->id;
}
public function destroy(Request $request) {
$dlesson = Lesson::find($request->input('id'));
$dlesson->delete();
return "Employee record successfully deleted #" . $request->input('id');
}
}
my model Lesson
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Lesson extends Model
{
protected $fillable = ['title', 'body', 'completed',];
//protected $hidden =['title'];
}
the store and other functions are working fine
Thank You
In update
can you dd($request->input('title')) in line 69
I think you don't sent the value of title
and in delete
I think you have no value in id field
Please check you postman and set it like this
i just downloaded Insomnia and tested every thing is working fine as expected
i don't know why it's not working in postman though
Laravel APi Update Function...
According to this query no need to define keys
Controller Function
`
public function update(Request $request){
$reqdata = $request->all();
$reqdata['date_created'] = date('Y-m-d');
$lesson= Lesson::where('id',$request->id)->update($reqdata);
if ($lesson) {
return 'true';
}else{
return 'false';
}
} `
Your data type as attached image
Related
I'm using laravel website and got this message error while I'm trying to submit the data :
"SQLSTATE[HY000]: General error: 1364 Field 'description' doesn't have a default value (SQL: insert into `tb_desc` (`month_year`, `updated_at`, `created_at`) values (2000 Juni, 2023-02-16 10:09:52, 2023-02-16 10:09:52))"
here my code :
DescriptionController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Description;
class DescriptionController extends Controller
{
public function description_page(Request $request){
$username = $request->session()->get('usernameAdmin');
$logo = $this->getLogo();
$description = Description::all();
$data_count = $this->getDataCount();
return view('admin.desc_award', compact('username', 'data_count', 'description', 'logo'));
}
public function store(Request $request){
if(Description::create($request->all())){
return $this->response(0, 'Description Created Successfull');
} else {
return $this->response(1, 'Failed Created Description');
}
}
public function update(Request $request){
$description = Description::findOrFail($request->id);
if($description->fill($request->all())->save()){
return $this->response(0, 'Description Updated Successfull');
} else {
return $this->response(1, 'Failed Updated Description');
}
}
public function destroy(Request $request){
$description = Description::findOrFail($request->id);
try {
$description->delete();
if( $description ){
return $this->response(0, 'Success Delete Data');
}
} catch (\Exception $e) {
return $this->response(1, 'Failed Delete Data');
}
}
}
Description.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Description extends Model
{
protected $table = 'tb_desc';
protected $fillable = [
'id', 'month_year', 'description', 'description_en', 'description_ja'
];
protected $primaryKey = 'id';
}
is there something wrong with this code?
There are multiple things you can do:
Add default value inside model using attributes as below:
protected $attributes = [ 'description' => 'a default value', ];
Add into the migration default value as below:
$table->text('description')->default('some text');
Make the description field nullable
You can also apply validation to throw an error when description is null.
This error message indicates that you are trying to insert a new record into the tb_desc table in your database, but you have not provided a value for the description field, which does not have a default value set.
To fix this error, you need to make sure that you provide a value for the description field when you insert a new record into the tb_desc table.
3.To make the description column nullable in Laravel, you can modify the migration file for the tb_desc table and add the nullable() method to the description column definition.
Here's an example migration file that modifies the tb_desc table to make the description column nullable:
`enter code here`use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class ModifyTbDescTable extends Migration
{
public function up()
{
Schema::table('tb_desc', function (Blueprint $table) {
$table->text('description')->nullable()->change();
});
}
public function down()
{
Schema::table('tb_desc', function (Blueprint $table) {
$table->text('description')->change();
});
}
}
Once you have modified the migration file, you can run the migration using the php artisan migrate
I am a beginner in laravel. I was updating records but I can't figure out what is wrong with my $student->save();
My controller code is as follows
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;
use PHPUnit\Framework\MockObject\Builder\Stub;
class HomeController extends Controller
{
public function read() {
$students = Student::all();
return view('read',['Students'=>$students]);
}
public function insert() {
return view('insert');
}
public function insertPost(Request $req) {
$student=new Student();
$student->Name = $req->input('name');
$student->Marks = $req->input('marks');
$student->save();
return redirect('/');
}
public function update($id) {
$student = Student::find($id);
return view('update',['Student'=>$student]);
}
public function delete($id) {
$student = Student::find($id);
$student->delete();
}
public function updatePost(Request $req) {
$student = Student::find($req->input('id'));
$student->Name=$req->input('name');
$student->Marks=$req->input('marks');
$student->save();
// Student::where('ID',$req->input('id'))
// ->update(['Name'=>$req->input('name'),
// 'Marks'=>$req->input('marks')]);
return redirect('/');
}
}
The Main main in updatePost(); is causing the records not updating
$student = Student::find($req->input('id'));
$student->Name=$req->input('name');
$student->Marks=$req->input('marks');
$student->save();
I changed the way of updating records to
Student::where('ID',$req->input('id'))
->update(['Name'=>$req->input('name'),
'Marks'=>$req->input('marks')]);
and it worked. But I wanted to know at which part I was making mistake in it.
You need to set your primary key to 'ID'
By default the primary key or PK name is 'id'
But in your code it changed to 'ID'
So you need to go to your User.php model class
and add this line
public $primaryKey = 'ID';
One thing you can try is using Laravel's update method. update will handle the save internally.
$student = Student::findOrFail($req->input('id')));
$student->update([
'Name' => $req->input('name'),
'Marks' => $req->input('marks'),
]);
I have a application that I am trying to add a second Module to.
Basically i'm cloning an existing module that is already working with my database. All code is exactly the same as the original/working module, other than a different table name and different controller/class/model names.
I have 3 new tables that are related to the new module, just like with the old module investments, investment_categories and investment_vendors.
Every time I try to use my new module it wants to upload the vendor and category name value to the investments table when it should be uploading that to the respective investment_categories and investment_vendor tables.
I don't believe the issue is with my new module code, but somewhere else within composer.
I don't expect that I would need to run composer dump-autoload as I've always edited my modules without running that (but this is my first time updating one to query/write to a different table).
Is there something else I need to be running to get this to work?
The below error I see in the log is:
[2018-01-24 21:13:21] production.ERROR: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'category_name' in 'field list' in /var/www//vendor/laravel/framework/src/Illuminate/Database/Connection.php:390
Controller File:
<?php
namespace MC\Modules\Investments\Controllers;
use MC\Http\Controllers\Controller;
use MC\Modules\Investments\Models\Investment;
use MC\Modules\Investments\Models\InvestmentCategory;
use MC\Modules\Investments\Models\InvestmentVendor;
class InvestmentController extends Controller
{
use ReturnUrl;
public function index()
{
$this->setReturnUrl();
$investments = Investment::defaultQuery()
->keywords(request('search'))
->categoryId(request('category'))
->vendorId(request('vendor'))
->sortable(['investment_date' => 'desc'])
->paginate(config('mc.defaultNumPerPage'));
return view('investments.index')
->with('investments', $investments)
->with('displaySearch', true)
->with('categories', ['' => trans('mc.all_categories')] + InvestmentCategory::getList())
->with('vendors', ['' => trans('mc.all_vendors')] + InvestmentVendor::getList())
}
Create Controller File:
<?php
namespace MC\Modules\Investments\Controllers;
use MC\Http\Controllers\Controller;
use MC\Modules\Investments\Models\Investment;
class InvestmentCreateController extends Controller
{
public function create()
{
return view('investments.form')
->with('editMode', false)
->with('currentDate', DateFormatter::format(date('Y-m-d')))
}
public function store()
{
$record = request()->except('attachments');
$record['investment_date'] = DateFormatter::unformat($record['investment_date']);
$record['amount'] = NumberFormatter::unformat($record['amount']);
$record['tax'] = ($record['tax']) ? NumberFormatter::unformat($record['tax']) : 0;
$investment = Investment::create($record);
return redirect($this->getReturnUrl())
->with('alertSuccess', trans('mc.record_successfully_created'));
}
}
Model:
<?php
namespace MC\Modules\Investments\Models;
use Illuminate\Database\Eloquent\Model;
class Investment extends Model
{
use Sortable;
protected $table = 'investments';
protected $guarded = ['id'];
protected $sortable = ['investment_date', 'investment_categories.name', 'description', 'amount'];
public static function boot()
{
parent::boot();
}
/*
|--------------------------------------------------------------------------
| Relationships
|--------------------------------------------------------------------------
*/
public function attachments()
{
return $this->morphMany('MC\Modules\Attachments\Models\Attachment', 'attachable');
}
public function category()
{
return $this->belongsTo('MC\Modules\Investments\Models\InvestmentCategory');
}
public function vendor()
{
return $this->belongsTo('MC\Modules\Investments\Models\InvestmentVendor');
}
/*
|--------------------------------------------------------------------------
| Accessors
|--------------------------------------------------------------------------
*/
public function getAttachmentPathAttribute()
{
return attachment_path('investments/' . $this->id);
}
public function getFormattedAmountAttribute()
{
return CurrencyFormatter::format($this->amount);
}
public function getFormattedTaxAttribute()
{
return CurrencyFormatter::format($this->tax);
}
public function getFormattedInvestmentDateAttribute()
{
return DateFormatter::format($this->investment_date);
}
/*
|--------------------------------------------------------------------------
| Scopes
|--------------------------------------------------------------------------
*/
public function scopeCategoryId($query, $categoryId = null)
{
if ($categoryId)
{
$query->where('category_id', $categoryId);
}
return $query;
}
public function scopeDefaultQuery($query)
{
return $query->select('investments.*', 'investment_categories.name AS category_name',
'investment_vendors.name AS vendor_name', 'clients.unique_name AS client_name')
->join('investment_categories', 'investment_categories.id', '=', 'investments.category_id')
->leftJoin('investment_vendors', 'investment_vendors.id', '=', 'investments.vendor_id');
}
public function scopeVendorId($query, $vendorId = null)
{
if ($vendorId)
{
$query->where('vendor_id', $vendorId);
}
return $query;
}
}
One thing to note is that I do have existing data in the table and the query works fine when viewing it from my web page, however the issue is when trying to edit it or insert new data/record.
As you can see from the model above,
investments.*', 'investment_categories.name AS category_name
the query works because of that command.
I cannot find anywhere else where it determines how to take "investment_categories.name as category_name".
Can you tell me why it is trying to write the category_name value to the investments table instead of the investment_categories table's name column?
I want to validate the input fields before storing the data in database so i went through the laravel docs and followed these
php artisan make:request StoreLessons
in StoreLessons
public function rules()
{
return [
'title' => 'required|unique:lesson',
'body' => 'required',
];
}
in my controller
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
use App\Http\Requests\StoreLessons;
class LessonsController extends ApiController
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index()
{
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//add a new lesson to lessons table
public function store(StoreLessons $request)
{
Lesson::create($request->all());
//Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
}
now i'm getting this error
QueryException in Connection.php line 770:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'laravel_api.lesson' doesn't exist (SQL: select count(*) as aggregate from `lesson` where `title` = the)
i don't know why it's looking for lesson table i have a lessons table
but the store() function works with default validation
//this works fine but i wan to do the validation
public function store()
{
if (! input::get('title') or ! input::get('body')) {
return $this->respondBadRequest();
}
Lesson::create(input::all());
return $this->respondCreated('Lesson created successfully');
}
Thank You
unique:table,column,except,idColumn
The unique syntax goes as above and the first parameter passed is the table name.
public function rules() {
return [ 'title' => 'required|unique:lesson', 'body' => 'required', ];
}
The unique rule here looks for a table lesson. Try changing that to lessons
Please write below line after related model class name like this.
class xyz extends Model
{
protected $table = 'lessons';
code---
}
Try this.
i have created a method to fetch only the soft deleted lessons in my LessonsController
i'm not getting what should be the route my lessoncontroller
<?php
namespace App\Http\Controllers;
use Response;
use App\lesson;
use Illuminate\Http\Request;
use App\Acme\Transformers\LessonTransformer;
use Illuminate\Support\Facades\Input;
class LessonsController extends ApiController
{
protected $lessonTransformer;
function __construct(LessonTransformer $lessonTransformer)
{
$this->lessonTransformer = $lessonTransformer;
}
//fetch all and pass a metadata 'data'
public function index()
{
$lessons = Lesson::all();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
//delete a lesson by id
public function destroy($id)
{
$dlesson = Lesson::find(input::get('id'));
if(! $dlesson) {
return $this->respondNotFound();
}
$dlesson->delete();
return $this->respondDeleted('Lesson deleted successfully');
}
public function deletedLessons()
{
$deleted_lessons = Lesson::onlyTrashed()->get();
return $this->respond([
'data' => $this->lessonTransformer->transformCollection($lessons->all())
]);
}
}
i have tried with a deleted record like
http://localhost:8000/api/v1/lessons/11
Thank You
Make sure:
You've used softDeletes() method in migration and executed this migration
You're using SoftDeletes trait in the model
You've added deleted_at to $dates property in the model
https://laravel.com/docs/5.3/eloquent#soft-deleting
After doing all that your query will work just fine and will return only soft deleted lessons:
$deleted_lessons = Lesson::onlyTrashed()->get();