Retrieving data from multiple tables - php

I have Student table in my database which connect many to many with Courses table , when I try to select student from the table ,give me error :
"Undefined property: stdClass::$courses (View: C:\xampp\htdocs\laravel\resources\views\admin\student\index.blade.php)
<td>
#foreach($student->courses as $course)
<label>{{$course->name_courses}}</label>
#endforeach
</td>
edit and update have error:
public function edit(Student $student)
{
$id = $student->id;
$students = DB::table('student')
->join('contacts', 'student.contact_id', '=', 'contacts.id')
->join('users', 'contacts.user_id', '=', 'users.id')
->select('contacts.*', 'users.*', 'student.*')
->where(['student.id' => $id])
->first();
$courses = Course::all();
$course2 = array();
foreach ($courses as $course) {
$course2[$course->id] = $course->name;
}
return view('admin.student.edit', ['student' => $students]);
}
function update:
public function update(Request $request, Student $student)
{
Student::updateStudent($request->all());
if (isset($request->courses)) {
$student->courses()->sync($request->courses);
} else {
$student->courses()->sync(array());
}
return redirect("/admin/student")->with('success','Has been Update');
}
in the model Student
public static function createStudent($data) {
/*
$user = User::create([
'username' => $data['user_name'],
'role_id' => 1,
'password' => Hash::make($data['password']),
]);*/
$user = User::createUser($data) ;
$data['user_id'] = $user['id'];
$contactId = Contact::createContact($data);
$student = Student::create([
'contact_id' => $contactId
]);
return $student;
}
public static function updateStudent($data) {
/* DB::table('users')
->where('id', $data['user_id'])
->update([
'username' => $data['username']
]);*/
User::updateUser($data);
Contact::updateContact($data);
}
public function courses()
{
return $this->belongsToMany('App\Course');
}
Could someone tell me what to do to fix this ?

Looks like you are using Route model binding, and your student is injected, if thats the case you don't need to use DB::table(...
public function edit(Student $student)
{
$courses = Course::all();
$course2 = array();
foreach ($courses as $course) {
$course2[$course->id] = $course->name;
}
return view('admin.student.edit', ['student' => $student]);
}

You have 2 problems in your code:
1-
The below indicates that you're using Query Builder instead of Eloquent
$students = DB::table('student')
->join('contacts', 'student.contact_id', '=', 'contacts.id')
->join('users', 'contacts.user_id', '=', 'users.id')
->select('contacts.*', 'users.*', 'student.*')
->where(['student.id' => $id])
->first();
And you didn't join the courses table.
2-
Query Builder will return Array, not an object. So to access the course you should do this instead, $course['name_courses']:
<td>
#foreach($student->courses as $course)
<label>{{$course['name_courses']}}</label>
#endforeach
</td>
To fix the issue, it's easier to do the following:
$students = Student::with('courses', 'contacts, 'contacts.users')
->where('id', '=', $id) //the 'id' here refers to 'student' ID.
->first();
and then you can loop over the courses that belong to this particular student.

Related

Laravel multiple relation return null value

Code:
$user = User::with('role.modules.subModule.module.moduleGroup')
->where('id', Auth::id())
->first();
return $user->role->modules->first()->sub_module;
user collection is like this:
Why can't I access with this statment?
return $user->role->modules->first()->sub_module;
User Model:
public function role()
{
return $this->hasOne(Roles::class, 'id', 'role_id');
}
Roles Model:
public function modules()
{
return $this->hasMany(RoleModules::class, 'role_id', 'id');
}
I solved the problem:
$user = User::with('role.modules.subModule.module.moduleGroup')
->where('id', Auth::id())
->first();
$user = collect($user);
$modules = collect();
for ($i = 0; $i < count($user['role']['modules']); $i++) {
if ($user['role']['modules'][$i]['sub_module'] != null)
$modules->push([
'module_group_name' => $user['role']['modules'][$i]['sub_module']['module']['module_group']['title'],
'module_group_must' => $user['role']['modules'][$i]['sub_module']['module']['module_group']['must'],
'module_name' => $user['role']['modules'][$i]['sub_module']['module']['name'],
'module_must' => $user['role']['modules'][$i]['sub_module']['module']['must'],
'module_ico' => $user['role']['modules'][$i]['sub_module']['module']['ico'],
'sub_module_name' => $user['role']['modules'][$i]['sub_module']['sub_name'],
'sub_module_must' => $user['role']['modules'][$i]['sub_module']['must'],
'sub_module_link' => $user['role']['modules'][$i]['sub_module']['link'],
]);
}
return $modules;

I am trying to query two tables in my laravel database

I am trying to query two tables in a database but its returning this error.
I am trying to implement a search through multiple tables. The project is an online store with 3 distinctive tables, Products, Categories and Brands. I can only search through the Products table but can't seem to get the same search field from my blade file to search either the categories or the brands and return results of the associated products.
QLSTATE[23000]: Integrity constraint violation: 1052 Column 'status' in where clause is ambiguous (SQL: select * from `categories` inner join `products` on `products`.`category_id` = `categories`.`id` where `name` LIKE %Television% and `status` = 1)
My Search function
public function searchProducts(Request $request) {
$product = $request->input('product');
$categories = Category::with('categories')->where(['parent_id' => 0])->get();
$productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
->where('name', 'LIKE', "%{$product}%")
->where('status', 1)->get();
$breadcrumb = "<a href='/'>Home</a> / ".$product;
return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));
}
My Category Model
class Category extends Model implements Searchable
{
protected $table = 'categories';
protected $fillable = [
'name'
];
public function categories(){
return $this->hasMany('App\Category','id');
}
public function products(){
return $this->hasMany('App\Product','id');
}
}
My Products Model
class Product extends Model implements Searchable
{
public function category() {
return $this->hasMany('App\Category', 'id') ;
}
public function attributes(){
return $this->hasMany('App\Product','id');
}
}
You have status column in more than one table.
Change this
->where('status', 1)->get();
to this
->where('products.status', 1)->get();
I was able to solve it by modifying my search function as follows.
public function searchProducts(Request $request) {
$product = $request->input('product');
$categories = Category::with('categories')->where(['parent_id' => 0])->get();
$productsAll = Category::query()->join('products', 'products.category_id', '=', 'categories.id')
->where('categories.name', 'LIKE', "%{$product}%")
->orWhere('products.product_name', 'LIKE', "%{$product}%")
->where('products.status', 1)->get();
$breadcrumb = "<a href='/'>Home</a> / ".$product;
return view('pages.results')->with(compact('categories','productsAll','product','breadcrumb'));
}

How to return data from 2 tables with foreign keys in laravel

I am trying to return a view with 2 tables, orders and order_menu. What I want to do is to display what orders the customer ordered based on order_id to my view.
Here is the database table for orders and this is database table for order_menu.
I've tried using join table in my controller but it won't work. Here is my controller:
public function show(Order $order)
{
$data = DB::table('order_menu')
->join('menus', 'menus.id', '=', 'order_menu.menu_id')
->join('orders', 'orders.id', '=', 'order_menu.order_id')
->select('orders.*', 'menus.name', 'order_menu.quantity')
->get();
return view('admin.order.detail')->with([
'order' => $order,
'data' => $data,
]);
}
Is there any solutions to solve this?
You just need to add a filter for order id in your query, I assume $order is the instance of model and has order data
$data = DB::table('order_menu')
->join('menus', 'menus.id', '=', 'order_menu.menu_id')
->join('orders', 'orders.id', '=', 'order_menu.order_id')
->select('orders.*', 'menus.name', 'order_menu.quantity')
->where('orders.id', $order->id)
->get();
Or if you already have relations in place in your model then using eloquent you can query the data as
class Order extends Model
{
public function menus()
{
return $this->belongsToMany(Menu::class, 'order_menu ', 'order_id', 'menu_id')->withPivot('quantity');
}
}
class Menu extends Model
{
public function orders()
{
return $this->belongsToMany(Order::class, 'order_menu ', 'menu_id','order_id');
}
}
$data = Order::with('menus')->find($order->id);
public function show(Order $order)
{
$data = DB::table('orders*')
->join('order_menu*', 'order_menu.id', '=', 'orders.id')
->groupBy('orders.id')
->get();
return view('admin.order.detail')->with([
'data' => $data,
]);
}

Index page does not show the object of db or sometime it shows undefined variable

I am trying to build a shopping cart but it doesn't show what the cart contains.
Something is wrong here is my code in the controller and blade:
public function index()
{
$id = Auth::id();
$results = DB::table('carts')
->select('book_id')
->where('user_id', '=', $id)
->get();
$data = (array) $results;
$books = Book::all()->whereIn('id', $data);
return view('carts.index')->withBooks($books);
}
#foreach($books as $book)
<tr>
<td> {{ $book->autori }} </td>
<td> {{ $book->titulli }} </td>
<td> {{ $book->cmimi }}</td>
</tr>
#endforeach
public function index()
{
$booksIds = DB::table('carts')
->select('book_id')
->where('user_id','=', Auth::id())
->get()
->pluck('book_id')
->toArray();
$books = Book::whereIn('id', $booksIds)->get();
return view('carts.index')->withBooks($books);
}
or using a single query:
public function index()
{
$books = Book::join('carts', static function($join) {
$join->on('books.id', '=', 'carts.book_id')
->where('carts.user_id', '=', Auth::id());
})->get();
return view('carts.index')->withBooks($books);
}
You should read about and use eloquent relationships.

Using 'with' in many-to-many relationship in Laravel

I have a table user - User(Model), which has relationship:
public function roles()
{
return $this->belongsToMany(Config::get('entrust.role'), Config::get('entrust.role_user_table'), 'user_id', 'role_id');
}
public function regions() {
return $this->belongsToMany('App\Regions', 'user_region', 'user_id', 'region_id');
}
I am trying this query, but it doesn't me the required result
$result = User::with(['roles' => function($query) {
$query->select('user_id','role_id');
},
'regions' => function($query) {
$query->select('user_id','region_id', 'region_name');
}])
->where('user_id', '=', $id)
->get()->toArray();
It only gives me data from user table and doesn't give the relationship data.
What am I missing out??
The notation you are using should be used for constraints. From your code it seems you don't actually need any contraints.
$result = User::with(['roles', 'regions'])
->where('user_id', '=', $id)
->first()->toArray();
The relationship you defined is only a belongsTo. You should probably use a hasMany relationship.
If you're using 5.1 try this:
$result = User::whereHas(['roles' => function($query) {
$query->lists('user_id','role_id');
},
'regions' => function($query) {
$query->lists('user_id','region_id','region_name');
}])
->where('user_id', '=', $id)
->all();
if not remove all() and use get()
This worked for me.
$users = User::with('regions', 'roles')->get();
$userInfo = [];
foreach ($users as $user)
{
$userInfo[] = [
'users' => $user,
'regions' => $user->regions->toArray(),
'roles' => $user->roles->toArray(),
];
}

Categories