Inserting values to a form with relationship in laravel (Referring projectid) - php

There is a a single form which takes in details and save it to 4 different tables in db. Project, Events, Donation and Opportunities. Project has many Events, many Donation and many Opportunities. I want to use the project id in other tables as well. but when I save the Form the details are stored in each 4 tables but the project is not been taken for the other 3 tables Events, Donation and Opportunity. Its value is 0. How to take that particular project id(auto-increment) in all other three tables.
My ProjectController is like this:
class ProjectController extends Controller
{
public function getProject()
{
return view ('other.project');
}
public function postProject(Request $request)
{
$this->validate($request, [
'ptitle' => 'required|max:200',
'pdescription' => 'required',
'etitle' => 'required|max:200',
'edetails' => 'required',
'dtotal' => 'required',
'oposition' => 'required|max:100',
'odescription' => 'required',
]);
Project::create([
'ptitle' => $request->input('ptitle'),
'pdescription' => $request->input('pdescription'),
'pduration' => $request->input('pduration'),
'psdate' => $request->input('psdate'),
'pedate' => $request->input('pedate'),
'pcategory' => $request->input('pcategory'),
'pimage' => $request->input('pimage'),
]);
Event::create([
'pro_id' => $request->input('pid'),
'etitle' => $request->input('etitle'),
'pdetails' => $request->input('pdetails'),
'edate' => $request->input('edate'),
'etime' => $request->input('etime'),
'elocation' => $request->input('elocation'),
'eimage' => $request->input('eimage'),
]);
Donation::create([
'pro_id' => $request->input('pid'),
'dtotal' => $request->input('dtotal'),
'dinhand' => $request->input('dinhand'),
'dbankaccount' => $request->input('dbankaccount'),
]);
Opportunity::create([
'pro_id' => $request->input('pid'),
'oposition' => $request->input('oposition'),
'odescription' => $request->input('odescription'),
'olocation' => $request->input('olocation'),
'odeadline' => $request->input('odeadline'),
]);
return redirect()
->route('home')
->with('info', 'Your project has been created.');
}
My Project Model:
class Project extends Model
{
use Notifiable;
protected $fillable = [
'ptitle',
'pdescription',
'pduration',
'psdate',
'pedate',
'pcategory',
'pimage',
];
public function events()
{
return $this->hasMany('Ngovol\Models\Event', 'pro_id');
}
public function donations()
{
return $this->hasMany('Ngovol\Models\Donation', 'pro_id');
}
public function opportunities()
{
return $this->hasMany('Ngovol\Models\Event', 'pro_id');
}
protected $hidden = [
];
}
Event Model:
class Event extends Model
{
use Notifiable;
protected $table = 'events';
protected $fillable = [
'pro_id',
'etitle',
'edetails',
'edate',
'etime',
'elocation',
'eimage',
];
public function projects()
{
return $this->belongsTo('Ngovol\Models\Project', 'pro_id');
}
}
Donation Model:
class Donation extends Model
{
use Notifiable;
protected $fillable = [
'pro_id',
'dtotal',
'dinhand',
'drequired',
'dbankaccount',
];
protected $hidden = [
];
public function projects()
{
return $this->belongsTo('Ngovol\Models\Project', 'pro_id');
}
}
Opportunity Model:
class Opportunity extends Model
{
use Notifiable;
protected $fillable = [
'pro_id',
'oposition',
'odescription',
'olocation',
'odeadline',
];
protected $hidden = [
];
public function projects()
{
return $this->belongsTo('Ngovol\Models\Project', 'pro_id');
}
}

Better try following code
$project = Project::create( $request->only(['ptitle', 'pdescription', 'pduration', 'psdate', 'pedate', 'pcategory', 'pimage']));
$project->events()->create( $request->only(['etitle', 'pdetails', 'edate', 'etime', 'elocation', 'eimage']));
$project->donations()->create($request->only(['dtotal', 'dinhand', 'dbankaccount']));
$project->opportunities()->create($request->only(['oposition','odescription','olocation','odeadline']));

Related

how to save a collection of items( subjects ) into a list and save in a database

i have created student and subject models and their CRUD
how do i register a collection of subject_id for a student
i have created a new model 'Registration' with subject_id and student_id but i don't how to add a collection of subject_id's to students
This is my student model
class Student extends Model
{
protected $table = 'students';
protected $fillable = [
'firstname','middlename','lastname','index_no','parent_id',
'regular_or_weekend',
'course_id',
'nationality',
'image'
]
public function subjects()
{
return $this->hasMany(Subject::class);
}
}
this is my subject class
class Subject extends Model
{
protected $table = 'subjects';
protected $fillable = ['subject_code','subject_name','credit_hours'];
protected $cast =[
'credit_hours' => 'Integer',
];
public function student()
{
return $this->belongsTo(Student::class);
}
}
In has many relationships you should do something like this:
$student = Student::find(1);
$student->subjects()->createMany([
[
'subject_code' => 'code',
'subject_name' => 'name',
'credit_hours' => 'hours'
],
[
'subject_code' => 'code',
'subject_name' => 'name',
'credit_hours' => 'hours'
],
]);

LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation

I'm supposed to display author details in bookformat method. But facing LogicException. Any suggestions thanks in advance. Im getting error like this LogicException in Model.php line 2709: Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation. Any help that would be great for me. If I comment authors in bookFormat() everything works fine. But Idk why I'm unable to get author details in my bookformat().
#booksController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use App\Models\Book;
use App\Models\Author;
class BooksController extends Controller
{
public function index()
{
$books = Book::all();
$results = [];
foreach ($books as $book) {
$results [] = $this->bookFormat($book);
}
return $results;
}
public function bookFormat($book){
return [
'Id' => $book->id,
'Title' => $book->title,
'Author' => [
'Id' => $book->author->id,
'First_name' => $book->author->first_name,
'Last_name' => $book->author->last_name
],
'Price' => $book->price,
'ISBN' => $book->isbn,
'Language' => $book->language,
'Year' => $book->year_of_publisher
];
}
}
//book.php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
public $timestamps = TRUE;
protected $table = 'books';
//rules
public static $rules = [
'title' => 'required|max:255',
'isbn' => 'required|max:50',
'author_id' => 'required|max:255',
'language' => 'required|max:255',
'price' => 'required|max:255',
'year_of_publisher' => 'required'
];
//relationship
public function author() {
$this->belongsTo(Author::class);
}
}
Instead of:
public function author() {
$this->belongsTo(Author::class);
}
you should have:
public function author() {
return $this->belongsTo(Author::class);
}
Notice the return difference.

Laravel 5.3: Eloquent hasMany update

I need to update the items for specific order with Eloquent.
I have this models:
class Orders extends \Illuminate\Database\Eloquent\Model
{
public $timestamps = false;
protected $fillable = ['items_array'];
public function items()
{
return $this->hasMany(Items::class, 'order_id', 'order_id');
}
public function setItemsArrayAttribute($data)
{
$this->items()->whereIn('article_id', array_map(function($item){
return $item['article_id'];
}, $data['items']))->update($data);
}
}
class Items extends \Illuminate\Database\Eloquent\Model
{
protected $table = 'order_to_items';
public $timestamps = false;
protected $fillable = ['internal_code'];
public function order()
{
return $this->belongsTo(Orders::class, 'order_id', 'order_id');
}
}
I have the api response like that:
$response = [
'message'=>'some',
'order_id'=>'111-222-333',
'items'=>[
[
'article_id' => 'R-320108',
'internal_code' => 333
],
[
'article_id' => 'R-320116',
'internal_code' => 444
],
]
];
So I make this
$order = Orders::where('order_id', $response['order_id'])->with('items')->first();
and I was trying to make this:
$order->update([
'is_sent' => true,
'items_array' => $response['items']
]);
but that doesn't work. Is there any way to match the related model with API response and make update?
Thanks!
You can use save():
$order->is_sent = true;
$order->items_array = $response['items'];
$order->save();
Or update():
$order = Orders::where('order_id', $response['order_id'])
->update([
'is_sent' => true,
'items_array' => $response['items']
]);

laravel factory insert foreign key

Hello everyone who's trying to help,
im trying to create the factory file to seeding my database and i have a question how can i insert a foreign key from a table already seeded ?
and the factory code is to have all in same file? any good pratice to this ?
Files
Model User
<?php
namespace App\Models;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
protected $table = 'user'; //name of the table in database
protected $primaryKey = 'Id'; //Primary Key of the table
/**
* Relations between tables
*/
public function GetLoginInfo()
{
return $this->hasMany('App\Models\LoginInfo', 'UserId');
}
public function getStatus()
{
return $this->belongsTo('App\Models\AccountStatus');
}
}
Model Account status
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AccountStatus extends Model
{
protected $table = 'account_status'; //name of the table in database
protected $primaryKey = 'Id'; //primary Key of the table
public $timestamps = false; //true if this table have timestaps
/**
* Relations between tables
*/
public function GetUsers()
{
return $this->hasMany('App\Models\Users', 'StatusId');
}
}
factory file:
<?php
/** #var \Illuminate\Database\Eloquent\Factory $factory */
//Factory for Account Status table
$factory->define(App\Models\AccountStatus::class, function (Faker\Generator $faker) {
return [
'Description' => $faker->word,
];
});
//Factory for user table
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => Factory(App\Models\AccountStatus::class)->create()->id,
];
});
This is what im trying to do as you can see : Factory(App\Models\AccountStatus::class)->create()->id but don't work
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => factory(App\Models\AccountStatus::class)->create()->id,
];
});
i see an uppercase F in factory..
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
$accountStatus = factory(App\Models\AccountStatus::class)->create()
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => $accountStatus->id,
];
});
Edit (Improvement)
If you have one model that depend on another model. you can do it this way, using a callback function to create with the related.
Like this
$factory->define(App\Models\User::class, function (Faker\Generator $faker) {
return [
'Username' => $faker->unique()->userName,
'Password' => bcrypt('test'),
'Email' => $faker->unique()->safeEmail,
'Name' => $faker->name,
'StatusId' => function () {
return factory(App\Models\AccountStatus::class)->create()->id;
}
];
});
One thing you need to keep in mind is that this will go to an endless loop if the related(Status Model) has a model that depends on the parent(User Model).

Why my own authentication doesn't work with my own model in Laravel?

I am using Laravel 4.2 and I'm trying to auth my own model (I don't use User model).
The problem appears when pass the mail and password, then I use the method Auth::attempt and enters to else (that it corresponds to the error)
Usuario Controller
class UsuarioController extends BaseController{
function doLogin(){
$userdata = array(
'Correo' => Input::get('correo'),
'Contrasena' => Input::get('contrasena')
);
if(Auth::attempt($userdata)){
echo 'SUCCESS!';
}else{
echo 'Error!';
}
} ...
Usuario Model
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Usuario extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'Usuario';
protected $primaryKey = 'idUsuario';
protected $fillable = array(
'Nombre',
'Apellido',
'Rol',
'Correo',
'Contarsena',
'Cumpleanos',
'Foto',
'Pais',
'Comuna',
'Profesion_idProfesion',
'Institucion_idInstitucion',
'remember_token'
);
function profesion(){
return $this->belongsTo('Profesion', 'idProfesion');
}
public function getPasswordAttribute()
{
return $this->Contrasena;
}
public function setPasswordAttribute($Contrasena)
{
$this->Contrasena= $Contrasena;
}
public function getReminderEmail()
{
return $this->Correo;
}
public function getRememberToken()
{
return $this->remember_token;
}
public function setRememberToken($value)
{
$this->remember_token = $value;
}
public function getRememberTokenName()
{
return 'remember_token';
}
public function getAuthIdentifier()
{
return $this->getKey();
}
public function getAuthPassword() {
return $this->Contrasena;
}
}
Auth.php
return array(
'driver' => 'eloquent', //database or eloquent
'model' => 'Usuario',
'table' => 'Usuario',
'username' => 'Correo',
'password' => 'Contrasena',
'reminder' => array(
'email' => 'emails.auth.reminder',
'table' => 'password_reminders',
'expire' => 60,
),
);
Usuario Table
The application never crash but in the If Condition always enter to the ''else'' returns Error!
You have a typo in your fillable array:
protected $fillable = array(
'Nombre',
'Apellido',
'Rol',
'Correo',
'Contarsena',
'Cumpleanos',
'Foto',
'Pais',
'Comuna',
'Profesion_idProfesion',
'Institucion_idInstitucion',
'remember_token'
);
Contarsena should be Contrasena
And your auth array should contain a email and password key:
$userdata = array(
'correo' => Input::get('correo'),
'password' => Input::get('contrasena')
);
try
dd(DB::getQueryLog());
to get the the SQL executed. That makes troubleshooting easier.
My guess is that there's no 'password' field, which the attempt method will automatically hash

Categories