How do I insert data in Laravel database from controller? - laravel

this is my first post in this forum and also I'm a very new user with Laravel.
I'm trying to do a very simple thing like creating an array and visualize the data inside in my database. The code works but I cant see the data in the database table. It might look easy but for some reason I've been a whole day with this thing so I'll appreciate a lot any help I can receive. This is how the code looks right now:
Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Client;
use App\Http\Controllers\Controller;
class ClientController extends Controller
{
public function index()
{
DB::table('clients')->insert(
array(
'id' => 1,
'name' => 'Josh',
'age' => 45,
'gender' => 'M',
'nationality' => 'UK',
'job' => 'a',
)
);
}
}
Model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Client extends Model
{
use HasFactory;
protected $fillable = [
'name', 'age', 'gender', 'nationality', 'job',
];
}
Migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateClientsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('age');
$table->string('gender');
$table->string('nationality');
$table->string('job');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('clients');
}
}

First of all in your migration change this line:
$table->bigIncrements('id');
with
$table->id();
Once you have migrated it with:
php artisan migrate:fresh (empty database and recreate it)
Insert a record with:
public function index()
{
Client::create([
'name' => 'Josh',
'age' => 45,
'gender' => 'M',
'nationality' => 'UK',
'job' => 'a',
]);
}
There is no need to populate the id. Laravel (MySQL) will do it for you.

Maybe you do not need "," at the end of the array
protected $fillable = [
'name', 'age', 'gender', 'nationality', 'job',
];

Related

created_at and updated_at don't update automatically on insert in laravel

I use laravel 8 :
public function up()
{
Schema::create('user', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->integer('created_by')->nullable();
$table->string('created_by_user')->nullable();
$table->timestamps();
});
}
Models:
<?php
namespace App\Models\Backend\MySQL;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'user';
}
In controller :
use App\Models\User;
public function store(Request $request) {
$data = [
'name' => !empty($request->name) ? $request->name : 'Jony',
'created_by' => auth()->user()->id,
'created_by_user' => auth()->user()->name,
];
User::insert($data);
}
I have successfully inserted. But the problem is that my created_by and updated_by columns are not updating automatically. Is there any way to solve this problem. In the user model I also don't set protected $timestamps = false but it doesn't work. Thank you.
insert method is not for eloquent models and doesn't update created_at and updated_at.
you should use create method instead.
create method sets created_at and updated_at automatically
see this answer here
https://stackoverflow.com/a/58075757/7689224
You should use create instead of insert.
User::create($data);
Use create() method instead of insert()
public function store(Request $request) {
$data = [
'name' => !empty($request->name) ? $request->name : 'Jony',
'created_by' => auth()->user()->id,
'created_by_user' => auth()->user()->name,
];
User::create($data);
}

How can I display my imported Excel data?

Currently working on an Excel import functionality. I want to import the Excel sheet and display its information on another page using a foreach loop. However it seems to be rather hard for some reason. When I die and dump the collection data (used this because import would error) it shows everything correctly. The data in the spreadsheet is where it should be. So I feel that is fine. However I cannot get it inserted into my database for some odd reason. I have a header row so I use the WithHeaderRow functionality.
DataImport class:
<?php
namespace App\Imports;
use App\Data;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
HeadingRowFormatter::default('none');
class DataImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Data([
'cliëntnummer' => $row['clientnummer'],
'zoeknaam' => $row['zoeknaam'],
'naam' => $row['naam'],
'omschrijving' => $row['omschrijving'],
'plaats' => $row['plaats'],
'week' => $row['week'],
'vennoot' => $row['vennoot'],
'relatiebeheerder' => $row['relatiebeheerder'],
'samensteller' => $row['samensteller'],
'ADVer' => $row['adver'],
'cliëntgroepcode' => $row['clientgroepcode'],
'accountant' => $row['accountant'],
'samenstellen' => $row['samenstellen'],
'ADV jaarwerk' => $row['ADVJaarwerk'],
'periodieke ADV' => $row['periodiekeADV'],
'fiscaliteiten' => $row['fiscaliteiten'],
]);
}
}
Datacontroller.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Imports\DataImport;
use Maatwebsite\Excel\Facades\Excel;
use App\Http\Controllers\Controller;
class DataController extends Controller
{
public function index(){
return view('importeren');
}
public function import(Request $request){
$datas = Excel::toCollection(new DataImport(), $request->file('import_file'));
dd($datas);
return redirect()->route('/home');
}
}
Data Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Data extends Model
{
protected $fillable = [
'id', 'cliëntnummer', 'zoeknaam', 'naam', 'omschrijving', 'plaats', 'week', 'vennoot', 'relatiebeheerder', 'samensteller', 'ADVer', 'cliëntgroepcode', 'accountant', 'samenstellen', 'ADV jaarwerk', 'periodieke ADV', 'fiscaliteiten',
];
}
Spreadsheet data:
Database table layout:
Datadump results:
If I left anything out feel free to tell me. I hope this is sufficient.
Turns out I forgot to reference my datamodel in the file, after finalizing the code of my controller like below it now works (almost) seamlessly.
<?php
namespace App\Imports;
use App\Data;
use Maatwebsite\Excel\Concerns\ToModel;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Imports\HeadingRowFormatter;
HeadingRowFormatter::default('none');
class DataImport implements ToModel, WithHeadingRow
{
/**
* #param array $row
*
* #return \Illuminate\Database\Eloquent\Model|null
*/
public function model(array $row)
{
return new Data([
'cliëntnummer' => $row['Cliëntnummer'],
'zoeknaam' => $row['Zoeknaam'],
'naam' => $row['Naam'],
'omschrijving' => $row['Omschrijving'],
'plaats' => $row['Plaats'],
'week' => $row['Week'],
'vennoot' => $row['Vennoot'],
'relatiebeheerder' => $row['Relatiebeheerder'],
'samensteller' => $row['Samensteller'],
'ADVer' => $row['ADVer'],
'cliëntgroepcode' => $row['Cliëntgroepcode'],
'accountant' => $row['Accountant'],
'samenstellen' => $row['Samenstellen'],
'ADVJaarwerk' => $row['ADVJaarwerk'],
'PeriodiekeADV' => $row['PeriodiekeADV'],
'fiscaliteiten' => $row['Fiscaliteiten'],
]);
}
}

Class 'App\Models\Registration' not found even though i have import it

Class 'App\Models\Registration' not found, i have import Registration class
i am trying to save student_id with it corresponding subjects array
When i dump dd($request->all()) i get the excepted results which is
"student_id" => "1"
"subjects" => array:2 [▼
0 => "1"
1 => "2"
]
but i get an exception when i trying saving into the database
this is my registration scheme
Schema::create('registrations', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('student_id')->index();
$table->string('subjects');
$table->foreign('student_id')->references('id')->on('students');
$table->timestamps();;
});
this is my registration model
class Registration extends Model
{
protected $table = 'registrations';
protected $fillable = ['student_id','subjects'];
protected $cast = [
'student_id' => 'Integer',
'subjects' => 'array',
];
public function student(){
$this->belongsTo(Student::class);
}
public function subjects()
{
$this->hasMany(Subject::class);
}
}
i am using checkbox array to get the subjects
<input class="form-check-input" name="subjects[]" value="{{$subject->id}}" type="checkbox">
this is registration controller code, i have imported registration model
namespace App\Http\Controllers\Admin;
use Illuminate\Http\Request;
use App\Models\Registration;
use App\Http\Controllers\BaseController;
class RegistrationController extends BaseController
{
public function store(Request $request)
{
$registration = Registration::create(request()->validate([
'student_id' => 'required|integer',
'subjects' => 'required',
'subjects.*'=> 'accepted',
]));
}
i want to save the student_id with the subjects array
student subjects
1 [2,4,5]enter code here
I think you need to add a namespace.
<?php
namespace App\Models;
class Registration extends Model { ... }
?>
Also your model must be stored inside the directory App/Models/Registration.php.
i think you create your Registration model in App directory...please check your directory.then use
use App\Registration;
If It on App\Models directory then In Registration Model,
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Registration extends Model { }

How can test a function that gets data from DB in a Laravel 5 package?

I'm working on a Laravel 5 package, and writing tests I'm trying to test a function that gets datas from DB.
public function getPhotoDatasFromDb()
{
$ret = GalleryImage::get()->keyBy('file_name');
return $ret;
}
The returned values should be in this format:
Collection {#416 ▼
#items: array:2 [▼
"IMG_1979.jpg" => GalleryImage {#423 ▼}
"alt_text" => "example alt text"
"description" => "lorem ipsum"
"IMG_1980.jpg" => GalleryImage {#424 ▶}
]
}
I had already experiences with testing database testing in other Laravel applications.
My question is: since I'm writing a package, and in the dev environment I don't have an instance of the DB I'm wondering what is the best approach to test it?
If can help to have a wider picture, the database table gets created in the application trough this migration:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateGalleryImagesTable extends Migration
{
public function up()
{
Schema::create('gallery_images', function (Blueprint $table) {
$table->increments('id');
$table->string('file_name')->unique();
$table->text('description')->nullable();
$table->string('alt')->nullable();
$table->string('video_link')->nullable();
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('gallery_images');
}
}
And this is the model associated
<?php
namespace DavideCasiraghi\ResponsiveGallery;
use Illuminate\Database\Eloquent\Model;
class GalleryImage extends Model
{
protected $fillable = [
'file_name', 'description', 'alt', 'video_link',
];
}
I found the solution myself.
I post it in case it can be helpful for somebody else.
This is my test:
/** #test */
public function it_gets_photos_from_db()
{
$gallery = new ResponsiveGalleryFactory();
$dbImageDatas = $gallery->getPhotoDatasFromDb();
$this->assertStringContainsString($dbImageDatas['DSC_9470.jpg']->description, 'Photo description');
}
To make it work I had to configure the DB in the beginning of the testing class:
/**
* Create the tables this model needs for testing.
*/
public static function setUpBeforeClass() : void
{
$capsule = new Capsule;
$capsule->addConnection([
'driver' => 'sqlite',
'database' => ':memory:',
'prefix' => '',
]);
$capsule->setAsGlobal();
$capsule->bootEloquent();
Capsule::schema()->create('gallery_images', function (Blueprint $table) {
$table->increments('id');
$table->string('file_name')->unique();
$table->text('description')->nullable();
$table->string('alt')->nullable();
$table->string('video_link')->nullable();
$table->timestamps();
});
Model::unguard();
GalleryImage::create([
'file_name' => 'DSC_9470.jpg',
'description' => 'Photo description',
'alt_text' => 'Photo alt text',
'video_link' => 'https://www.youtube.com/fsda234',
]);
}

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist

When I try to save data from laravel form to a database table I am getting the following exception:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db.store' doesn't exist (SQL: select count(*) as aggregate from store where name = samplename)
the table store exists but still I am getting the error
this is my contoller that is processing the form:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\storestore;
use App\Http\Requests\storeFormRequest;
class AddstoreController extends Controller
{
//
public function create()
{
//
}
public function store( storeFormRequest $request)
{
$store = new Store;
$store->name = Input::get('name');
$store->description = Input::get('description');
$store->store_vendor_id = Input::get('owner');
$store->contact_email = Input::get('contact_email');
$store->postal_address = Input::get('postal_address');
$store->city = Input::get('city');
$store->zip = Input::get('zip');
$store->phone = Input::get('phone');
$store->business_logo = Input::get('logo');
$store->save();
return \Redirect::route('add_store_success')
->with('message', 'Thanks for joining us!');
}
}
This is my Store model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
protected $table = 'stores';
protected $fillable = ['name', 'description', 'vendor_id',
'contact_email','postal_address','city','zip','phone',
'meta_description','business_logo'];
}
StoreRequest file:
<?php
namespace App\Http\Requests;
use App\Http\Requests\Request;
use App\StoreController;
class StoreFormRequest extends Request
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
return [
//
'name' => 'required|unique:dstore',
'vendor_id' => 'required',
'contact_email' => 'required|email|max:100|unique:dstore',
'business_logo' => 'required',
];
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
}
}
These are the get and post routes:
Route::get('/store_form', ['as' => 'add_store_form', 'uses' => 'StoreController#create']);
Route::post('/store_form',['as' => 'dstore', 'uses' => 'StoreController#store']);
Both routes are listed when I run php artisan route:list command
I have tried to goggle for solution but the one I landed on pointed out to missing tables as a course, but in my case the store table is existing but still I am getting the error.
Any help please!
Look at your Store model class:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Store extends Model
{
//
protected $table = 'stores';
protected $fillable = ['name', 'description', 'vendor_id',
'contact_email','postal_address','city','zip','phone',
'meta_description','business_logo'];
}
As you see property $table is set to stores so I assume table name in your database is stores and not store.
You should probably change in your StoreFormRequest content or rules method to use in unique rule valid table name, for example:
public function rules()
{
return [
//
'name' => 'required|unique:stores',
'vendor_id' => 'required',
'contact_email' => 'required|email|max:100|unique:stores',
'business_logo' => 'required',
];
//validate
if ($validation->fails())
{
return redirect()->back()->withErrors($v->errors());
}
}

Resources