Change date format in Laravel migration - laravel-6

I want to change the date format from 1990-01-30 to 30/01/1990 straight from my migration. I get the following error when I try to migrate with seeding from factory.
Invalid datetime format: 1292 Incorrect date value: '30/01/1990' for
column 'dob' at row 1
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('fname');
$table->string('lname');
$table->string('phone')->unique();
$table->date('dob')->format('d/m/Y');
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}

Declare in model:
class ModelName extends Model
{
protected $casts = [
'created_at' => 'datetime:d/m/Y', // Change your format
'updated_at' => 'datetime:d/m/Y',
];
}

You can't do that within a migration. You will need to use Carbon and format the date in your Model instead.

Related

(laravel ) checkbox toggle is not working. And Changing text do not working either.What's wrong with mycode?

I am new to laravel and creating todo list.
I try to toggle checkbox.
BUt in checked method(the bottom of PostController), I can't even change text in the first place.
What's wrong with checked method?
I expect a problem in web.php.
I'm using laravel8.
thankyou for your help!
What's wrong with checked method?
(((PostController.php)))
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Post;
use App\Http\Requests\PostRequest;
class PostController extends Controller
{
public function index()
{
$posts = Post::latest()->get();
return view('index')
->with(['posts' => $posts]);
}
public function show(Post $post)
{
return view('posts.show')
->with(['post' => $post]);
}
public function checked(Post $post)
{
// $post->is_done = !$post->is_done;
$post->title = 'hogehoge';
$post->save();
return redirect()
->route('posts.index');
}
}
(((web.php)))
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PostController;
Route::get('/', [PostController::class, 'index'])
->name('posts.index');
Route::get('/posts/{post}', [PostController::class, 'show'])
->name('posts.show')
->where('post', '[0-9]+');
Route::patch('/posts/{post}/checked', [PostController::class, 'checked'])
->name('posts.checked')
->where('post', '[0-9]+');
(((post table column)))
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('body');
$table->boolean('is_done')->default(false);
$table->timestamps(); // created_at, updated_at
});
}

How to call function as auto increment in laravel

I'm trying to call my function as auto increment value in laravel, but i dont know how to do it.
The function i'm trying to use is
public function generateRandomString()
{
$pass = substr(str_shuffle("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, 6);
return $pass;
}
and the column im trying to call the function are 'No_Resi'
public function up()
{
Schema::create('order', function (Blueprint $table) {
$table->increments('No_Resi');
$table->string('Nama_Lengkap',100);
$table->text('Alamat_Pengambilan',100);
$table->text('Alamat_Tujuan',100);
$table->integer('No_Telepon_Pengirim');
$table->integer('No_Telepon_Penerima');
$table->enum('Jenis Barang',['Makanan','Dokumen','Barang Pecah Belah','Pakaian',
'Obat-Obatan','Buku','Lainnya']);
});
}
so the output should be something like this
No_Resi
Nama_lengkap
1B45CY
someone
9K0L7T
nobody

Laravel Carbon error data missing with casting

I have a date property, and I try to cast it to the DateTime format during saving.
protected $casts = [
'date' => 'datetime:Y-m-d H:m',
];
In my controller, I have the following method.
public function change(int $gameSerieId, Request $request)
{
try {
$gameSerie = GameSerie::findOrFail($gameSerieId);
$gameSerie->update($request->all());
return response()->json('ok');
} catch (\Exception $exception) {
throw new GameApiException('Something went wrong!');
}
}
However, I get an error "Data Missing" because my date input format looks like a string: 2019-11-17 21:00.
I have found the ability of use mutators for set attributes
public function setDateAttribute($date)
{
$this->attributes['date'] = Carbon::make($date);
}
https://laravel.com/docs/5.7/eloquent-mutators#defining-a-mutator

SQLSTATE[HY000]: General error: 1 unknown column "user_id" in foreign key definition

I have this error when i run :
php artisan migrate:fresh
Illuminate\Database\QueryException : SQLSTATE[HY000]: General
error: 1 unknown column "user_id" in foreign key definition (SQL:
create table "users" ("id" integer not null primary key autoincrement,
"name" varchar not null, "email" varchar not null, "username" varchar
not null, "email_verified_at" datetime null, "password" varchar not
null, "remember_token" varchar null, "created_at" datetime null,
"updated_at" datetime null, foreign key("user_id") references
"users"("id") on delete cascade))
I'm following a video tutorial on youtube, and the code of the tutorial is this:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('profiles');
}
}
If I copy and paste this code I have the error. So i searched on stackoverflow and I've found this solution:
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
Schema::table('profiles', function (Blueprint $table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('profiles');
}
This is my users table:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::disableForeignKeyConstraints();
Schema::dropIfExists('users');
}
But today, when i run php artisan migrate:fresh I had this error again.
How can I solve?
Thanks
As others have mentioned, user_id isn't a column in your users table, but you are trying to create an index on it. This line:
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
belongs in the profiles table creation schema and not in the users table creation schema.
The full code:
// create_users_table.php
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
// create_profiles_table.php <-- migrate AFTER users table
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
The error is clearly mention here:
foreign key("user_id") references "users"("id") on delete cascade)
and you don't have a column with name user_id
The syntax is:
CONSTRAINT constraint_name
FOREIGN KEY foreign_key_name (columns) <-- this must be a column in the table
REFERENCES parent_table(columns)
ON DELETE action
ON UPDATE action
but in your case user_id column is not available in the query. So either add the that column or remove this constraint code and try again.
The reason for this problem is that the profile table was created before the user table.
I have a trick for problem solve.
You should rename migration files in the migration directory.
for example let my file names be like this
2019_06_10_000001_create_users_table.php
2019_06_10_000002_create_profiles_table.php
first user table is created when you run "artisan migrate or migrate:fresh"
why? because first created migration file is user file.You should look carefully
2019_06_10_000001 -> users table name
2019_06_10_000002 -> profiles table name
Solution:
So u just need to do this: rename "user" table and name it numerically smaller than the "profiles" table.So problem will solve.
Other solution:
delete all migration files after run them respectively this commands.
php artisan make:migration create_users_table
php artisan make:migration create_profiles_table
Try this;
public function up()
{
Schema::dropIfExists('profiles');
Schema::create('profiles', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('title')->nullable();
$table->text('description')->nullable();
$table->string('url')->nullable();
$table->string('image')->nullable();
$table->timestamps();
$table->index('user_id');
});
}
That is the migration. Before you are able to run it; delete the row for 'CreateProfilesTable' in the migrations table.

Search by Max of Value in Eloquent Database Laravel

How convert this Raw SQL to Eloquent Database in my API Controller?
What i'm tried is i wanna get data from Two Tables from My API Controller.
First: Formc_image Table which is general information about data
Second: Formc_image_detail which is detail and path of data
They are related by ID.
This is my API Controller FormCController.php
SELECT *
FROM formc_image_detail
WHERE id_tps=$id_tps AND jenis_pemilihan=$election_id
AND versi = (SELECT MAX(versi) FROM formc_image WHERE id_tps=id_tps AND jenis_pemilihan=$election_id)
ORDER BY no_lembar ASC
This is my Model FormCImageDetail
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImageDetail extends Model
{
protected $table = 'formc_image_detail';
public function formc_image(){
return $this->belongsTo('App\Models\FormCImage');
}
}
This is my FormCImage Models
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class FormCImage extends Model
{
protected $table = 'formc_image';
}
I was make this code in My API Controller:
return response(FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->orderBy('no_lembar', 'ASC')->paginate(100)->jsonSerialize(), Response::HTTP_OK);
But it still error.
This is my Migration:
Schema::create('formc_image', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->string('jenis_pemilihan');
$table->timestamps();
}
Schema::create('formc_image_detail', function (Blueprint $table) {
$table->integer('id_tps');
$table->smallint('versi');
$table->integer('no_lembar');
$table->string('jenis_pemilihan');
$table->char('url_image', 100);
$table->timestamps();
}
Use this:
return FormCImageDetail::with('formc_image')
->where('jenis_pemilihan', $electionId)
->where('id_tps', $tpsId)
->where('versi', function($query) use($election_id) {
$query->select(DB::raw('max(versi)'))
->from('formc_image')
->whereColumn('id_tps', 'formc_image_detail.id_tps')
->where('jenis_pemilihan', $election_id);
})
->orderBy('no_lembar')
->paginate(100);