laravel eloquent forceDelete database query equivalent - laravel

I need to change my migration files because currently it's using model but I've read that we should not be using models inside migration files.
I have an eloquent code:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\MyModel;
class AddRelationshipIdToMyModel extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
MyModel::query()->forceDelete();
Schema::table('my_model', function (Blueprint $table) {
$table->foreignId('my_model_id')->constrained();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('my_model', function (Blueprint $table) {
$table->dropForeign(['my_model_id']);
});
}
}
I need to refactor this to not use model 'MyModel' but I don't know the equivalent for this in db query

I understand that you want to Truncate the table before running the migration.
If I'm right then you need to use DB::table() and truncate() function.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use App\MyModel;
class AddRelationshipIdToMyModel extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
\DB::table('my_model')->truncate();
Schema::table('my_model', function (Blueprint $table) {
$table->foreignId('my_model_id')->constrained();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('my_model', function (Blueprint $table) {
$table->dropForeign(['my_model_id']);
});
}
}

Related

Get attribute in model - laravel eloquent

In laravel i can getFirstNameAttribute in my products model and change the value but I'm create this column "priceArray" and i can not get attributes because The first letter in the second word is capital letters and model can not found this column.
public function getPriceArrayAttribute($value)
{
return 'test';
}
Its not work and can not get "priceArray" column
This is my migration
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('priceArray')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
This is my product model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Products
* #package App\Models
* #property Variants Variants
*/
class Products extends Model
{
use HasFactory;
protected $guarded=[];
protected $changePrice=0;
public function Insert($data)
{
return self::create($data);
}
public function getPriceArrayAttribute($value)
{
return 'test';
}
public function getPriceAttribute($value)
{
return ceil($value);
}
}
The getPriceAttribute is worked but getPriceArrayAttribute does not worked
I think you are trying to modify the priceArray value after it is retrieved from the database, the way you did with ceil() on the price attribute. The only way this works is if you change the column name to price_array. This is by far the simplest fix.
Migration
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('title')->nullable();
$table->string('price')->nullable();
$table->string('price_array')->nullable();
$table->text('items')->nullable();
$table->enum('status',['active','inactive','unavailable'])->default('inactive');
$table->timestamps();
});
Model
public function getPriceArrayAttribute($value)
{
return 'test';
}
You must follow Eloquent's rules: you use snake case for the attributes. The getPriceArrayAttribute accessor will automatically be called by Eloquent when you retrieve the value of the price_array attribute.
$table->string('price_array')->nullable();

Laravel API: How to get data from foreign key from different table

I currently want to make an API that will get all the lessons by its module_id. These are currently my codes:
Module Migration Table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModulesTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('modules', function (Blueprint $table) {
$table->id();
$table->string('module_name');
$table->bigInteger('created_by')->unsigned()->nullable();
$table->bigInteger('updated_by')->unsigned()->nullable();
$table->timestamps();
});
Schema::table('modules', function(Blueprint $table) {
$table->foreign('created_by')->references('id')->on('admins');
$table->foreign('updated_by')->references('id')->on('admins');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('modules');
}
}
Lesson Migration Table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateLessonTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up() {
Schema::create('lesson', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->bigInteger('module_id')->unsigned();
$table->longText('content');
$table->bigInteger('created_by')->unsigned()->nullable();
$table->bigInteger('updated_by')->unsigned()->nullable();
$table->string('enabled')->nullable();
$table->string('position')->nullable();
$table->timestamps();
});
Schema::table('lesson', function(Blueprint $table) {
$table->foreign('module_id')->references('id')->on('modules');
$table->foreign('created_by')->references('id')->on('admins');
$table->foreign('updated_by')->references('id')->on('admins');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down() {
Schema::dropIfExists('lesson');
}
}
And this is the GetLessonByModule controller of that API I want to make (getting all the lessons by its module_id):
<?php
namespace App\Http\Controllers;
use App\Models\Lesson;
use App\Models\Modules;
use Illuminate\Http\Request;
class GetLessonByModuleController extends Controller {
public function index() {
$lessons = Lesson::all();
return response($lessons,200);
}
}
The module_id and the ID in the modules table are currently connected as seen in the migration tables. I just don't know how to compose it in my Controller. I also don't know if I should make a new model. Any kind of help/suggestion is deeply appreciated. Thanks in advance.
You can do
<?php
namespace App\Http\Controllers;
use App\Models\Lesson;
use App\Models\Modules;
use Illuminate\Http\Request;
class GetLessonByModuleController extends Controller {
public function index(int $module_id) {
$lessons = Lesson::where('module_id', '=', $module_id)->get();
return response($lessons,200);
}
}
In your api.php there should be definition of the route:
Route::get('lessons-by-module/{module_id}', [\App\Http\Controllers::class, 'index']);
If it works for you and want to do it better, you can go fancy with Laravel routing explicit binding: https://laravel.com/docs/8.x/routing#explicit-binding

How to build the database migration properly?

I'm setting up a laravel project (I'm beginner) to manage customers (a customer has many contracts and a contract has many different products). And I want to implement a CRUD method and generate pdf but I have an issue at the beginning, when I migrate my database. (this is the beginning so I guess it will hard for me...)
I wrote all my migrations (customer + contracts + products) and migrate them
customer (clients):
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Clients extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('clients', function (Blueprint $table) {
$table->Increments('id');
$table->string('name');
$table->string('company');
$table->string('email', 50);
$table->string('phone', 15);
$table->string('adress1', 50);
$table->string('adress2', 50);
$table->string('adresse3', 50);
$table->string('pays', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('clients');
}
}
Contracts (contrats)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Contrats extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
/* $table->unsignedBigInteger('clients_name');
$table->foreign('name')->references('name')->on('Clients'); */
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('contrats');
}
}
and products (produits)
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class Produits extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->Increments('id');
$table->foreign('name');
$table->string('description', 20);
$table->double('price');
$table->double('taxes');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
schema::drop('produits');
}
}
Migration table created successfully.
Migrating: 2014_10_12_000000_create_users_table
Migrated: 2014_10_12_000000_create_users_table (0.03 seconds)
Migrating: 2014_10_12_100000_create_password_resets_table
Migrated: 2014_10_12_100000_create_password_resets_table (0.02 seconds)
Migrating: 2019_10_15_131435_clients
Migrated: 2019_10_15_131435_clients (0.01 seconds)
Migrating: 2019_10_15_131454_contrats
Illuminate\Database\QueryException : SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table (SQL: alter table contrats add constraint contrats_name_foreign foreign key (name) references Clients (name))
at
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664
660| // If an exception occurs when attempting to run a query, we'll format the error
661| // message to include the bindings with SQL, which will make this exception a
662| // lot more helpful to the developer instead of just the database's errors.
663| catch (Exception $e) {
664| throw new QueryException(
665| $query, $this->prepareBindings($bindings), $e
666| );
667| }
668|
Exception trace:
1 PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'name' doesn't exist in table")
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
2 PDOStatement::execute()
/Applications/MAMP/htdocs/test04/vendor/laravel/framework/src/Illuminate/Database/Connection.php:458
Please use the argument -v to see more details.
I expect to get a good migration to going ahead with this project
Thanks in advance for your help, cheers.
The foreign key column format must match the format of the column it's referencing on the other table, so instead of unsignedBigInteger, it should be string
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
/* $table->unsignedBigInteger('clients_name'); */
$table->string('name');
$table->foreign('name')->references('name')->on('clients');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
Tho it's highly recommended that you reference the primary key id instead
Proper way
Eloquent will make use of naming conventions to make proper relationships with less explicit code
clients
<?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->string('company');
$table->string('email', 50);
$table->string('phone', 15);
$table->string('adress1', 50);
$table->string('adress2', 50);
$table->string('adresse3', 50);
$table->string('pays', 20);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('clients');
}
}
contrats
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateContratsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('contrats', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients')->onDelete('cascade');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate');
$table->index('startdate');
$table->date('enddate');
$table->index('enddate');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('contrats');
}
}
produits
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProduitsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('produits', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('client_id');
$table->foreign('client_id')->references('id')->on('clients');
$table->string('description', 20);
$table->double('price');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('produits');
}
}
Hope this helps
Bon Courage :)
write your function up for contrats migration like this
Schema::create('contrats', function (Blueprint $table) {
$table->Increments('id');
$table->string('id_dossier');
$table->string('id_contrat');
$table->string('id_bateau');
$table->date('startdate')->index();
$table->date('enddate')->index();
$table->timestamps();
});

Rollback Error in Laravel 5

I wanted to delete one column, it worked but for the " rollback" it always shows up an error!
ERROR : parse error: syntax error,unexpected end of file,expectinf function (T_FUNCTION) or const ( T_CONST)
the code :
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class DropBody extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('body');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->mediumText('body');
});
}
}
.
I guess you are writing reverse code, by reverse code i mean to say you have to create table fields in up function and drop columns in down function.
You should try something like this:
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
$table->mediumText('body');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('posts', function (Blueprint $table) {
$table->dropColumn('body');
});
}

Laravel 5.5 : Fetch many to many response on collection instance

I have many to many relationships between Blog and Category.
Blog.php
public function category() {
return $this->belongsToMany('App\Category');
}
Category.php
public function blog() {
return $this->belongsToMany('App\Blog');
}
create_blogs_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBlogsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('blogs', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->length(250);
$table->text('content');
$table->integer('updated_by')->unsigned()->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('blogs');
}
}
create_categories_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCategoriesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->length(250);
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('categories');
}
}
blog_category_table.php
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class BlogCategoryTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create ( 'blog_category', function (Blueprint $table) {
$table->integer ( 'category_id' )->unsigned ();
$table->integer ( 'blog_id' )->unsigned ();
$table->foreign ( 'category_id' )->references ( 'id' )->on ( 'categories' );
$table->foreign ( 'blog_id' )->references ( 'id' )->on ( 'blogs' );
$table->primary ( [
'category_id',
'blog_id'
]);
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists ( 'blog_category' );
}
}
To get blog related to any category I can code like
$category = App\Category::find(1);
$category->blog->get();
But if I want to get blogs related to category having category id 1 & 2 in a single query. What should be the solution for this?
I tried same approach it is giving me error like
'Exception with message 'Property [blog] does not exist on this collection instance.'

Resources