I'm new to laravel and just started creation of apis to connect to the database. I'm able to send a single entry at a time to the database, now what i want to do is to pass an array of data to be inserted into the database but don't seem to find my way around
Controller
public function newSaveUser(Request $request) {
$newFood = new Food;
$newFood->name = $request->name;
$newFood->save();
}
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model {
//
public $timestamps = false;
}
Try this here:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model
{
//
public $timestamps = false;
protected $fillable = ['name'];
}
and then to insert data:
Food::create([
'name' => $request->get('name')
]);
firstly check the db connection is works or not.
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model
{
//
public $timestamps = false;
protected $table = "write_table_name_here";
protected $guarded = [];
}
extend model in controller;
$newFood = new Food;
$newFood->name = $request->name;
$newFood->save();
Related
In my model file Category.php I am extending the Category Class...
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $guarded = [];
public $timestamps = false;
public $table = "category";
public function subcategories(){
return $this->hasMany(SubCategory::class)->orderBy('name');
}
}
class ProductCategory extends Category
{
public $table = 'product_categories';
}
But when i try to access the ProductCategory Model It is not available, am i forgetting an import somewhere?
$partcategories = PartCategory::orderBy('name')->get();
This is the error i get...
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'App\Http\Controllers\ProductCategory' not found
Thanks in advance!
Firstly, create a separate class file for the PartCategory, if you haven't already.
namespace App;
class ProductCategory extends Category
{
public $table = 'product_categories';
}
Secondly, where you are using the model, make sure you are importing the PartCategory class correctly:
use App\PartCategory;
Then you can use the model as you had:
$partcategories = PartCategory::orderBy('name')->get();
I am Trying to get data from mysql and mongodb in laravel framework.I am using HybridRelations to fetch data realated data but I stuck.please help me.
I got Error like that.
Call to undefined relationship [Country] on model [App\Models\State].
Here is my code.
country model;
namespace App;
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\Model as Eloquent;
class Country extends Eloquent
{
protected $connection = 'mongodb';
protected $collection = 'countries';
protected $fillable = [ 'country' ];
public function country()
{
return $this->hasMany(State::class,'country_id');
}
}
my state model:
<?php
namespace App\Models;
use Jenssegers\Mongodb\Eloquent\HybridRelations;
use Illuminate\Database\Eloquent\Model;
class State extends Model
{
use HybridRelations;
protected $connection = 'mysql';
protected $table = 'state';
protected $primaryKey = 'state_id';
protected $fillable = [ 'name','code','status' ];
public function state()
{
return $this->belongsTo(Country::class, '_id');
}
}
I'm quite new to Laravel and now I'm trying to move parts of a former application from a small self written framework into Laravel. The address book is multilingual therefor the table structure is a little more complicated.
db-structure
And this is my source code:
AddressBookController.php
namespace App\Http\Controllers;
use App\AddressBook as AB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class AddressBookController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$entries = AB::all();
return view('addressBook')->with([
'class' => __CLASS__,
'function' => __FUNCTION__,
'line' => __LINE__,
'entries' => $entries,
]);
}
}
Model AddressBook.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class AddressBook extends Model
{
protected $table = 'address';
protected $primaryKey = 'address_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
protected $searchable = [
'columns' => [
'address.address_surname' => 10,
'address.address_company' => 5,
'address.address_vatid' => 2,
],
];
public function country() {
return $this->hasOne('country', 'country_id', 'country_id');
}
public function addresstype() {
return $this->hasOne('addresstype', 'addresstype_id', 'addresstype_id');
}
}
Model Country.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Country extends Model
{
protected $table = 'country';
protected $primaryKey = 'country_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
public function translation() {
return $this->hasOne('translations', 'translations_id', 'translations_id');
}
public function addressbook() {
return $this->belongsTo('address', 'country_id', 'country_id');
}
}
Model AddressType
namespace App;
use Illuminate\Database\Eloquent\Model;
class AddressType extends Model
{
protected $table = 'addresstype';
protected $primaryKey = 'addresstype_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
public function translation() {
return $this->hasOne('translations', 'translations_id', 'translations_id');
}
public function addressbook() {
return $this->belongsTo('address', 'addresstype_id', 'addresstype_id');
}
}
Model Translation.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Translation extends Model
{
protected $table = 'translations';
protected $primaryKey = 'translations_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
public function country() {
return $this->belongsTo('country', 'translations_id', 'translations_id');
}
public function addresstype() {
return $this->belongsTo('addresstype', 'translations_id', 'translations_id');
}
}
The request "$entries = AB::all();" works in general but I get the id's and maybe I'm completely wrong here but I thought that data from foreign keys will be replaced with the respective models (if configured correctly). so my question is:
a. did I make a mistake during configuration and if yes, where exactly is the error?
or
b. is my assumption of replacing id's with objects is completly wrong?
Thanks in advance!
Steve
Laravel Eloquent models do not replace the foreign keys of the active records with the relational data, it only appends a new property with the same name as the method relating the classes and in that property it puts all the Model instances of the resulted query, this ONLY if you access the property, its called Eager Loading.
It is explained here (Ofiicial Documentation)
$addressBook = App\AddressBook::find(1); //this only will return the active record with the id 1 and nothig more.
$addressBook->country; // The property "country" does not exist in the AddressBook Classs but eloquent models will return a "fake" property with the value of the result of the query by the method with the same name (only if the method returns an Eloquent Relation).
This Eloquent behavior is natural, and is a very clever way to minimize the number of queries, Eloquent will never load a relation if there is no need to.
If you want to load a relation in a set the models at the same time that those models are retriving from the db you need to explicitly especify wich relations you want to load.
$addressBook = App\AddressBook::with(['country', 'addresstype', 'anotherRelation'])->get(); // this will retrive all the addressBook models and in each one will attach the relations specified.
[EDITED]
Also you have to place the entire namespace of the related model class in the relation methods so you need to replaced like:
class Translation extends Model
{
protected $table = 'translations';
protected $primaryKey = 'translations_id';
protected $keyType = 'int';
public $incrementing = true;
public $timestamps = false;
// ****** You need to put the entire namespace of the Model class
public function country() {
return $this->belongsTo('App\Country', 'translations_id', 'translations_id');
}
I have company, employee and motorCycle table.
One Company has many employee. One employee has One motorCycle
Company.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Company extends Model
{
protected $table = 'company';
protected $primaryKey = '_id';
public function employee()
{
return $this->hasMany(Employee::class);
}
}
?>
Employee.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
protected $table = 'employee';
protected $primaryKey = '_id';
public function motorCycle()
{
return $this->hasOne(MotorCycle::class, 'motorCycle', 'id');
}
}
?>
MotorCycle.php
<?php
namespace App\Model;
use Illuminate\Database\Eloquent\Model;
class MotorCycle extends Model
{
protected $table = 'motorCycle';
protected $primaryKey = 'id';
public function employee()
{
return $this->belongsTo('MotorCycle::class');
}
}
?>
I would like to fetch result in controller like below
public function show(Company $company)
{
return $company->employee()->offset(0)->limit(20)->motorCycle()->get();
}
I am trying to browse this URL http://127.0.0.1:8000/api/comapanys/1
My route is like below
Route::apiResource('comapanys', 'ComapanyController');
what kind of result do you want to display? you want to have a list of employees and his/her motorcycle in a certain company?
may you can return a query like this.
public function show(Company $company)
{
return $company->employee()->with('motorCycle')->offset(0)->limit(20)->get();
}
There is to many problem in your code.
First, for example you write class company extends Model but in controller you use Company $company. Also for class employee class employee extends Model but in motoCycle class return $this->belongsTo('App\Model\Employee');. Use naming convention like first letter uppercase for model name .
Second, im not sure but I dont think you can chain eloquent methods like this return $company->employee()->offset(0)->limit(20)->motorCycle()->get();. Offset and limit should be on the end of chain.
Also use (Employee::class) instead of ('App\Model\Employee')
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Task extends Model
{
protected $dates = ['due_date'];
protected $fillable = ['name', 'project_id'];
public function scopeDueInDays($query,$days)
{
return $query->where('due_date', '>', \Carbon\Carbon::now()
->subDays($days));
}
static public function dueInDays($days)
{
return Task::where('due_date', '>', \Carbon\Carbon::now()
->subDays($days));
}
}
I want to go to method definition on vscode editor.
I can't this with scopeMethod.
Then i create static method. it works. at least until now, fine.
can use static method like below
$task = new Task;
$tasks = $task->dueInDays($day)->get();
$tasks = Task::dueInDays($day)->get();
this way is have problem on using laravel?
is anyone to using static method without scopeMethod?