This is my first laravel Application, and my first database based application so please be patient with me !!
I will try to be specific!!
Categories Table:
Id
Name
Timestamps
Posts table:
Id
title
body
slug
Category_id
timestamps
Lets say i have 4 catergories.
Laptops, computers,phones,tablets
I want when i go to /computers to be able to get all the posts that are specific to that category.
Posts Model
Category Model
Category Controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Post;
use App\Category;
class CatController extends Controller
{
public function getCategory($Category_id)
{
$posts = Post::where('Category_id',$Category_id);
return view('blog.index',['posts' => $posts]);
}
Route:
Route::get('computer/{Category_id}','CatController#getCategory');
I am really confused at the moment !!
Thanks everyone in advance!!
Define your Model
class Category extends Model
{
/**
* Get the posts.
*/
public function posts()
{
return $this->hasMany('App\Post', 'Category_id');
}
}
class Post extends Model
{
/**
* Get the category.
*/
public function category()
{
return $this->belongsTo('App\Category', 'Category_id');
}
}
Define your Controller
class CatController extends Controller
{
public function getCategory($Category_id)
{
$category = Category::find($Category_id);
if($category !== null){
$posts = $category->posts;
return view('blog.index',['posts' => $posts]);
}
}
I hope this will help you.
Route:
Route::get('categories/{category_id}/computers','CatController#show');
Controller:
public function show($category_id)
{
$category = Category::findOrFail($category_id);
if($category){
$posts = Post::where('Category_id',$category_id)->get();
return view('category.index', compact('posts'));
}
return view('errors.404');
}
Simply add this to your controller
public function category($id){
$data['posts'] = Post::where('status', 1)->where('category_id', $id)->orderBy('id', 'DESC')->get();
return view('frontEnd.home', $data);
}
Related
How to show specific order details and all products which belongs only to that specific order on same view? Trying this, but getting empty array when doing dd().
OrderController:
public function show(Order $order){
$products = Product::where('order_id', $order);
//dd($products);
return view('order.view', ['order'=>$order, 'products'=>$products]);
}
web.php
//Orders and products related routes
Route::get('/order/{order}', 'OrderController#show')->name('order');
Route::get('/orders/create', 'OrderController#create')->name('order.create');
Route::post('/order', 'OrderController#store')->name('order.store');
Route::get('/order', 'OrderController#index')->name('order.index');
Route::delete('/order/{order}/destroy', 'OrderController#destroy')->name('order.destroy');
Route::get('/order/{order}/edit', 'OrderController#edit')->name('order.edit');
Route::put('/order/{order}/update', 'OrderController#update')->name('order.update');
Route::get('/order/{order}/product/create', 'ProductController#create')->name('product.create');
Route::post('/order/{order}/product', 'ProductController#store')->name('product.store');
Product.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $guarded = [];
public function order(){
return $this->belongsTo(Order::class);
}
}
Order.php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Customer;
class Order extends Model
{
protected $guarded = [];
public function customer(){
return $this->belongsTo(Customer::class);
}
public function products(){
return $this->hasMany(Product::class);
}
}
I would suggest to change the name of your route param to id to consistency and readability
Route::get('/order/{id}', 'OrderController#show')->name('order');
In view generate url for your route as
Show Order
And in controller you can get order details along with related products as
public function show($id){
$order = Order::with('products')->find($id);
return view('order.view', ['order'=>$order]);
}
And in view you can get collection of products from $order->products
I have a articles table with a field named article_categories.
I have a categories table with id field.
In my Article Model I have defined:
public function category(){
return $this->hasMany(Category::class,'id','article_categories');
}
the categories in the articles table are saved as json like ["1","3","24"]
in my ArticleController I want to retrieve all categories of a specific article.
In my edit function in the ArticleController I have this function:
public function edit(Article $article)
{
$category_ids = implode(',',json_decode($article->article_categories)) ; //this gives me 1,3,24
/////////
// HERE SHOULD COME THE QUERY WHICH I DON'T KNOW
// $article_categories = ??????????
////////
$categories = Category::all();
return view('article.edit', compact('articles','categories','article_categories'));
}
From what I've researched, there is no way to do this with Laravel but I don't know if this is true or not. I'm using Laravel 8.
Can anyone help me?
First of all you should know that you violated a many-to-many relation in a single column and that's not valid. What you should do is a pivot table article_category or category_article and in both Article and Category models you will define a many-to-many relation
like so
class Article extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
class Category extends Model
{
public function articles()
{
return $this->belongsToMany(Article::class);
}
}
And in your controller you can do
public function edit(Article $article)
{
$categories = Category::all();
return view('article.edit', compact('article','categories'));
}
And in the view you will have direct access to $article->categories
In your current situation you can do this
public function edit(Article $article)
{
$category_ids = json_decode($article->article_categories)
$article_categories = Category::whereIn('id', $category_ids);
$categories = Category::all();
return view('article.edit', compact('article','categories','article_categories'));
}
I am using scope to filter conditions for specific users, I have assigned a course to a teacher and when this teacher signs into their account, I only want this teacher to view their course, although my scope method doesn't appear to be working correctly. I am not getting an error, so I am not sure where I have gone wrong. I have added some of my code below, i would be very grateful for any help. Thanks
CoursesController index method;
public function index()
{
$courses = Course::ofTeacher()->get();
return view('admin.courses.index')->with('course', $courses); //pass data down to view
}
Course.php;
<?php
namespace App;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
class Course extends Model
{
protected $fillable = [
'id', 'title'
];
public function courses(){
return $this->belongsToMany('App\User');
}
public function teachers() {
return $this->belongsToMany(User::class, 'course_user')
}
public function scopeOfTeacher($query)
{
if (!Auth::user()->isAdmin()) {
return $query->whereHas('teachers', function($q) {
$q->where('user_id', Auth::user()->id);
});
}
return $query;
}
}
User.php;
public function isAdmin() {
return $this->role()->where('role_id', 1)->first();
}
I have three tables:
notes: id, business_id, note
businesses: id, title, description
businessimages : id, business_id, image
I get my customers notes with this:
$customer = Auth::guard('customer-api')->user();
$notes = Note::where('customer_id', $customer->id)->with('business:id')-
>orderBy('id', 'desc')->get();
Now I want to get notes.id, businesses.id, businesses.title, businesses.description, businessimages.image for each notes and show all of them in one json array
How could I do?
Note::where('customer_id',$customer->id)
->join('businesses', 'businesses.id', '=', 'notes.buisness_id')
->join('businessimages', 'businesses.id', '=', 'businessimages.buisness_id')
->select(notes.id, businesses.id, businesses.title, businesses.description,businessimages.image)
->get();
Note model;
public function business() {
return $this->hasOne('App\Business', 'business_id', 'id');
}
Business mode;
public function businessImage()
{
return $this->hasOne('App\BusinessImage', 'business_id', 'id');
}
Your controller;
$notes = Note::where('customer_id', $customer->id)->with('business.businessImage')->orderBy('id', 'desc')->get();
You should consider using API Resources
This is a great way to organize a model(or a collection of models as well).
App\Note
use Illuminate\Database\Eloquent\Model;
class Note extends Model
{
public function business()
{
return $this->belongsTo('App\Business');
}
}
App\Business
namespace App;
use Illuminate\Database\Eloquent\Model;
class Business extends Model
{
public function note()
{
return $this->hasOne('App\Note');
}
public function businessImage()
{
return $this->hasOne('App\BusinessImage');
}
}
App\BusinessImage
namespace App;
use Illuminate\Database\Eloquent\Model;
class BusinessImage extends Model
{
protected $table = 'businessimages';
public function business()
{
return $this->belongsTo('App\Business');
}
}
App\Http\Resources\Note
namespace App\Http\Resources;
class Note
{
public function toArray($request)
{
return [
'noteId' => $this->resource->id,
'businessId' => $this->resource->business->id,
'businessTitle' => $this->resource->business->title,
'businessDescription' => $this->resource->business->description,
'businessImage' => $this->resource->business->businessImage->image
];
}
}
Somewhere in a controller
use App\Http\Resources\Note as NoteResource;
public function foo()
{
$customer = Auth::guard('customer-api')->user();
$notes = Note::where('customer_id', $customer->id)->with(['business','business.businessImage'])->orderBy('id', 'desc')->get();
return NoteResource::collection($notes);
}
This is my Controller method wherein I want to fetch posts by user id.
I also have relationship defined in User model
public function posts()
{
return $this->hasMany('Post','user_id','id');
}
UserController.php
use App\Post;
public function findPostsByUser($id){
$user = User::findOrFail($id);
$posts = $user->posts()->get();
return $posts;
}
But it is giving me 'Post' not found error. Can someone help on this.
In your Post model make sure you have the relation defined like this:
public function user()
{
return $this->belongsTo('App\User');
}
And change your User model to this:
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
Change relation method to
use App\Post;
....
public function posts()
{
return $this->hasMany(Post::class,'user_id','id');
}
or
public function posts()
{
return $this->hasMany('App\Post','user_id','id');
}
If you wont to get only posts that case use this
public function findPostsByUser($id){
$posts = Post::where('user_id', $id)->get();
return $posts;
}
The second solution has 1 query, but first solution has 2 query in db.
Also you can do it this way
public function findPostsByUser($id){
$posts = Post::whereUserId($id)->get();
return $posts;
}