I am beginner. I have small problem with Laravel Equolent.
I have migrations:
Schema::create('datas', function (Blueprint $table) {
$table->id();
$table->integer('number');
$table->timestamps();
});
and model:
class Data extends Model
{
protected $guarded = ['id'];
protected $fillable = [
'number'
];
protected $dates = [
'created_at',
'updated_at',
'date'
];
protected $casts = [
'number'=>'integer',
];
}
Normalny I make this code:
Data::get();
and this is return me all record from DB.
I need information how often does the number appear in the database.
For example:
Data->where('number', 1)->get();
Data->where('number', 15)->get();
Data->where('number', 55)->get();
etc
how wany can I count this result? ->count()?
If you need to count all the records in your Data model, you can use this code:
$count = Data::count();
But if you want to count specific number, try this:
$count = Data::where('number', $number)->count();
in the controller file Data::count();
Related
As you can see on the following image my laravel relation between shoporder and shoporderroutingstepplans is not as it has to be.
I have no idea what I exactly did wrong so I hope someone can help me out. In the code beneath I have left some fields out of the code to make it more legible.
class shoporder extends Model
{
protected $primaryKey = 'ID';
protected $fillable = [
'CADDrawingURL',
'ID',
'Costcenter',
'CostcenterDescription',
'Costunit',
'CostunitDescription',
'Created',
'Creator',
'CreatorFullName',
'Description',
'ShopOrderParent',
'ShopOrderParentNumber',
'ShopOrderRoutingStepPlanCount',
'Status',
'SubShopOrderCount',
];
public function shopOrderRoutingStepPlans() {
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
}
}
class ShopOrderRoutingStepPlan extends Model
{
protected $primaryKey = 'ID';
public $table = "shoporderroutingstepplans";
protected $fillable = [
'Account',
'ID',
'AccountName',
'AccountNumber',
'AttendedPercentage',
'Backflush',
'Created',
'Creator',
'CreatorFullName',
'Description',
'ShopOrder',
];
public function shopOrder() {
return $this->belongsTo('App\shopOrder', 'ShopOrder', 'ID');
}
}
This is the code Im executing to get the relations of 1 shoporder in the controller.
$orders = shopOrder::find('0600959e-6b92-4135-8ea8-1fa2fd92a916')->shopOrderRoutingStepPlans()->get();
In the shoporder migration I defined the primary key:
$table->string('ID')->unique();
$table->primary('ID');
In the shoporderroutingstepplans migration I defined the foreign key as followed.
$table->string('ID')->unique();
$table->primary('ID');
$table->foreign('ShopOrder')
->references('ID')
->on('shoporders');
You must switch the order of the last two parameters:
From
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ShopOrder', 'ID');
To
return $this->hasMany('App\shopOrderRoutingStepPlan', 'ID', 'ShopOrder');
The parameters are
model,
name of column in the linked model,
name of column in this model.
I am using Laravel Framework 5.5.22.
I am having users and tasks in my db. My tasks have the following schema:
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('user_id')->unsigned();
$table->timestamps();
});
My users model looks like the following
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
protected $hidden = [
'password', 'remember_token',
];
public function task()
{
return $this->hasMany('App\Task');
}
}
I would like to store the task from a user in the database. See below the store method I have tried:
public function store(Request $request)
{
$this->validate($request, [
'newTaskName' => 'required|min:3|max:190',
]);
Auth::user()->task()->Create($request->all()); //here I get the error
Session::flash('success', 'New task has been successfully added.');
return redirect()->route('tasks.index');
}
However, I get the following error at this line Auth::user()->task()->Create($request->all());:
Illuminate\Database\Eloquent\MassAssignmentException _token
Any suggestions why the request is not safed properly?
Try with DB
$insertData = [
"name" => $request->name,
"user_id" => \Auth::id()
];
DB::table('tasks')->insert($insertData);
OR if you have model created as Task
$task = new Task($insertData);
$task->save();
Use the ->except() method instead of all():
Auth::user()->task()->create($request->except('_token'));
at Task Model add this line :
protected $guarded = ['_token'];
TL;DR
Trying to get three models to interact using eloquent for a rest api.
User - belongsToMany(pulls)
Pull - belongsToMany(user) && belongsToMany(boxes)
Box - belongsToMany(pulls)
The pull_user table is working perfectly, I can just attach a user after I save a pull. Saving a box works fine but the attach doesn't work/enter anything into the pivot table (I get no errors though).
The Problem
I can't get a pivot table that associates two of my models together to attach() after a save. I have the three models listed above, the pivot is working for pull_user but not for pull_box even though the save for box is working perfectly. I am able to save a box without an error but the association just never occurs (no error).
The Code
pull_box.php
class PullBox extends Migration
{
public function up()
{
Schema::create('pull_box', function (Blueprint $table) {
$table->increments('id');
$table->timestamps();
$table->integer('pull_id');
$table->integer('box_id');
});
}
public function down()
{
Schema::dropIfExists('pull_box');
}
}
Pull.php
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box');
}
}
Box.php
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull');
}
}
BoxController.php
public function store(Request $request)
{
$this->validate($request, [
'user_id' => 'required|integer',
...
]);
$user_id = $request->input('user_id');
...
$box = new Box([
'user_id' => $user_id,
...
]);
$pull = Pull::whereId($pull_id)->first();
if($box->save()){
$pull->boxes()->attach($box->id);
$box->view_box = [
'href' => 'api/v1/box/' . $box->id,
'method' => 'GET'
];
$message = [
'msg' => 'Box created',
'box' => $box,
'pull' => $pull_id
];
return response()->json($message, 201);
}
$response = [
'msg' => 'Box creation error, contact supervisor',
];
return response()->json($response, 404);
}
The Solution
I need to know how I can get this association working. I am going to need to add a new layer in under the pull for Item, but I don't want to move one before I solve this. I think that my problem has to stem from a syntactical/logical error on my part but I can't see it. There are a bunch of questions on SO that are very close to giving me a solution, but after reading them I wasn't able to solve my problem.
Any help is appreciated.
Try renaming your pull_box table to box_pull, pivot tables on laravel must be in alphabetical order. If you want to use custom name on pivot table you have to extends your pivot, for example:
<?php
namespace App;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PullBox extends Pivot
{
protected $table = 'pull_box';
}
And your many to many relationships:
class Pull extends Model
{
protected $fillable = ['from', 'to', 'runit_id', 'start_time', 'end_time', 'box_count', 'pull_status', 'audit_status', 'status', 'total_quantity', 'accuracy'];
public function users(){
return $this->belongsToMany('App\User');
}
public function boxes(){
return $this->belongsToMany('App\Box')->using('App\PullBox');
}
}
class Box extends Model
{
protected $fillable = ['user_id','from', 'to', 'runit_id', 'start_time', 'end_time', 'pull_id', 'total_quantity', 'status', 'accuracy'];
public function pulls(){
return $this->belongsToMany('App\Pull')->using('App\PullBox');
}
}
I am doing project in Laravel. I have used laravel's eloquent model. I want to insert record into the database with timestamp values.
Here is my model 'Provider.php'
{
protected $primaryKey = 'provider_id';
protected $table = 'provider';
protected $fillable = [
'organization_name',
'email',
'website',
'mobile',
'landline',
'password',
'added_by'
];
public function cities(){
return $this->belongsToMany('App\City','provider_city','provider_id','city_id');
}
}
'City.php'
{
protected $primaryKey = 'city_id';
protected $table = 'city';
protected $fillable = ['state_id','name'];
}
and my controller method is as following,
{
$city_selection = $request->input('city_selection');
$provider = Provider::findOrFail($provider_id);
foreach ($city_selection as $city) {
$provider->cities()->attach($city['city_id']);
}
}
where city_selection is as below,
"city_selection":
[
{
"city_id": 1,
"name": "Pune"
},
{
"city_id": 3,
"name": "Bangalore"
}
]
After that when I tried to insert the record then all fileds i.e. provider_id and city_id filed goes properly into the database but the only problem is created_at and updated_at fields are still null.
I have used timpstamps(); while creating migration file. I don't know what's going wrong.
Any suggestions?
You need to add the dates mutators.
https://laravel.com/docs/5.3/eloquent-mutators#date-mutators
class Provider extends Model
{
/**
* The attributes that should be mutated to dates.
*
* #var array
*/
protected $dates = [
'created_at',
'updated_at',
'deleted_at'
];
}
Add timestamp in your Schema
$table->timestamps();
Your schema look like this
Schema::create('city', function(Blueprint $table){
$table->increments('id');
$table->integer('state_id')->unsigned();
$table->foreign('state_id')->references('id')->on('state');
$table->string('name', 100);
$table->timestamps();
});
Add following columns in your table schema.
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
created_at column will store value when record is inserted and updated_at will keep updated when any changes in this record(Any update in row).
Update
Use below code to update in new migration
public function up()
{
Schema::table('table_name', function($table) {
$table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
$table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP'));
});
}
I'm having troubles to setup the right Eloquent relationships (belongsTo, hasMany, ...) for a pivot table.
I will abbreviate code for clarity.
I have two important tables: 'parties' and 'p2p_relations'.
This is the migration for parties
public function up()
{
Schema::create('parties', function ($table) {
$table->increments('id');
$table->string('name');
$table->unsignedInteger('kind');
$table->timestamps();
$table->softDeletes();
$table->foreign('kind')->references('id')->on('kinds');
});
}
This is the migration for p2p_relations (party to party relations)
public function up()
{
Schema::create('p2p_relations', function ($table) {
$table->bigIncrements('id');
$table->unsignedInteger('context');
$table->unsignedInteger('reference');
$table->datetime('start');
$table->datetime('end')->nullable();
$table->unsignedInteger('kind')->nullable();
$table->timestamps();
$table->softDeletes();
$table->foreign('context')->references('id')->on('parties');
$table->foreign('reference')->references('id')->on('parties');
$table->foreign('kind')->references('id')->on('kinds');
});
}
The model for Party
class Party extends Ardent
{
use SoftDeletingTrait;
protected $softDelete = true;
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $table = 'parties';
public static $rules = array(
'name' => 'required',
'kind' => 'required|numeric'
);
}
The model for Relation
class Relation extends Ardent
{
use SoftDeletingTrait;
protected $softDelete = true;
protected $dates = ['created_at', 'updated_at', 'deleted_at'];
protected $table = 'p2p_relations';
public static $rules = array(
'context' => 'required|numeric',
'reference' => 'required|numeric',
'kind' => 'required|numeric',
'start' => 'required|date',
'end' => 'date'
);
}
How can I set relationships so I can associate parties as context or reference in a relationship.
I thought belongsTo will help like so in class Relation
public function context() {
return $this->belongsTo('Party', 'context', 'id');
}
public function reference() {
return $this->belongsTo('Party', 'reference', 'id');
}
But when I run this unit-test I get an error: Undefined property: Relation::$context
$context = new Party();
$context->name = 'Person A';
$context->kind = 1;
$context->save();
$ref = new Party();
$ref->name = 'Company B';
$ref->kind = 2;
$ref->save();
$relation = new Relation();
$relation->start = new DateTime();
$relation->context()->associate($context);
$relation->reference()->associate($ref);
$relation->kind = 3;
$relation->save();
Any thoughts? I'm really a newbie to this framework.
Thanks to the comments provided I've learned a lot :-)
Updated my Party Model:
public function references() {
return $this->belongsToMany('Party', 'p2p_relations', 'context', 'reference')
->withPivot('reference', 'start', 'kind')
->withTimestamps() ;
}
No Relation model needed.
The pivot table works perfectly.
Thanks