when I send data from form to database
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'fypp.joblisting' doesn't exist (SQL: select count(*) as aggregate from `joblisting` where `email` = )
this error occurs. In my database joblistings table exists but laravel looking for the singular name instead of the plural table name. Even I have created new model with new migration and everything but still facing this issue.
model code
class Joblisting extends Model
{
use HasFactory;
protected $fillable = [
'title',
'category',
'company',
'email',
'level',
'number',
'description',
];
}
controller code
class JoblistingController extends Controller
{
public function showForm()
{
return view('frontend.pages.addjob');
}
public function createjob(Request $request)
{
$this->validate($request,[
'title'=> 'required|string',
'category'=> 'required',
'company' =>'required',
'email' => 'required|unique:joblisting',
'level' => 'required',
'number' => 'required',
'description' => 'required',
]);
Joblisting::create([
'title' => $request->title,
'category' => $request->category,
'company'=> $request->company,
'email'=> $request->email,
'level'=> $request->level,
'number'=> $request->number,
'description'=> $request->description,
]);
return redirect('viewlist')->with('success', 'job posted successfully');
}
}
migration code
class CreateJoblistingsTable extends Migration
{
public function up()
{
Schema::create('joblistings', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->string('category');
$table->string('company');
$table->string('email');
$table->string('level');
$table->string('number');
$table->string('description');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('joblistings');
}
}
You have to use like this
'email' => 'required|unique:joblistings',
Laravel uses snake case, hence:
Fix 1:
use controller name as JobListingController
Fix 2:
in your model, add tthe following line:
protected $table = 'joblistings';
Related
Sorry if this is something really simple but I haven't been able to find an answer after hours of searching...
I have this object with relations:
$this->versionSelected = new StyleVersions();
$this->versionSelected = StyleVersions::with([
'colourways.colourway_yarns.yarns.spinners',
])->find($id);
Which is edited using wire:model:
wire:model="versionSelected.name"
and then verified:
protected $rules = [
'versionSelected.name' => 'required',
'versionSelected.factories_id' => 'required',
'versionSelected.yarn_transportation_cost' => 'required',
'versionSelected.yarn_transportation_currency' => 'required',
'versionSelected.accessories_cost' => 'required',
'versionSelected.accessories_currency' => 'required',
'versionSelected.transport_cost' => 'required',
'versionSelected.gmt_transportation_currency' => 'required',
'versionSelected.cmt' => 'required',
'versionSelected.gmt_weight' => 'required',
'versionSelected.area_office_commission' => 'required',
'versionSelected.notes' => 'required',
'versionSelected.style_version_prices' => 'required',
];
I then want to save that object to the database, but it is having issues with the relations.
$this->versionSelected->save();
When this is called I get the followin error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'style_version_prices' in 'field list' (SQL: update style_versions set style_version_prices = [{"id":10,"style_versions_id":4,"price":54.7,"notes":"Quo dolorum ab dolores.","created_at":"2022-02-25T10:19:23.000000Z","updated_at":"2022-02-25T10:19:23.000000Z"},{"id":18,"style_versions_id":4,"price":75,"notes":"Voluptatibus aut nihil.","created_at":"2022-02-25T10:19:23.000000Z","updated_at":"2022-02-25T10:19:23.000000Z"},
Is there a way I can update without it looking at the relations, which I can update separately? Thanks in advance! =D
EDIT:
Here is the code for the style_versions table:
Schema::create('style_versions', function (Blueprint $table) {
$table->id();
$table->foreignId('styles_id')->constrained()->onDelete('cascade');
$table->foreignId('factories_id')->constrained()->onDelete('cascade');
$table->text('name')->nullable();
$table->float('yarn_transportation_cost');
$table->float('gmt_weight');
$table->float('cmt');
$table->float('accessories_cost');
$table->float('transport_cost');
$table->text('notes')->nullable();
$table->float('area_office_commission')->default(0);
$table->float('yarn_cost');
$table->text('cmt_currency')->nullable();
$table->text('accessories_currency')->nullable();
$table->text('yarn_transportation_currency')->nullable();
$table->text('gmt_transportation_currency')->nullable();
$table->timestamps();
});
And the model:
class StyleVersions extends Model
{
use HasFactory;
protected $fillable = [
'styles_id',
'factories_id',
'yarn_transportation_cost',
'gmt_weight',
'cmt',
'accessories_cost',
'transport_cost',
'area_office_commission',
'notes',
'cmt_currency',
'accessories_currency',
'yarn_transportation_currency',
'gmt_transportation_currency',
'yarn_cost',
];
public function styles()
{
return $this->belongsTo(Styles::class);
}
public function factories()
{
return $this->belongsTo(Factories::class);
}
public function colourways()
{
return $this->hasMany(Colourways::class);
}
public function style_version_prices()
{
return $this->hasMany(StyleVersionPrices::class);
}
}
This is a continuation of my last question.
I like to create a relationship between a user (with an account type that’s equal to a “profile”) and my job posts. What I did was create a relationship like this in my models (not sure if correct tho)
User.php
public function jobposts()
{
$this->hasMany(JobPost::class)->where('account_type', 'profile');
}
JobPost.php
public function userprofile()
{
$this->belongsTo(User::class)->where('account_type', 'profile');
}
JobPostController.php
public function store(Request $request)
{
$this->validate($request, [
'job_name' => 'required|max:100',
'describe_work' => 'required|max:800',
'job_category' => 'required|not_in:0',
'city' => 'required|not_in:0',
'state' => 'required|not_in:0',
'zip' => 'required|regex:/\b\d{5}\b/',
]);
dd(auth()->user()->jobpost()->job_name);
}
2021_11_20_211922_create_job_posts_table.php
Schema::create('job_posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->contrained()->onDelete('cascade');
$table->string('job_name');
$table->text('describe_work');
$table->string('job_category');
$table->timestamps();
});
Got 2 questions about what I can do in the JobPostController.php.
How do I dd() to test the output?
This seems wrong
dd(auth()->user()->jobpost()->job_name);
How do I add it correctly into the DB like this?
public function store(Request $request)
{
$request->user()
->jobpost()
->create([
'job_name' => $request->job_name
]);
}
I am using Laravel 8 and trying to get an application form to post to two tables in my database
From my 2 database migration files:
public function up() {
Schema::create('applicants', function (Blueprint $table) {
$table->id();
$table->string('apptitle');
$table->string('firstname');
$table->string('middlename')->nullable();
...
$table->timestamps();
});
}
public function up() {
Schema::create('applications', function (Blueprint $table) {
$table->id();
$table->integer('applicant_id');
$table->integer('user_id');
$table->integer('loanAmount');
$table->string('loanTerm');
...
$table->timestamps();
});
}
Models:
class Applicant extends Model {
use HasFactory;
protected $table = 'applicants';
protected $fillable = [
'apptitle', 'firstname', 'middlename'...
];
public function application() {
return $this->hasOne(Application::class);
}
}
class Application extends Model {
use HasFactory;
protected $table = 'applications';
protected $fillable = [
'applicant_id',
'user_id',
'loanAmount',
'loanTerm',
...
];
public function applicant() {
return $this->belongsTo(Applicant::class);
}
}
Controllers:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\Applicants\CreateApplicantRequest;
class ApplicantsController extends Controller {
...
public function store(CreateApplicantRequest $request) {
$applicant = Applicant::create([
'apptitle' => $request->apptitle,
'firstname' => $request->firstname,
'middlename' => $request->middlename,
...
]);
}
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Application;
use App\Models\Applicant;
use App\Models\User;
use App\Http\Requests\Applications\CreateApplicationRequest;
class ApplicationsController extends Controller {
...
public function store(CreateApplicationRequest $request) {
$application = Application::create([
'applicant_id' => $request->applicant_id,
'user_id' => 'required',
'loanAmount' => 'required',
'loanTerm' => 'required',
...
]);
}
}
Requests:
public function rules() {
return [
'apptitle' => 'required',
'firstname' => 'required',
'middlename',
...
];
}
public function rules() {
return [
'applicant_id' => 'required',
'user_id' => 'required',
'loanAmount' => 'required',
'loanTerm' => 'required',
...
];
}
web.php
Route::get('applicants','ApplicantsController#store');
Route::resource('applications', 'ApplicationsController');
Route::get('applications/{application}', 'ApplicationsController#show');
I am continually getting errors: The applicant id field is required. (If I make this field nullable the form does successfully post all other fields to the database.)
This is my first big Laravel project so any help would be greatly appreciated.
Update:
I have gone through the answers provided and am still getting the same error.
I feel the main issue is - when the form is filled out the applicant_id field for the newly created Applicant is not being captured and added to the applications table?
You can store data from one form into 2 tables like this.
Remove use App\Http\Requests\Applicants\CreateApplicantRequest; from your ApplicationsController and run the following cmd commands:
composer dump-autoload
php artisan cache:clear
php artisan config:clear
php artisan view:clear
php artisan route:clear
These commands clear all cache from your project.
Add nullable to your application migration applicant_id:
$table->integer('applicant_id')->nullable();
I finally was able to get my form posting correctly to both databases - a big thank you to all those that have helped me in this journey.
This is my updated store function in my ApplicationsController:
public function store(CreateApplicationRequest $request, Applicant $applicant)
{
$applicant = Applicant::create([
'apptitle' => $request->apptitle,
'firstname' => $request->firstname,
'middlename' => $request->middlename,
...
]);
$application = $applicant->application()->create([
'applicant_id' => $applicant->id,
'user_id' => auth()->id(),
'loanAmount' => $request->loanAmount,
'loanTerm' => $request->loanTerm,
...
]);
// redirect the user
return redirect(route('applications.index'));
}
I hope this answer helps someone else out!
I'm studying some Laravel and at some point I had to re-migrate the database because I had to change a table. I'm using postman to do testing, and one of the api methods give me the error:
SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: events.user_id (SQL: insert into "events" ("sport", "title", "players", "when", "description", "location", "updated_at", "created_at") values (Hockey, Grass Hockey, 12, 30/09/2018, Come join us, Fairview park, 2018-11-08 22:19:45, 2018-11-08 22:19:45))
so it seems to be a problem with the events.user_id which I changed on a table called Events to have a relationship with the Users table. Some examples I found by researching is on table fields that were not ids, so I don't how to figure this one out, maybe some of you can help me!
here are the migrations for Events and Users:
public function up()
{
Schema::create('events', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')
->references('id')->on('users')
->onDelete('cascade');
$table->string('sport');
$table->string('title');
$table->decimal('players', 8, 2);
$table->date('when');
$table->mediumText('description');
$table->string('location');
$table->timestamps();
});
}
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
Here are the models:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location'
];
public function user()
{
return $this->belongsTo('App\User');
}
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function events()
{
return $this->hasMany('App\Event');
}
}
And below is the api method that is giving me the error:
Route::post('/admin/create-event', function (Request $request) {
$data = $request->all();
$event = Event::create(
[
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
Thanks guys!
Edit:
Route::middleware('auth:api')->post('/admin/create-event', function (Request $request) {
$user = $request->user();
$data = $request->all();
$event = Event::create(
[
'user_id' => \Auth::user()->id,
'sport' => $data['sport'],
'title' => $data['title'],
'players' => $data['players'],
'when' => $data['when'],
'description' => $data['description'],
'location' => $data['location'],
]
);
return $event;
});
I think you have to add 'user_id' to $fillable of Event class:
class Event extends Model
{
protected $fillable = [
'sport',
'title',
'players',
'when',
'description',
'location',
'user_id'
];
public function user()
{
return $this->belongsTo('App\User');
}
}
You need to pass the user_id:
'user_id' => \Auth::user()->id
The example above requires an authenticated user in the session, but if you are making the request using postman you probably don’t have one.
Anyway, you need to provide the user_id that will be stored in the database.
EDIT
Eloquent's method create will copy to the model only the attributes defined as fillable. So you have two options:
Add user_id to $fillable
Use newInstance instead of create, manually set the user_id with $event->user_id = ..., and manually save the $event model with $event->save();
I am trying to follow this error but I don't know where it is that I need to create purchases. If someone could please help me know how to follow this error I would appreciate it.
Here is my Migration
public function up()
{
Schema::create('purchases', function (Blueprint $table) {
$table->increments('id');
$table->string('product');
$table->string('fname');
$table->string('lname');
$table->string('address');
$table->string('city');
$table->string('state');
$table->integer('zip');
$table->string('card');
$table->timestamps();
});
}
Here is my Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Purchase extends Model
{
public function addPurchase($body)
{
$this->purchases()->create(compact('fName'));
$this->purchases()->create(compact('lName'));
$this->purchases()->create(compact('address'));
$this->purchases()->create(compact('city'));
$this->purchases()->create(compact('state'));
$this->purchases()->create(compact('zip'));
$this->purchases()->create(compact('card'));
}
}
edit: I am trying to push all the above date to a mySQL database
Here is my controller store function
public function store(Purchase $purchase)
{
$this->validate(request(), ['fName' => 'required|min:3']);
$this->validate(request(), ['lName' => 'required|min:3']);
$this->validate(request(), ['address' => 'required']);
$this->validate(request(), ['city' => 'required']);
$this->validate(request(), ['state' => 'required']);
$this->validate(request(), ['zip' => 'required']);
$this->validate(request(), ['card' => 'required']);
$purchase->addPurchase(request('fName'));
$purchase->addPurchase(request('lName'));
$purchase->addPurchase(request('address'));
$purchase->addPurchase(request('city'));
$purchase->addPurchase(request('state'));
$purchase->addPurchase(request('zip'));
$purchase->addPurchase(request('card'));
return back();
}
As we've established in the comments, the error happens because $purchase variable in the controller is an instance of a Purchase query builder. And in your ->addPurchase() {...} method you're calling $this->purchase(), which is a nonexistant method on a query builder.
Now how to make this work. There's a lot of ways.
One would be to manually assign all properties to the model and call ->save() afterwards:
public function store(Purchase $purchase)
{
// ... validation
// Assign the properties
$purchase->fname = request('fName');
$purchase->lname = request('lName');
$purchase->address = request('address');
$purchase->city = request('city');
$purchase->state = request('state');
$purchase->zip = request('zip');
$purchase->card = request('card');
$purchase->save(); // Save to the database
return back();
}
Another would be to use mass assignment:
public function store(Purchase $purchase)
{
// ... validation
$purchase->forceCreate(request()->only([
'fName', 'lName', 'address', 'city', 'state', 'zip', 'card',
]));
return back();
}
Using forceCreate(...), which is same as ->create(...) except that it bypasses the $fillable array, which in this specific instance is OK, since a) we're manually telling it which fields are to be filled, with request()->only([fields]) b) you're performing validation before saving.
And there are more ways to do this, most of them well documented.
One last thing I would recommend is to perform validation with (technically) 1 line:
public function store(Purchase $purchase)
{
$this->validate(request(), [
'fName' => 'required|min:3',
'lName' => 'required|min:3',
'address' => 'required',
'city' => 'required',
'zip' => 'required',
'card' => 'required',
]);
// Save the model...
}
This way you would get all the errors (if something doesn't pass) in an array, rather than only the first one that didn't pass.