Laravel - Model attributes stay NULL in database after creation - php

I have a model named Articles which contained three attributes: 'title', 'subtitle' and 'body' and it worked perfectly but after adding four columns to that model ('subtitle2', 'body2', 'subtitle3' and 'body3') the newly added columns stay NULL after creating articles.
There is clearly something that I missed but I can't figure out what.
This is the migration:
public function up()
{
Schema::table('articles', function (Blueprint $table) {
$table->string('subtitle2')->nullable()->default(null);
$table->text('body2')->nullable()->default(null);
$table->string('subtitle3')->nullable()->default(null);
$table->text('body3')->nullable()->default(null);
});
}
After migrating I edited my app/Http/Models/Article.php and it looks like this:
protected $fillable = [
'title',
'subtitle',
'body',
'subtitle2',
'body2',
'subtitle3',
'body3',
];
This is my app/Http/Livewire/CreateArticle.php
class CreateArticle extends Component
{
use WithFileUploads;
public $title;
public $subtitle;
public $body;
public $category;
public $subtitle2;
public $body2;
public $subtitle3;
public $body3;
public $temporary_images;
public $images = [];
public $article;
public function store()
{
$this->validate();
$this->article = Category::find($this->category)->articles()->create($this->validate());
$this->article->user()->associate(Auth::user());
$this->article->save();
if(count($this->images)){
foreach($this->images as $image){
$newImage = $this->article->images()->create(['path'=>$image->store('images', 'public')]);
dispatch(new ResizeImage($newImage->path, 600, 400));
}
}
}
And finally I added these lines to the form:
{{-- INSERT SUBTITLE 2 --}}
<div class="mb-3">
<label for="subtitle2" class="form-label">Second paragraph subtitle</label>
<input type="text" wire:model="subtitle2" class="form-control" id="subtitle2">
</div>
{{-- INSERT PARAGRAPH 2 --}}
<div class="mb-3">
<label for="body2" class="form-label">Second paragraph</label><br>
<textarea class="form-control" wire:model="body2" id="body2" cols="30" rows="3"></textarea>
</div>
{{-- INSERT SUBTITLE 3 --}}
<div class="mb-3">
<label for="subtitle3" class="form-label">Third paragraph subtitle</label>
<input type="text" wire:model="subtitle3" class="form-control" id="subtitle3">
</div>
{{-- INSERT PARAGRAPH 3 --}}
<div class="mb-3">
<label for="body3" class="form-label">Third paragraph</label><br>
<textarea class="form-control" wire:model="body3" id="body3" cols="30" rows="3"></textarea>
</div>
dd($this); is returning the following
Tinker is showing all columns

You need to specify
protected $rules
in order to use
$this->validate()

Assuming the dd(); image you provided is the latest. I can see the new columns does not exists in database. ('subtitle2', 'body2', 'subtitle3' and 'body3') all these are not available in list.
so I think you are missing to run the migrate command
php artisan migrate

Related

Laravel insert data to multiple relational tables with a single form

I'm working on Laravel project and i would like to know:
how to insert data to my multiple related tables ?
How can we insert author id in the author_type_id field of the Author table?
How to store author_id in post?
So idon't know how to insert related models using a form. thanks for your help :)
my models
//Post model
class Post extends Model
{
//
protected $fillable = [
'post_type_id','author_id','author_type_id','article'
];
public function posttype()
{
return $this->belongsTo(Posttype::class);
}
public function author()
{
return $this->belongsTo(Author::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Posttype model
class Posttype extends Model
{
//
protected $fillable = [
'post_type'
];
public function posts()
{
return $this->hasMany(Post::class);
}
}
//author model
class Author extends Model
{
//
protected $fillable = [
'author_name','author_first_name','author_type_id'
];
public function posts()
{
return $this->belongsToMany(Post::class);
}
public function authortype()
{
return $this->belongsTo(Authortype::class);
}
}
//Authortype model
class Authortype extends Model
{
//
protected $fillable = [
'author_type '
];
public function author()
{
return $this->hasMany(Author::class);
}
public function posts()
{
return $this->hasMany(Post::class);
}
}
// PostsController Contoller
class PostsController extends Controller
{
public function index()
{
return view('index')->with('posts',Post::all());
}
public function create()
{
return view('create')->with('posttypes',$posttypes)
->with('authors',$authors)
->with('authortypes',$authortypes);
}
public function store(Request $request)
{
$this->validate($request,[
"post_type_id" => "required",
"author_id" => "required",
"author_type_id" => "required",
"article" => "required"
]);
//How can we insert author id in the author_type_id field of the Author table?
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $request->author_id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
return redirect()->back();
}
}
//create post blade
#section('content')
<div class="container">
<form action="{{route('store')}}" method="POST" enctype="multipart/form-data">
{{ csrf_field()}}
<div class="form-group">
<label for="posttype">Post Type</label>
<select class="form-control" id="posttype" name="post_type_id">
#foreach ($posttypes as $posttype)
<option value="{{$posttype->id}}">{{$posttype->post_type}}</option>
#endforeach
</select>
</div>
//author type for author model (author_type_id)
<div class="form-group">
<label for="authortype">Author Type</label>
<select class="form-control" id="authortype" name="author_type_id">
#foreach ($authortypes as $authortype)
<option value="{{$authortype->id}}">{{$authortype->author_type}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="author_name">Author Name</label>
<input type="text" class="form-control" name="author_name" placeholder="your name">
</div>
<div class="form-group">
<label for="author_first_name">Author First Name</label>
<input type="text" class="form-control" name="author_first_name" placeholder="your first name">
</div>
//How to store author_id in post
<div class="form-group">
<label for="content">article</label>
<textarea class="form-control" name="article" rows="8" cols="8"></textarea>
</div>
<button type="submit" class="btn btn-primary">{{__('main.save')}}</button>
</form>
</div>
#endsection
I found solution, May this can help you in future.
$author = Author::create([
'author_type_id' => $request->author_id,
]);
$post = Post::create([
"post_type_id" => $request->post_type_id,
"author_id" => $author->id,
"author_type_id" => $request->author_type_id,
"article" => $request->article,
]);
Auther::create([
'author_type_id' => $request->author_id,
]);

Resolving "Integrity constraint violation: 19 NOT NULL", what's the most proper solution?

Trying to write a function to create a new "profile" in my profiles table and get the following error:
"SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: profiles.about (SQL: insert into "profiles" ("dateofbirth", "state", "zipcode", "profilepic", "user_id", "updated_at", "created_at") values (2020-04-15, FL, 12345, /tmp/phpTT6CZr, 1, 2020-04-30 00:48:23, 2020-04-30 00:48:23))"
I've been reading answers to similar questions for the past few hours. Tried several different things, no luck so far. Hoping to see a solution that works in my code, and also get a better understanding of where exactly the error begins. The error message leads me to believe it's something to do with my "about" section in table. But unsure. I thought adding " protected $guarded = []; " to controller would solve but that gave the same result.
Here is what I'm working with:
Migration File:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('user_id'); //foreign key
$table->text('about')->nullable;
$table->text('profilepic')->nullable;
$table->date('dateofbirth')->nullable;
$table->unsignedinteger('zipcode')->nullable;
$table->string('state')->nullable;
$table->timestamps();
$table->index('user_id'); //index for foreign key
});
}
Profile Model:
class profile extends Model {
protected $guarded = [];
public function user()
{
return $this->belongsTo(User::class);
} }
I have also tried changing the profile model like below:
class profile extends Model {
public function user()
{
return $this->belongsTo(User::class);
}
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'dateofbirth' => 'datetime',
'zipcode' => 'unsignedinteger'
];
/*
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'about','profilepic','state', 'user_id', 'updated_at', 'created_at'
]; }
They both provide the same error message but with slightly different array values
Here is my controller store function:
public function store()
{
$data = request()->validate([
'dateofbirth' => 'required',
'state' => 'required',
'zipcode' => 'required',
'profilepic' => 'image'
]);
auth()->user()->profile()->create($data);
dd(request()->all());
}
Here is the view:
#extends('layouts.app')
#push('styles')
<link href="{{ asset('css/profile.css') }}" rel="stylesheet">
#endpush
#section('content')
{{-- This needs to present a create profile form --}}
<div class="row">
<h1 class="pl-4">CREATE YOUR PROFILE</h1>
</div>
<form action="/profile" class="pl-4" enctype="multipart/form-data" method="post">
#csrf
<div class="form-group row">
<label for="profilepic"
class="col-md-4 ocl-form-label"
>Upload a Profile Picture</label>
<input type="file"
class="form-control-file"
id="profilepic"
name="profilepic">
</div>
<div class="form-group">
<label for="about">Write your "About" Section here. What do you want us to know about you?</label>
<textarea type="text" class="form-control" id="about" name="about" rows="3"></textarea>
</div>
<div class="form-group">
<label for="dateofbirth">Date of Birth</label>
<input type="date"
id="dateofbirth"
name="dateofbirth">
</div>
<div class="form-group">
<label for="zipcode">Zipcode</label>
<input type="text" id="zipcode" name="zipcode">
</div>
<div class="form-group">
<label for="State">State</label>
<input type="text" id="state" name="state">
</div>
<div class="form-group row pt-4">
<button class="btn btn-primary">Submit</button>
</div>
</form> #endsection
That error means you're trying to set a foreign key column as null which is unacceptable, in this case, user_id on profiles table. Try to modify your code as such:
In your Profile model, add mass assignment columns:
protected $fillable = ['dateofbirth', 'state', 'zipcode', 'profilepic'];
In your controller store method:
//assuming the route method is authenticated such that there's always a logged in user
$user = auth()->user();
$data['user_id'] = $user->id;
$profile = Profile::create($data);
I'll add in also, I have since gotten this resolved with implementing #djunehor's answer. But one thing that helped get the problem resolved was adding in this to the controller:
public function store(Request $request)
At first I was not passing the request in and saving it to a variable like this, but this step seems to have made a big difference for the errors I was running into.
At first I was just doing this:
public function store()

Inserting data to database laravel

At the moment I am working with Laravel. I am trying to insert data into a database. It is not user data, but product data. Costumers have to be able to insert a title, description and price of a product into the database.
I have looked at the laravel website, however, I was unable to find anything. There are some people with the same question as mine on StackOverflow. However, the answers that were given to them do not work for me.
My controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data=array('title'=>$productname,"description"=>$description,"price"=>$price);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
My view:
#section('content')
<h1>Add your new items here:</h1>
<form method="get">
<div class="title">
<div class="title">
<span class="input-group-text" id="title">Title</span>
</div>
<input type="text" name="title" class="form-control" aria-label="title" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="description">
<div class="description">
<span class="input-group-text" id="description">Description</span>
</div>
<input type="text" name="description" class="form-control" aria-label="description" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="price">
<div class="price">
<span class="input-group-text" id="price">Price</span>
</div>
<input type="text" name="price" class="form-control" aria-label="price" aria-describedby="inputGroup-sizing-default">
</div>
<br>
<br>
<div class="form-group">
<label for="exampleFormControlFile1">Insert Image</label>
<input type="file" class="form-control-file" id="exampleFormControlFile1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
#endsection
My web.php:
<?php
Route::get('/', function () {
return view('welcome');
});
Route::get('insert','ProductsController#insertform');
Route::post('create','ProductsController#insert');
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
My database structure:
The home and welcome, along with some code in the web.php, has been made by authentication.
Hopefuly you guys can help me out. I want to make sure that the product data is inserted into the database.
Don't use DB class. Instead create a model called Product and use model function to create or update data into table.
php artisan make:model Product
$product= Product::create([
'name' => $request->name, # declared as fillable on Product model
'description' => $request->description,
...
]);
Convert the route of /insert into POST and add csrf field in your form
#csrf
OR
<input type="hidden" name="_token" value="{{csrf_token()}}">
On your controller validation of input in insert function.
Also take a look at these -
https://laravel.com/docs/5.8/eloquent#defining-models
Laravel Validation Rules
or https://laravel.com/docs/5.8/validation#quick-writing-the-validation-logic
In your web.php, Add route names
Route::get('insert','ProductsController#insertform')->name('product.create');
Route::post('create','ProductsController#insert')->name('product.store');
In your view, change method to post and add action attribute and csrf field.
<form action="{{ route('product.store') }}" method="post">
#csrf
In Controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use DB;
class ProductsController extends Controller
{
public function insertform(){
return view('home');
}
public function insert(Request $request){
$productname = $request->input('title');
$description = $request->input('description');
$price = $request->input('price');
$data = array(
"title" => $productname,
"description" => $description,
"price" => $price
);
DB::table('products')->insert($data);
echo "Record inserted successfully.<br/>";
echo 'Click Here to go back.';
}
}
Alternate you can directly add action without route name
<form action="/create" method="post">
#csrf
In laravel 5.6 i can show you how to insert the data and display the data to the index page
so first of all i can code my route
in here we can use 2 routes
first is index page route
second is store and in store controller you can display your stored data.
Route::get('/FAQ_page', 'SettingController#FAQ_page')->name('FAQ_page');
Route::get('/FAQ_page/create', 'SettingController#FAQ_page_create')->name('FAQ_page.create');
Route::post('/FAQ_page/store', 'SettingController#FAQ_pagestore');
now make a database and connect to your module
this is your module
namespace App;
use Illuminate\Database\Eloquent\Model;
class FAQpage extends Model
{
protected $table = 'p66_FAQ_page';
public $timestamps = false;
protected $primaryKey = 'fid';
}
now make your controller like this
public function FAQ_page()
{
$data = FAQpage::get();
return view('SuperAdmin.settings.FAQ_page', compact('data'));
}
public function FAQ_page_create()
{
return view('SuperAdmin.settings.FAQ_page_create');
}
public function FAQ_pagestore(Request $request)
{
request()->validate([
'FAQ_question'=> 'required',
'FAQ_answer'=> 'required',
'Sort_order'=> 'required|max:4',
'FAQ_departments'=> 'required',
]);
$data = new FAQpage();
$data->FAQ_question = $request->get('FAQ_question');
$data->FAQ_answer = $request->get('FAQ_answer');
$data->Sort_order = $request->get('Sort_order');
$data->FAQ_departments = $request->get('FAQ_departments');
$data->Created_date = Carbon::now();
$data->save();
return redirect('/SuperAdmin/FAQ_page');
}
thank you

DropDown list for foreign key

I would like to learn to create a dropdown list with a foreign key on Laravel.
For information, I have a table named series with 3 fields id, name, fk_mark.
Then, I have another table named marks with 2 fields id, name_mark.
My create works correctly, here is the proof.
I am stuck about the dropdownlist, what is the syntax please for my foreign key ?
<fieldset class="form-group">
<label for="form-group-input-1">Name serie</label>
<input type="text" name="name" class="form-control" id="form-group-input-1">
</fieldset>
<fieldset class="form-group">
<label for="form-group-input-1">FK Mark</label>
<input type="text" name="fk_mark" class="form-control" id="form-group-input-1">
</fieldset>
I have tried this but without result...
<div class="form-group">
<label for="company-content">Select compagny</label>
<select name="fk_mark" class="form-control">
#foreach($series as $serie)
<option value="{{$serie->id}}"> {{$serie->name}} </option>
#endforeach
</select>
</div>
Here is my Models
Model Mark
class Mark extends Model
{
protected $fillable = ['name_mark'];
public function series(){
return $this->hasMany('App\Serie', 'fk_mark');
}
}
Model Serie
class Serie extends Model
{
protected $fillable = ['name', 'fk_mark'];
public function marks(){
return $this->belongsTo('App\Mark', 'fk_mark');
}
}
SerieController
public function index()
{
$series = Serie::oldest()->paginate(5);
return view('admin.series.index', compact('series'))
->with('i', (request()->input('page', 1)-1)*5);
}
public function create()
{
return view('admin.series.create');
}
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'fk_mark' => 'required'
]);
Serie::create($request->all());
return redirect()->route('series.index')
->with('success', 'save');
}
Thank you very much for your help.

Updating a row in the database from the modal using Laravel Eloquent

I have a calls table that is populated from a form,
calls table
public function up()
{
Schema::create('calls', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->timestamps();
$table->text('terminal_id', 20);
$table->text('terminal_name', 100);
$table->text('fault_description');
$table->string('call_status', 10)->default('New call');
$table->text('assigned_FE', 20)->nullable();
$table->text('closed_on', 20)->nullable();
$table->text('closed_by', 50)->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
I want to fetch and update only the assigned_FE column in my calls table with a user's entry on this modal form
<div class="modal-body">
<form action="{{route('Call.update')}}" method="POST" style="padding:30px 0px">
#csrf
<div class="col-md-6">
<div class="input-group" style="width: 100%;">
<label for="assigned_FE">{{ __('Name of field engineer') }}</label><br>
<input type="text" name="assigned_FE" id="assigned_FE" class="form-control" placeholder="Name of field engineer" style="padding: 20px;" required>
</div>
</div>
<button type="submit" class="btn-primary" style="padding: 10px; font-size: 14px; border: 0; margin-top:25px">{{ __('Submit') }}</button>
</form>
</div>
How do I achieve this without fetching all the data in a call's row?
I don't have an idea of what to place in my CallsController
This is my CallsController
public function edit($id)
{
//find the call in the db and save it as a variable
$call = Call::find($id);
//return it to the view and pass in the variable
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}
and here is my Calls model (Call.php)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Call extends Model{
protected $fillable = [
'terminal_id',
'terminal_name',
'branch_address',
'fault_description'
];
//describing a one-to-many-relationship between calls and users
public function user(){
return $this->belongsTo('App\User');
}
}
Ok, first in your Model you should include all column name in the fillable array your Call model is missing assigned_FE
class Call extends Model{
protected $fillable = [
'terminal_id',
'terminal_name',
'branch_address',
'atm_variant',
'assigned_FE',
'closed_on',
'closed_by',
'fault_description'
];
//describing a one-to-many-relationship between calls and users
public function user(){
return $this->belongsTo('App\User');
}
after making sure that all columns are present in the fillable array, change your Form action to point to call.update route
<div class="modal-body">
<form action="{{route('call.update')}}" method="POST" style="padding:30px 0px">
#csrf
<div class="col-md-6">
<div class="input-group" style="width: 100%;">
<label for="assigned_FE">{{ __('Name of field engineer') }}</label><br>
<input type="text" name="assigned_FE" id="assigned_FE" class="form-control" placeholder="Name of field engineer" style="padding: 20px;" required>
</div>
</div>
<button type="submit" class="btn-primary" style="padding: 10px; font-size: 14px; border: 0; margin-top:25px">{{ __('Submit') }}</button>
</form>
your controller
use App\Call;
public function update(Request $request, $id)
{
$assigned_FE = $request->assigned_FE;
$call = Call::findOrFail($id);
$call->assigned_FE = $assigned_FE;
$call-save();
return redirect()->back();
}
your routes file should have something like this:
route::post('call/{id}', CallsController#update)->name('call.update);
Get the required record in the update function and then update it.
public function update(Request $request, $id)
{
$call = Call::find($id);
$input = $request->all();
$call->assigned_FE = $input['assigned_FE'];
$call->update();
// redirect wherever you want
return redirect()->back();
}
Here you go If I try to understand your question!
public function update(Request $request, $id)
{
if($request->isMethod('post')){
$data = $request->all();
//this part will get your item with that specific id updated just match database columns with form input names.
call::where(['id'=> $id])
->update(['terminal_name'=> $data['terminal_name'], 'fault_description' =>$data['fault_description']]);
//redirected to another page after updating or
//return back(); to stay on same page.
return redirect('/page');
}
}

Categories