My database isn't accepting 'name' property - php

I am trying to pass in "name" in my "friends" through my controller.
I have already made a "names" table with names in it
I keep getting "Trying to get property 'name' of non-object" This error.
Here's my FriendsController:-
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Friend;
use Illuminate\Support\Facades\Auth;
use App\Name;
class FriendsController extends Controller
{
public function store(Request $request)
{
$name = Name::all()->random(1)[0]->name;
Friend::create([
'my_id'=>Auth::user()->id,
'friends_id'=>$request->friends_id,
'name' => $name->name,
]);
Friend::create([
'friends_id'=>Auth::user()->id,
'my_id'=>$request->friends_id,
'name' => $name->name,
]);
return redirect('/home');
}
}
Here's my friends table:-
public function up()
{
Schema::create('friends', function (Blueprint $table) {
$table->id();
$table->string('my_id');
$table->string('friends_id');
$table->string('name')->nullable();
$table->timestamps();
});
}
Here's My Names table:-
public function up()
{
Schema::create('names', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->timestamps();
});
}
Can anyone please help me?

'name' => $name should be correct as Tim mentioned. If it wasn't saved into your database, it was probably because name column is guarded in your model.
Try adding protected $guarded=['id']; or protected $fillable=['name'];in your Friend Model and see if that works. To know more about this, You can check laravel's Mass Assignment. Cheers :)

Here's The Solution:-
public function store(Request $request)
{
$name = Name::inRandomOrder()->first()->name;
Friend::create([
'my_id'=>Auth::user()->id,
'friends_id'=>$request->friends_id,
'name' => $name,
]);
Friend::create([
'friends_id'=>Auth::user()->id,
'my_id'=>$request->friends_id,
'name' => $name,
]);
return redirect('/home');
}
}

Related

Laravel table update issue General error: 1364 Field 'start_date' doesn't have a default value

hope you are safe and doing well. I am facing an issue with laravel relational table. I have three table, USER, CLIENT ,ORDER and CAR_PARKING. Now Client is related to user and ORDER is related to both Client and USER while CAR_PARKING related to ORDER only. What i am facing like issue is that when I am trying to update table ORDER it says #General error: 1364 Field 'start_date' doesn't have a default value#
Below are my different table models and controller
public function updateOrderCarParking(Request $request, $id)
{
if (Auth::check()) {
$carParkingData = $request->only('removed', 'removed_date');
$validateCarParking = Validator::make($carParkingData, [
'removed' => 'required|boolean',
'removed_date' => 'nullable'
]);
if ($validateCarParking->fails()) {
return response()->json($validateCarParking->errors(), 422);
}
$orderData = $request->only('paid', 'amount_paid', 'overdue', 'currency', 'user_id');
$validateOrder = Validator::make($orderData, [
'amount_paid' => 'required|regex:/^\d*+(\.\d{1,2})?$/',
'currency' => [
'required',
Rule::in(['USD', 'CAD'])
],
"paid" => "required|boolean",
'overdue' => 'regex:/^\d*+(\.\d{1,2})?$/'
]);
if ($validateOrder->fails()) {
return response()->json($validateOrder->errors(), 422);
}
$updateCarParking = CarParking::updateOrCreate([
'removed' => $request->removed,
'removed_date' => $request->removed_date,
]);
$order = Order::find($id);
$order->carParkings()->save($updateCarParking);
$updateOrder = Order::find($id);
$updateOrder->amount_paid = $request->amount_paid;
$updateOrder->paid = $request->paid;
$updateOrder->currency = $request->currency;
$updateOrder->overdue = $request->overdue;
$updateOrder->user_id = Auth::user()->id;
$updateOrder->save();
if ($order && $updateOrder) {
return response()->json([
'success' => true,
'message' => 'Order updated successfully',
'data' => $order
], Response::HTTP_OK);
}
} else {
return response()->json([
'success' => false,
'message' => 'Can not update',
], Response::HTTP_UNAUTHORIZED);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
use HasFactory;
protected $fillable = ['order_type', 'amount_paid','client_id', 'user_id', 'price', 'currency', 'paid', 'overdue'];
public function user()
{
return $this->belongsTo(User::class);
}
public function client()
{
return $this->belongsTo(Client::class);
}
public function carParkings(){
return $this->hasMany(CarScrap::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class CarParking extends Model
{
use HasFactory;
protected $fillable = ['start_date', 'end_of_free_charge', 'order_id', 'removed', 'removed_date'];
public function order()
{
return $this->belongsTo(Order::class);
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->decimal('price', 8, 2);
// $table->date('start_date');
$table->enum('order_type', ['Storage rent', 'Forklift', 'Ramp', 'Car Parking', 'Car Scrap', 'Shipping']);
$table->enum('currency', ['USD', 'CAD']);
$table->boolean('paid')->default('0');
$table->decimal('amount_paid')->default(0);
$table->decimal('overdue')->nullable();
$table->foreignId('client_id')->constrained('clients')->onDelete('cascade');
$table->foreignId('user_id')->constrained('users')->onDelete('cascade');
$table->timestamps();
});
Schema::enableForeignKeyConstraints();
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('orders', function (Blueprint $table) {
$table->dropConstrainedForeignId("client_id");
$table->dropConstrainedForeignId("user_id");
});
Schema::dropIfExists('orders');
}
}
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCarParkingsTable extends Migration
{
public function up()
{
Schema::create('car_parkings', function (Blueprint $table) {
$table->id();
$table->date('start_date');
$table->date('end_of_free_charge');
$table->boolean('removed')->default("0");
$table->date('removed_date')->nullable();
$table->timestamps();
$table->foreignId('order_id')->constrained('orders')->onDelete('cascade');
});
Schema::enableForeignKeyConstraints();
}
public function down()
{
Schema::table('car_parkings', function (Blueprint $table) {
$table->dropConstrainedForeignId("order_id");
});
Schema::dropIfExists('car_parkings');
}
}
What am I doing wrong?
Replace your existing method with this:
class CreateCarParkingsTable extends Migration
{
public function up()
{
Schema::create('car_parkings', function (Blueprint $table) {
$table->id();
$table->date('start_date')->nullable();
$table->date('end_of_free_charge');
$table->boolean('removed')->default("0");
$table->date('removed_date')->nullable();
$table->timestamps();
$table->foreignId('order_id')->constrained('orders')->onDelete('cascade');
});
Schema::enableForeignKeyConstraints();
}
public function down()
{
Schema::table('car_parkings', function (Blueprint $table) {
$table->dropConstrainedForeignId("order_id");
});
Schema::dropIfExists('car_parkings');
}
}
If you get error for any other field then make it nullable as I had done in start_date
Set start_date to Nullable in Database Migration.
Example:
$table->date('start_date')->nullable();
How can we imagine that only two lines of code have solved the errors. No need of setting nullable on any column. I got the solution by doing this code below:
$client = Client::findOrFail($client->id);
$client->update($request->all());
But i put in the model the relationships function. I meant in the CLIENT model i put
public function orders(){
return $this->hasMany(Order::class);
}
same thing for order model

laravel migration changes not reflecting

i changed my post_id foreign key to posts_id in images migration in order for the relationship to work. however after changing, the insertion of images in images table is still picking post_id which is giving me an error column not found. i tried cache:clear and config but nothing worked. post_id is nowhere in my code
postcontroller
public function store( Request $request )
{
$data = request()->validate([
'user_id' => 'required',
'about' => 'required',
'category' => '',
'expire_date' => '',
]);
if (Auth::guard('web')->check())
{
$user = Auth::user();
$post = new Post();
/*$post = $user->posts()->create([
'about' => $data['about'],
'category' => $data['category'],
'expire_date' => $data['expire_date'],
]);*/
if($request->hasFile('image'))
{
$files = $request->file('image');
foreach($files as $file)
{
$name = time().'-'.$file->getClientOriginalName();
$name = str_replace('','-',$name);
echo $name;
$file->move('images',$name);
$post->images()->create(['image' => $name ]);
}
}
$user = Auth::guard('web')->id() ;
return redirect()->route('home',['user'=>$user]);
}
}
postmodel
public function posts()
{
return $this->belongsTo(User::class);
}
images model
class images extends Model
{
protected $fillable = [
'posts_id',
'image'
];
public function posts(){
return $this->belongTo(Posts::class);
}
}
posts migration
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->uuid('user_id')->nullable;
$table->uuid('admin_id')->nullable;
$table->string('category')->nullable;
$table->string('about');
$table->timestamps();
});
}
images migration
public function up()
{
Schema::create('images', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('posts_id');
$table->string('image');
$table->timestamps();
$table->index('posts_id');
});
}
Try to change Images model
public function posts(){
return $this->belongTo(Posts::class);
}
to
public function posts(){
return $this->belongTo(Posts::class, 'posts_id');
}
Why would you change it? Laravel can handle this for you if leave it to post_id. Otherwise you’ll have to update the relation posts in your images model by adding extra arguments. See the documentation: laravel.com/docs/7.x/eloquent-relationships
public function posts(){
return $this->belongTo(Posts::class, 'posts_id');
}

Laravel : Doesn't have a default value - KeyProduct with Faker

I can't add a keyproduct when i'm creating a new product.
I get the error SQLSTATE[HY000]: General error: 1364 Field 'category_id' doesn't have a default value (SQL: insert into `products` (`activation_key`, `updated_at`, `created_at`) values (57394cd3-54f8-3e95-a951-e11f029fa0f5, 2020-05-27 17:09:08, 2020-05-27 17:09:08))
I don't know why, it asks me that.
What I tried :
category_id is my first column that i'm adding in my table. If I put ->nullable() to category_id , I get the same error with name that is the next column in my table.
This is imy code :
ProductController
public function store(Request $request)
{
$inputs = $request->except('_token');
$quantity = $inputs['quantity'];
factory(KeyProduct::class, $quantity)->create();
foreach ($inputs as $key => $value) {
$home->$key = $value;
}
$home->image=$path;
$home->save();
return redirect('admin/gamelist');
}
Product_table
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('category_id')->unsigned();
$table->string('name');
$table->string('image')->nullable();
$table->string('activation_key')->nullable();
$table->timestamps();
});
KeyProduct_table.php
Schema::create('key_products', function (Blueprint $table) {
$table->increments('id');
$table->string('activation_key');
$table->timestamps();
});
Keyproduct.php
public function products()
{
return $this->HasOne('App\Product')->withPivot('quantity');
}
Product.php
class Product extends Model
{
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function keyProduct()
{
return $this->HasOne('App\KeyProduct');
}
protected $fillable = ['quantity'];
}
KeyProductFactory.php
use App\KeyProduct;
use App\Product;
$factory->define(KeyProduct::class, function (Faker $faker) {
$product = factory(Product::class)->create();
return [
'activation_key' => $product->activation_key,
];
});
ProductFactory.php
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
return [
'activation_key' => $faker->uuid
];
});
CategoryFactory
use App\Category;
use Faker\Generator as Faker;
$factory->define(Category::class, function (Faker $faker) {
return [
'activation_key' => $faker->uuid
];
});
Thanks for your help.
It fails because the product is created without you setting that category_id or name at the time of creation. Make them nullable() or change your creation method accordingly.
In your SQL you provided values for "activation_key", "updated_at" and "created_at" columns only, so other fields must satisfy at least one statement:
have an AUTO_INCREMENT option;
have a DEFAULT value;
allow NULL values.
You haven't provided enough data to complete the query.
Add more $fillables to your Product.php Model. By looking at your migrations it should look like this:
protected $fillable = [
'category_id', 'name', 'image', 'activation_key', 'quantity'
];

How to add table that has foreign key value referring to another table in laravel?

Model 1:
namespace App;
use Illuminate\Database\Eloquent\Model;
class productDescription extends Model
{
protected $table="ProductDescription";
protected $connection="mysql";
public function productPricing()
{
return $this->belongsTo(priceInfo::class);
}
public function salesPackage()
{
return $this->hasMany(packageModel::class);
}
}
Model2:
class packageModel extends Model
{
//
protected $table="subSalesPackage";
protected $connection="mysql";
public function product_description(){
return $this->belongsTo(productDescription::class);
}
}
Controller:
public function addProductDetails(Request $formdescription,$dataId)
{
$description=new productDescription;
$description->deviceCategoryId=$dataId;
$description->productdescriptionid=$this->getproductDescriptionId();
$description->modelName=$formdescription->input('mname');
$description->batteryType=$formdescription->input('batteryType');
//$description->salesPackage =$formdescription->input('package');
$description->skillSet =$formdescription->input('skillSet');
$description->Colour=$formdescription->input('colour');
$description->Material =$formdescription->input('material');
$description->maxAge=$formdescription->input('maxage');
$description->minAge =$formdescription->input('minage');
//$product->productPricing()-save($priceInfo);
//$product->productDetails()->save($description);
$description->save();
$salesPackage=new packageModel;
$salesPackage->salesPackage=$formdescription->input('package');
**$salesPackage->product_description()->associate($description);**
$salesPackage->save();
//echo("success");
return response()->json([
'modelName' => $formdescription->mname,
'colour' => $formdescription->colour,
'rechargable' => $formdescription->rechargable,
'batteryType' => $formdescription->batteryType
]);
//$description->product()->associate($priceInfo);
}
Migration->productdescription:
public function up()
{
//
Schema::create('ProductDescription', function (Blueprint $table) {
$table->engine='InnoDB';
$table->string('productdescriptionid')->primary();
$table->string('product_id');
$table->string('salesPackage');
$table->timestamps();
$table->index(['productDescriptionId']);
});
}
This is my migration for 1st table(model).It has the primary key as'productdescriptionid'.
Migration->subSalespackage
public function up()
{
//
Schema::create('subSalesPackage', function (Blueprint $table) {
$table->increments('id');
$table->string('product_description_id');
$table->string('salesPackage');
$table->foreign('product_description_id')-
>references('productdescriptionid')->on('ProductDescription');
$table->timestamps();
$table->index(['id']);
});
}
Here I have referred the productdescriptionid as foreign key.And when I add this salespackage table,the values should get added with the value of productdescriptionid(productDescription).
But the error i'm getting is can't able to add or update a child row.
You should try this:
return response()->json([
'SKUID' => $priceInfo->SKUID,
'listingStatus' => $priceInfo->listingStatus,
'MRP' => $priceInfo->MRP,
'sellingPrice' => $priceInfo->sellingPrice,
'id' =>$this->getproductId()
]);

Laravel One to many CRUD Example

I am new to Laravel. I want to insert data to certain master detail tables with Laravel4. I searched all over the internet and could not find a proper solution.
I have two (plus one) tables as shown below.
PO_HEADER
PO_HEADER_ID
SUBJECT
PO_DATE
PO_DETAIL
PO_DETAIL_ID
PO_HEADER_ID
DESCRIPTION
AMOUNT
QTY
UNIT_OF_MEASURE_ID
UNIT_OF_MEASURE
UNIT_OF_MEASURE_ID
UNIT_OF_MEASURE
I should be able to insert the PO master along with as many PO detail records in one shot while pressing a SAVE BUTTON. Unit of measure in the detail section should be a drop down list (filled from the UNIT_OF_MEASURE table)
Kindly suggest how to achieve this easily. Thanks in advance!
This depends on your models being set up correctly:
class PurchaseOrder extends \Eloquent
{
protected $fillable = [
'subject',
'date'
];
public function detail()
{
return $this->hasMany('PurchaseOrderDetail');
}
}
class PurchaseOrderDetail extends \Eloquent
{
protected $fillable = [
'description',
'amount',
'qty'
];
protected $with = [
'unitOfMeasure',
];
public function header()
{
return $this->belongsTo('PurchaseOrder');
}
public function unitOfMeasure()
{
return $this->hasOne('UnitOfMeasure');
}
}
class UnitOfMeasure extends \Eloquent
{
protected $fillable = [
'name'
];
public function lineItems()
{
return $this->belongsToMany('PurchaseOrderDetail');
}
}
You also need to set up your migrations using the proper settings, like so:
//migration for purchaseorder table
public function up()
{
Schema::create('purchaseorders', function(Blueprint $table)
{
$table->increments('id');
$table->string('subject');
$table->string('date');
$table->timestamps();
});
}
//migration for purchaseorderdetail table
public function up()
{
Schema::create('purchaseorderdetails', function(Blueprint $table)
{
$table->increments('id');
$table->integer('purchaseorder_id')->unsigned()->index();
$table->integer('unitofmeasure_id')->unsigned()->index();
$table->foreign('purchaseorder_id')->references('id')->on('purchaseorders');
$table->string('description');
$table->float('amount');
$table->float('qty');
$table->timestamps();
});
}
//migration for unitsofmeasure table
public function up()
{
Schema::create('unitsofmeasure', function(Blueprint $table)
{
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
That should get you fairly close to what you need, I hope. :) You can then query for your items like so:
$po-details = PurchaseOrderDetail::with(['purchaseOrder', 'unitOfMeasure')->find($id);
This is what an overly simplified controller method may look like:
class PurchaseOrderController
{
public function show($id)
{
$purchaseOrders = PurchaseOrder::with('detail')->find($id);
return View::make('purchaseOrder.show', compact('purchaseOrders'));
}
}
And then your view:
#foreach ($purchaseOrders as $purchaseOrder)
#foreach ($purachseOrder->detail as $lineItem)
#endforeach
#endforeach

Categories