Update object in relations in Laravel - php

I am beginner in Laravel. I use in my project Laravel 5.8.
I have this code :
class Client extends Authenticatable
{
use SoftDeletes, Deactivation, Notifiable;
protected $fillable = [
'email',
'email_verified_at',
'password_assigned_at',
'verify_token',
'password',
'type'
];
protected $hidden = [
'password',
'verify_token',
'remember_token',
];
protected $dates = [
'password_assigned_at',
'email_verified_at',
'created_at',
'updated_at',
'deactivated_at',
'deleted_at',
];
public function invoiceAddress()
{
return $this->hasOne('App\Models\Addresses', 'client_id', 'id');
}
}
and Adress:
class Addresses extends Model
{
use SoftDeletes;
protected $fillable = [
'user_id',
'company_name',
'nip',
'address',
'city',
'postal_code'
];
protected $dates = [
'deleted_at'
];
public function client()
{
return $this->belongsTo(Client::class);
}
}
In controller I have:
$bla = Client::with('invoiceAddress')->where('id', 1)->get();
I want update object in relation invoiceAddress.
I make code to normal update. I try this code:
$data = [
'client_id' => $id,
'company_name' => $request->input('company_invoice_company_name'),
'nip' => $request->input('company_invoice_nip'),
'address' => $request->input('company_invoice_address'),
'city' => $request->input('company_invoice_city]'),
'postal_code' => $request->input('company_invoice_postal_code'),
];
$client->invoiceAddress()->update($data);
but this is not working. How can I make it?
I need update object in relation. My code not working

In your $fillable of Addresses is saying user_id and in relationship you've used client_id
change client_id to user_id
public function invoiceAddress()
{
return $this->hasOne('App\Models\Addresses', 'user_id', 'id');
}
One more issue I can see is you're using get() method it should be first();
$bla = Client::with('invoiceAddress')->where('id', 1)->first();
$bla->invoiceAddress()->update($data);

Related

Laravel authenticate always fails without default user

I'm doing something wrong?
My If (Auth::attempt($validated)) {} always fails when I change default user. But work with default user. Maybe i forgot any config in my new user 'personal'?
config/auth.php
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Personal::class,
],
App/Models/Personal.php
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
class Personal extends Authenticatable
{
use HasFactory;
protected $table = 'personals';
protected $fillable = [
'name',
'email',
'password',
];
protected $hidden = [
'password',
'remember_token',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
}
App\Http\Requests\AuthRequest.php
use Illuminate\Foundation\Http\FormRequest;
class AuthRequest extends FormRequest
{
public function authorize()
{
return true;
}
public function rules()
{
return [
'email' => 'required|email',
'password' => 'required'
];
}
}
App\Http\Controller\AuthController.php
public function login(AuthRequest $request)
{
$validated = $request->validated();
if ($validated) {
\Log::info($validated); //<- so far it works
if (Auth::attempt($validated)) { //<- this if always fails with personal model, but it work with default user model
\Log::info('test');
$personal = Auth::user();
return redirect()->route('dashboard');
}
return redirect()->back()->withInput()->withErrors(['algo deu errado']);
}
return redirect()->back()->withInput()->withErrors(['Preencha todos os campos']);
}
$validated = [ 'email' => 'teste#outlook.com', 'password' => 'teste123', ];

BadMethodCallException Call to undefined method App\Models\User::role()

I code a attendance employee system to load reports of time employers
i got below error
What should I do to solve this problem?
BadMethodCallException
Call to undefined method App\Models\User::role()
Did you mean App\Models\User::only() ?
my user.php model:
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use Notifiable;
protected $fillable = [
'name',
'email',
'password',
];
protected $casts = [
'email_verified_at' => 'datetime',
];
protected $appends = [
'profile_photo_url',
];
}
Report Controller
$employees = User::whereHas('role', function ($query) {
$query->where('employee');
})
->get();
$dateRange = $reportService->generateDateRange();
$timeEntries = $reportService->generateReport($request->input('employee'));
if ($timeEntries) {
$chart = new LaravelChart([
'chart_title' => 'Hours of work per day',
'chart_type' => 'line',
'report_type' => 'group_by_date',
'model' => 'App\\TimeEntry',
'group_by_field' => 'time_start',
'group_by_period' => 'day',
'aggregate_function' => 'sum',
'aggregate_field' => 'total_time_chart',
'column_class' => 'col-md-8',
'continuous_time' => true,
]);
} else {
$chart = NULL;
}
as per the discussion, there is no roles table so you can't check using User::whereHas('role')
instead of that, you should use the following line
$employees = User::whereRole('employee')->get();
also, I have noticed that you haven't added role in fillable, you should add role to protected $fillable in order to consider that column for performing operations like create and save.
You must define a relation function role in your User model. Something like this:
public function role() {
return $this-><Type of relation>(Role::class);
}

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'
],
]);

Laravel - Model BelongsTo multiple models

I am developing a system and I have a question, in the system I have 3 main models (User, State, City), to manage the users I use a package for Laravel called Entrust, with this package I can define system roles, one of these roles is the manager, the manager can have Cities and States, however, a States can have several Cities, so in my model Cities BelongsTo to a User and a States.
Is that correct? A model can BelongsTo more then one model? I found no satisfactory answer on Google.
User.php
class User extends Authenticatable
{
use Notifiable;
use EntrustUserTrait;
use SearchableTrait;
protected $fillable = [
'role',
'active',
'status',
'name',
'slug',
'email',
'password',
'cpf',
'rg',
'mothers_name',
'marital_status',
'curriculum',
'psychiatric_report',
'contract',
'phone',
'adress',
'city',
'state',
'country',
];
protected $hidden = [
'password', 'remember_token',
];
protected $searchable = [
'columns' => [
'users.name' => 10,
'users.slug' => 8,
'users.email' => 8,
]
];
public function getRouteKeyName()
{
return 'slug';
}
public function states()
{
return $this->hasMany('App\State');
}
public function cities()
{
return $this->hasMany('App\City');
}
}
State.php
class State extends Model
{
protected $fillable = [
'name',
'slug',
'initials',
'manager_id'
];
public function getRouteKeyName()
{
return 'slug';
}
public function manager(){
return $this->belongsTo('App\User');
}
public function cities(){
return $this->hasMany('App\City');
}
}
City.php
class City extends Model
{
protected $fillable = [
'name',
'slug',
'state_id',
'manager_id',
];
public function getRouteKeyName()
{
return 'slug';
}
public function manager(){
return $this->belongsTo('App\User');
}
public function state(){
return $this->belongsTo('App\State');
}
}

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

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']));

Categories