I am new to laravel. I have a table:
students_attendance.
In students_attendance I have a column named class_id, which refers to the students_classes table that also includes the class_id and class_name for each student.
In the frontend table I am getting the values from students_attendance table so the class_id is available, but what I need is the class_name.
How I can get the class_name?
//Migration for students_attendance
public function up()
{
Schema::create('students_attendances', function (Blueprint $table) {
$table->increments('id');
$table->integer('class_id')->index()->unsigned()->nullable();
$table->string('student_id');
$table->string('first_name');
$table->string('last_name');
$table->string('attendance');
$table->timestamps();
});
}
//Migration for students_classes
public function up()
{
Schema::create('students_classes', function (Blueprint $table) {
$table->increments('id');
$table->string('class_name');
$table->string('class_fee');
$table->string('class_teacher');
$table->timestamps();
});
}
//Students Class Model
class StudentsClass extends Model
{
protected $fillable = [
'class_name',
'class_fee',
'class_teacher'
];
public function students() {
return $this->hasMany('App\Students');
}
}
//Students Attendance Model
class StudentsAttendance extends Model
{
protected $fillable = [
'class_id',
'student_id',
'first_name',
'last_name',
'attendance'
];
public function studentsClass() {
return $this->belongsTo('App\StudentsClass');
}
}
From a StatusAttendance variable you can access the class name with $attendance->studentClass->class_name.
Assuming you have the class_id and you want to get the name of the associated class, you can simply do this:
$class = StudentsClass::find($class_id);
$class->class_name; // Outputs the name
Related
I have a one-to-one relationship model, and I'm trying to save the data into my database. Upon saving, it does not save the foreign id of its hasOne class (Workday). It is a vacancy post, tied with a workdays
Schema::create('vacancies', function (Blueprint $table) {
$table->bigIncrements('id');
// other data
$table->unsignedBigInteger('workdays_id')->index();
// other data
});
Schema::create('workdays', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('vacancy_id')->index();
$table->boolean('monday')->nullable();
.
.
.
$table->boolean('sunday')->nullable();
});
Models
class Vacancy extends Model
{
protected $fillable = [
// other data
// does not have workdays_id & it's own id column
];
public function company()
{
return $this->belongsTo(Company::class);
}
public function workday()
{
return $this->hasOne(Workday::class);
}
}
class Workday extends Model
{
protected $fillable = [
'monday',
'tuesday',
'wednesday',
'thursday',
'friday',
'saturday',
'sunday'
];
public function vacancy()
{
return $this->belongsTo(Vacancy::class);
}
}
In my VacancyController, I've taken the inputs and created the Vacancy and make the Workday
$workdayInputs = $request->workdays;
$vacancy = Vacancy::create($inputs);
$workday = new Workday;
$workday->monday = in_array('monday', $workdayInputs);
$workday->tuesday = in_array('tuesday', $workdayInputs);
$workday->wednesday = in_array('wednesday', $workdayInputs);
$workday->thursday = in_array('thursday', $workdayInputs);
$workday->friday = in_array('friday', $workdayInputs);
$workday->saturday = in_array('saturday', $workdayInputs);
$workday->sunday = in_array('sunday', $workdayInputs);
$workday->vacancy()->associate($vacancy);
$workday->save();
$vacancy->workday()->save($workday);
The statement
$workday->vacancy()->associate($vacancy); $workday->save() did save the vacancy's id, but
$vacancy->workday()->save($workday) did not
In this code, I would like to get time when the user joined and left and store it to DB. What happens it that I get the same value in both 'joined' and 'left' tables. How to fix it so it would store different values?
Schema::create('user_info', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('ip');
$table->string('joined');
$table->string('left');
});
in LoginController
public function logout() {
$left = now();
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
in Model
protected $fillable = ['ip','name', 'joined'];
const CREATED_AT = 'joined';
const UPDATED_AT = 'left';
public static function storeUser() {
UserInfo::create([
'ip' => Request::ip(),
'name' => Auth::user()->name,
'joined' => now(),
]);
}
BroadcastServiceProvider.php
Broadcast::channel('chat', function ($user) {
$ip = Request::ip();
$time = now();
if (auth()->check() && !session()->has('name')) {
UserInfo::storeUser();
session()->put('name',$user->name);
return [
'id' => $user->id,
'ip' => $ip,
'name' => $user->name,
'joined' => $time,
];
}
});
This image illustates the behaviour after some changes you'll see below. It show that data with key 'left' for now goes not to the intended user but to the first user with this name.
The follow up of this question is here How to override this code so that it insert data properly?
CREATED_AT and UPDATED_AT are timestamps that gets changed by the Eloquent model, whenever a model gets created it's also modified or updated from a non-existing to existing so this is why you get the same value
In the logout function, update the user's left column
public function logout() {
$user_id = auth()->id(); // Get authenticated user ID
$user_info = App\UserInfo::find($user_id); // Get user info
$user_info->left = now(); // Change here
$user_info->save(); // Update here
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
According to your table, there's no way to distinguish between users and their info since the name is not unique
Make a user_id based relationship
User model
public function info()
{
return $this->hasOne(UserInfo::class);
}
UserInfo model
public function user()
{
return $this->belongsTo(User::class);
}
And in the user_infos migration
Schema::create('user_infos', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->string('name');
$table->string('ip');
$table->dateTime('joined');
$table->dateTime('left');
});
Cleaner Method
public function logout() {
$info = auth()->user()->info; // Get user info
$info->left = now(); // Change here
$info->save(); // Update here
auth()->logout();
session()->forget('name');
session()->put('left', $left);
return redirect('/');
}
Hope this helps
I would like to load the user, which has the appropriate url in the table invites stored. Unfortunately, I do not get the query written. How can I switch to the table "invites" and still load the right user to the page?
Relation:
One to one
Route
Route::get('/invite/{url}', 'Auth\RegisterController#show')->name('invite.show');
Table invites:
Schema::create('invites', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->text('greeting')->nullable();
$table->string('url')->unique();
$table->timestamps();
});
function
public function show($url)
{
$user = User::where(function ($query) use ($url) {
$query->where('invites.url', '=', $url);
})->first();
return view('invite_user', compact('user'));
}
Try this:
$user = User::whereHas('invites', function($query) use($url) {
$query->where('url', $url);
})->first();
Make sure that you have the invites relationship function in your User model like so:
public function invites() {
return $this->hasMany(Invite::class, 'user_id');
}
I want to show user suggestions to the logged in user.
It should be displayed to users who the logged in user does not yet follow and which the user has not blocked and was blocked.
How can I query this accordingly?
Function:
$id = Auth::id();
$users = User::with('profile')->where('id', '!=', $id )->inRandomOrder()->get();
Relationship on Usermodel
public function followers()
{
return $this->belongsToMany(User::class, 'followers', 'leader_id', 'follower_id')->withTimestamps();
}
public function followings()
{
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'leader_id')->withTimestamps();
}
public function blockers()
{
return $this->belongsToMany(User::class, 'blockers', 'leader_id', 'block_id')->withTimestamps();
}
public function blockings()
{
return $this->belongsToMany(User::class, 'blockers', 'block_id', 'leader_id')->withTimestamps();
}
Table Blockers
Schema::create('blockers', function (Blueprint $table) {
$table->increments('id');
$table->integer('block_id')->unsigned();
$table->integer('leader_id')->unsigned();
$table->timestamps();
$table->foreign('block_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('leader_id')->references('id')->on('users')->onDelete('cascade');
});
Table Follower
Schema::create('followers', function (Blueprint $table) {
$table->increments('id');
$table->integer('follower_id')->unsigned();
$table->integer('leader_id')->unsigned();
$table->timestamps();
$table->foreign('follower_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('leader_id')->references('id')->on('users')->onDelete('cascade');
You can use the whereDoesntHave() query method, which will check against the absense of a relation.
Firstly, you will need to get the currently authenticated user's id. Then which each check, you will need to pass this id to be used within the check.
Example:
$user_id = Auth::user()->id;
$suggestions = User::whereDoesntHave('followers', function ($query) use ($user_id) {
$query->where('follower_id', $user_id);
})
->whereDoesntHave('blockings', function ($query) use ($user_id) {
$query->where('block_id', $user_id);
})
->whereDoesntHave('blockers', function ($query) use ($user_id) {
$query->where('leader_id', $user_id);
})
->get();
as i found you have for relation in your UserModel follower, folloeing, blocker, blocking but you want to select users that dont have any relationship with this user, so use WhereDosentHave such as:
$users =User::where(id, $id)->WhereDoesntHave('followers')
->ORwhereDoesntHave('following')
->ORwhereDoesntHave('blocker')
->ORwhereDoesntHave('blocking')
->get();
i dont test it but i think that work just check name of relations
Hello I want to returned a list of products with the selected category.
I have two tables connected by relationship table products:
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->integer('article_id')->unsigned();
$table->integer('category_id')->unsigned();
$table->string('sn');
$table->integer('quantity');
$table->date('warranty');
$table->timestamps();
});
Schema::table('products', function(Blueprint $table) {
$table->foreign('user_id')->references('id')->on('users');
$table->foreign('article_id')->references('id')->on('articles');
$table->foreign('category_id')->references('id')->on('categories');
});
}
and table categories:
public function up()
{
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('category_name');
$table->timestamps();
});
}
product model:
public function user(){
return $this->belongsTo('App\User');
}
public function article(){
return $this->belongsTo('App\Article');
}
public function category(){
return $this->belongsTo('App\Category');
}
And category model:
public function products(){
return $this->hasMany('App\Product')->withTimestamps();
}
I write query SQL in phpmyadmin:
SELECT
products.id,
products.user_id,
articles.article_name,
categories.category_name,
products.sn,
products.quantity,
products.warranty,
products.created_at,
products.updated_at,
SUM(quantity) AS ilosc
FROM
products
LEFT JOIN
categories ON products.category_id = categories.id
LEFT JOIN
articles ON products.article_id = articles.id
GROUP BY articles.article_name
ORDER BY id;
This query works on phpmyadmin but I want write metohod in Laravel. How can I return a list of products assigned to the selected category ?? I would add that the selected category is passed in the method show by ID CATEGORY:
public function show($id){
$categories = Category::find($id);
return view('categories.showcategory', compact('categories'));
}
I do not want a solution, only hints how I can do it. I found this theme enter link description here, but still I do not know how to do it ;)
I convert query SQL to query laravel i file CategoriesController:
public function show($id){
$categories = Category::find($id);
$productsList = DB::table('products')->select('products.id,
products.user_id,
articles.article_name,
categories.category_name,
products.sn,
products.quantity,
products.warranty,
products.created_at,
products.updated_at,
SUM(quantity) AS ilosc')->from('products')->where('id' , '=' , $categories->id)->leftJoin('categories', 'products.category_id', '=', 'categories.id')->leftJoin('articles', 'products.article_id', '=', 'articles.id')->groupBy('articles.article_name')->orderBy('id')->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
But Laravel returned error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'products.id, '
in 'field list' (SQL: select products.id, as `` from products
left join categories on products.category_id = categories.id
left join articles on products.article_id = articles.id
where id = 1 group by articles.article_name order by id asc)
with the help of swatkins I wrote method:
public function show($id){
$categories = Category::find($id);
$productsList = Category::with(['products' => function ($query) {
$query->where('category_id', 20);
}])->get();
return view('categories.showcategory', compact('categories', 'productsList'));
}
Laravel returns correctly Products with selected category, but only when I write ID category. In this method ID category is equal to 20.
$query->where('category_id', 20);
How can I dynamically pass the value of GET category_id ??
You already have a category, you just need to eager load the products relationship:
public function show($id){
$categories = Category::with(['products' => function ($query) {
$query->where('paid', true);
}])->find($id);
// this will give you a child property on your category
// called 'products' that will be an array of associated
// Product objects
return view('categories.showcategory', compact('categories'));
}
docs: https://laravel.com/docs/5.2/eloquent-relationships#eager-loading