I have tree structure of categories. Now I have to display only that categories which is not applied in a particular business.
Code in Controller
public function edit($id)
{
try
{
$id=Crypt::decrypt($id);
$business=Business::findOrFail($id);
$business_contact_details=BusinessContactDetails::where('business_id',$id)->select('contact_no','id')->get();
$business_working_hours=BusinessWorkingHours::where('business_id',$id)->get();
$business_categories=BusinessCategories::leftJoin('categories','categories.id','=','category_id')->where('business_id',$id)->where('categories.parent_id','0')->select('categories.name as name','approved','category_id','business_categories.id as id')->get();
$categories = Categories::where('parent_id', '=', 0)->get();
return view('admin.businesses.edit',compact('business','business_contact_details','business_working_hours','categories','category_counter','business_categories'));
}
catch(DecryptException $e)
{
return view('errors.404');
}
}
Code in Model
public function subChilds(){
return $this->hasMany('App\Categories','parent_id','id')->whereNotExists(function($query){
$query->from('business_categories')->whereRaw('categories.id=business_categories.category_id')->where('business_id',2);
});
}
Code in edit View
<div class="col-md-6">
<ul id="tree1">
#foreach($categories as $category)
<li>
<input type="checkbox" value="{{$category->id}}" name="categories[]">
{{ $category->name }}
#if(count($category->subChilds($business->id)))
#include('admin.businesses.manageChildSub',['subChilds' => $category->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
</div>
Code in manageChildSub View
<ul>
#foreach($subChilds as $child)
<li>
<input type="checkbox" value="{{$child->id}}" name="categories[]">
{{ $child->name }}
#if(count($child->childs))
#include('manageChildSub',['subChilds' => $child->subChilds($business->id)])
#endif
</li>
#endforeach
</ul>
Here, You can see that I have passed business_id as 2, but I have to pass it as my current business ID. Basically I need to call the model function with ID.
After changing to this, I am not getting any subcategories.
You can try this:
public function subChilds($business_id){
return $this->hasMany('App\Categories','parent_id','id')
->whereNotExists(function($query) use ($business_id){
$query->from('business_categories')
->whereRaw('categories.id=business_categories.category_id')
->where('business_id', $business_id);
});
}
Related
Looking to solve this error that I'm getting when trying to display some data to the view. I'm working with v5.7 and I have a feeling it might be something with the index method in my controller, I could be very wrong. If there is any more info that is needed please let me know.
Trying to get property 'slug' of non-object (0)
Route:
Route::get('/category/{category}','BlogController#category')->name('category');
BlogCategory Model
namespace App;
use Illuminate\Database\Eloquent\Model;
class BlogCategory extends Model
{
protected $fillable = ['title', 'slug'];
public function posts()
{
return $this->hasMany(Post::class);
}
public function getRouteKeyName()
{
return 'slug';
}
}
Post Model
public function category()
{
return $this->belongsTo(BlogCategory::class);
}
Controller:
protected $limit = 3;
public function index()
{
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = Post::with('author')
->latestFirst()
->published()
// ->filter(request()->only(['term','year','month']))
->simplePaginate($this->limit);
return view('pages.frontend.blog.index', compact('posts', 'categories'));
}
public function category(BlogCategory $category)
{
$categoryName = $category->title;
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = $category->posts()
->with('author')
->latestFirst()
->published()
->simplePaginate($this->limit);
return view("pages.frontend.blog.index", compact('posts', 'categories', 'categoryName'));
}
View:
#foreach ($posts as $post)
<article class="post-item">
#if ($post->image_url)
<div class="post-item-image">
<a href="{{ route('blog.show', $post->slug) }}">
<img src="{{ $post->image_url }}" alt="">
</a>
</div>
#endif
<div class="post-item-body">
<div class="padding-10">
<h2>
{{ $post->title }}
</h2>
{!! $post->excerpt_html !!}
</div>
<div class="post-meta padding-10 clearfix">
<div class="pull-left">
<ul class="post-meta-group">
<li>
<i class="fa fa-user"></i>
{{ $post->author->name }}
</li>
<li>
<i class="fa fa-clock-o"></i>
<time> {{ $post->date }}</time>
</li>
<li>
<i class="fa fa-folder"></i>
{{ $post->category->title }}
</li>
<li>
<i class="fa fa-comments"></i>
4 Comments
</li>
</ul>
</div>
<div class="pull-right">
Continue Reading ยป
</div>
</div>
</div>
</article>
#endforeach
Post table
Blog Cats table
The belongsTo function accepts a second argument for the name of the foreign key in your posts table, if you do not provide it the framework will try to guess what is the foreign key column name giving the name of the function as pattern, in your case category(), so the framework is searching for category_id, however, your foreign key column name is blog_category_id.
public function category()
{
return $this->belongsTo(BlogCategory::class, 'blog_category_id');
}
You should call the category relationship in the index of your controller, if this view is related to the index method!
public function index()
{
$categories = BlogCategory::with(['posts' => function ($query) {
$query->published();
}])->orderBy('title', 'asc')->get();
$posts = Post::with('author')
->category()
->latestFirst()
->published()
// ->filter(request()->only(['term','year','month']))
->simplePaginate($this->limit);
return view('pages.frontend.blog.index', compact('posts', 'categories'));
}
I'm a new developer and I'm trying to make work my very simple blog.
I want to set a previous and a next link to my previous and next articles in the blog. This is my current code.
POSTS CONTROLLER
public function move($id)
{
$post = DB::table('posts')->find($id);
$previous = DB::table('posts')->where('id', '<', $post->id)->max('id');
$next = DB::table('posts')->where('id', '>', $post->id)->min('id');
return view('posts.show')->with('previous', $previous)->with('next', $next);
}
WEB.PHP
<?php
Route::get('/', 'PostsController#index')->name('home');
Route::get('/posts/create', 'PostsController#create');
Route::post('/posts', 'PostsController#store');
//Route::get('/posts/{post}', 'PostsController#show');
Route::get('/posts/tags/{tag}', 'TagsController#index');
Route::post('/posts/{post}/comments','CommentsController#store');
Route::get('/posts/{id}/edit', 'PostsController#edit');
Route::get('/edit/{post}', 'PostsController#update');
Route::patch('/post/{post}', 'PostsController#update');
Route::get('/register', 'RegistrationController#create');
Route::post('/register', 'RegistrationController#store');
Route::get('/login', 'SessionsController#create');
Route::post('/login', 'SessionsController#store');
Route::get('/logout', 'SessionsController#destroy');
Route::get('/posts/{id}', 'PostsController#move');
SHOW.BLADE
#extends ('layouts.master')
#section ('content')
<div class="col-sm-8 blog-main">
<h1> {{$post->title}}</h1>
#if (count($post->tags))
<ul>
#foreach($post->tags as $tag)
<li>
<a href="/posts/tags/{{ $tag->name}}">
{{ $tag->name }}
</a>
</li>
#endforeach
</ul>
#endif
{{$post->body}}
<hr>
Modifica
<hr>
<div class='comments'>
<ul class="list-group">
#foreach ($post->comments as $comment)
<li class="lista-commenti">
<strong>
{{$comment->created_at->diffForHumans()}}:
</strong>
{{ $comment -> body}}
</li>
#endforeach
</ul>
</div>
<hr>
<div>
<div>
<form method="POST" action="/posts/{{$post->id}}/comments">
{{csrf_field()}}
<div>
<textarea name="body" placeholder="Il tuo commento" class="form-control" required></textarea>
</div>
<div>
<button type="submit" class="bottone">Invia Commento</button>
</div>
</form>
#include('layouts.errors')
</div>
<div class="row">
<ul>
<li> Previous</li>
<li> Next
</li>
</ul>
</div>
</div>
</div>
#endsection
POST.PHP
<?php
namespace App;
use Carbon\Carbon;
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
public function addComment($body)
{
$user_id= auth()->id();
$this->comments()->create(compact('user_id','body'));
}
public function scopeFilter($query, $filters)
{
if(!$filters)
{
return $query;
}
if ($month = $filters['month'])
{
$query->whereMonth('created_at', Carbon::parse($month)->month);
}
if ($year = $filters['year']) {
$query->whereYear('created_at', $year);
}
}
public static function archives()
{
return static::selectRaw('year(created_at) year, monthname(created_at) month, count(*) published')
->groupBy('year','month')
->orderByRaw('min(created_at) desc')
->get()
->toArray();
}
public function tags(){
return $this->belongsToMany(Tag::class);
}
}
This gives me an error about the undefined variables previous and next and also about the www.
Sorry but this is my first post and I can't upload any images. Hope someone can help me.
Thanks
Alessandro
use url() helper method:
<li> Previous</li>
<li> Next</li>
Edit: remove this Route::get('/posts/{post}', 'PostsController#show'); line or change your code like move method in your show method.
For your new error, add this line at top-
use Illuminate\Support\Facades\DB;
When you're going to post/1, you're executing the show method and not move.
Also, change the code to:
<li> Previous</li>
<li> Next</li>
You've said, "and also about the www". I'm pretty sure you're not getting the error about the $previous or $next but you get the error about the www... because you're trying to use text as variable in your code.
I have a category table, it is organized by 'parent_id' and 'categoryid'. I need to organize it in a list, where I group the parent class with the daughter class.
I created this code.
In the controller I get the value of the categories.
public function index()
{
$cat1 = Category::where('erp_parentid', '=', 0)->get();
foreach($cat1 as $categoria1){
$cat2 = Category::where('erp_parentid', '=', $categoria1->erp_categoryid)->get();
return view('admin.categories')->with('cat1', $cat1)->with('cat2', $cat2);
}
}
$cat2 is the child category, I get its values through the categoryid of the parent category.
But when I pass the values to the view, all parent categories take the same value as the first.
I used that code to display the values in the view:
<div class="container">
<div class="row">
<ul class="list-group">
#foreach($cat1 as $value)
<a data-toggle="collapse" data-target="#catfilha{{$value->erp_categoryid}}"><li class="list-group-item">{{$value->erp_name}}</li></a>
<ul id="catfilha{{$value->erp_categoryid}}" class="collapse">
#foreach($cat2 as $value2)
<li>{{$value2->erp_name}}</li>
#endforeach
</ul>
#endforeach
</ul>
</div>
</div>
I searched for similar cases here on the site, but found no resemblance, any suggestions? Thank you in advance.
You should define the relations in the model and call them in the view. Try something like this:
In Category Model:
public function getParent()
{
return self::where('erp_parentid', '=', $this->erp_categoryid)->get();
}
In Controller:
public function index()
{
$cat1 = Category::where('erp_parentid', '=', 0)->get();
return view('admin.categories')->with('cat1', $cat1);
}
In the View:
<div class="container">
<div class="row">
<ul class="list-group">
#foreach($cat1 as $value)
<a data-toggle="collapse" data-target="#catfilha{{$value->erp_categoryid}}"><li class="list-group-item">{{$value->erp_name}}</li></a>
<ul id="catfilha{{$value->erp_categoryid}}" class="collapse">
#foreach($value->getParent() as $value2)
<li>{{$value2->erp_name}}</li>
#endforeach
</ul>
#endforeach
</ul>
</div>
</div>
In your code, the return statement is inside the loop, so cat2 will be always the categories from the first item of cat1.
I wanted to update multiple rows in the database and have found a way to do it. but it does not seem like the best way to do it, since it is doing it in multiple calls at the moment.
I wanted to now if there is a better way to do this.
The homecontroller with the updatePersons function:
<?php
class HomeController extends BaseController {
public function index()
{
$persons = Person::get();
return View::make('hello')
->with(compact('persons'));
}
public function updatePersons()
{
$persons = Person::get();
foreach ($persons as $person) {
$person->fname = Input::get('fname'.$person->id);
$person->lname = Input::get('lname'.$person->id);
$person->save();
}
return Redirect::route('home')->with('succes', 'Siden er opdateret');
}
}
the view with the form
#extends('layouts.master')
#section('content')
<div class="container">
<ul class="list-group">
{{ Form::open(array('route'=>'personUpdate', 'method' => 'post')) }}
#foreach ($persons as $person)
<li class="list-group-item">
{{ Form::text('fname'.$person->id,$person->fname,array('class'=>'form-control', 'placeholder'=>'fname')) }}
{{ Form::text('lname'.$person->id,$person->lname,array('class'=>'form-control', 'placeholder'=>'lname')) }}
</li>
#endforeach
<li class="list-group-item">
<div class="box-footer">
<button type="submit" class="btn btn-primary">Update</button>
</div>
</li>
{{ Form::close() }}
</ul>
</div>
</div>
#stop
The routes:
<?php
Route::get('/', array('as'=>'home', 'uses'=>'HomeController#index'));
Route::post('/', array('as'=>'personUpdate', 'uses'=>'HomeController#updatePersons'));
I have tried to use the savemany() function on $persons after the foreach loop in updatePersons() but with no results.
If you're updating many rows with each with different values, there's no easier way to do it.
Could you think of how you'd write this in SQL?
I have a form which is submitting data to 2 separate models.
The model SalesItem belongs to Sale. A Sale can have many SalesItems.
I know I need to get the repeating fields into an array, but I'm not entirely sure how I should go about doing that. I though I had the right idea, but my controller isn't catching the array as the variable I was trying to set it up as.
Can see relevant code here: http://laravel.io/bin/Qzk24
All help is greatly appreciated!
/*** Sale Model ***/
class Sale extends \Eloquent {
public function user(){
return $this->belongsTo('User');
}
public function salesItem()
{
return $this->hasMany('SalesItem');
}
}
/*** SalesItem Model ***/
class SalesItem extends \Eloquent {
protected $table = 'SalesItems';
public function sale()
{
return $this->belongsTo('Sale');
}
}
/**** SalesController#store ****/
public function store()
{
$sale = new Sale();
if(Auth::user()){
$userID = Auth::user()->id;
$sale->user_id = $userID;
}
$sale->invoice_number = Input::get('invoice_number');
$sale->name_of_purchaser = Input::get('name_of_purchaser');
$sale->date_of_sale = Input::get('date_of_sale');
// For each saleItem that exists
foreach($items as $item)
{
//Create new salesitem
$saleItem = new SalesItem();
//Save attributes
$saleItem->product_id = $item['equipment'];
$saleItem->selling_price = $item['selling_price'];
$saleItem->serial_number = $item['serial_number'];
$saleItem->save();
//associate with the sale
$sale->salesItem()->associate($salesItem);
}
$sale->save();
return "Sale Saved";
}
/**** sales/create.blade.php *****/
{{ Form::open(array('action'=>'SalesController#store')) }}
<ul>
<li>
{{ Form::label('invoice_number','Dealer Invoice Number:')}}
{{ Form::text('invoice_number')}}
{{ $errors->first('invoice_number','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('name_of_purchaser','Name of Purchaser:')}}
{{ Form::text('name_of_purchaser')}}
{{ $errors->first('name_of_purchaser','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('date_of_sale','Date of Sale:')}}
{{ Form::text('date_of_sale')}}
{{ $errors->first('date_of_sale','<small class="error">:message</small>')}}
</li>
<li>
<h2> Sale Items </h2>
<ul class="repeatable">
<li>
{{ Form::label('items[0][equipment]','Equipment:')}}
{{ Form::text('equipment[0]', Input::get('equipment'), array('class' => 'form-control clone'))}}
{{ $errors->first('equipment','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('selling_price[0]','Selling Price:')}}
{{ Form::text('selling_price[0]', Input::get('selling_price'), array('class'=>'form-control clone'))}}
{{ $errors->first('selling_price','<small class="error">:message</small>')}}
</li>
<li>
{{ Form::label('serial_number[0]','Serial Number:')}}
{{ Form::text('serial_number[0]', Input::get('serial_number'), array('class'=>'form-control clone'))}}
{{ $errors->first('serial_number','<small class="error">:message</small>')}}
</li>
<li>
<button href="#" class="add" rel=".clone"><i class="fa fa-plus-square"></i> Add Item</button>
</li>
</ul>
</li>
<li>
{{ Form::submit($buttonText) }}
</li>
</ul>
{{ Form::close(); }}
/**** Getting this error Undefined variable: items
* /app/controllers/SalesController.php
****/
Well you have a few errors in your code, but I'll try to give you a direction..
Replace the input fields with something like this:
{{ Form::text('items[0]["equipment"]', array('class' => 'form-control clone'))}}
....
{{ Form::text('items[0]["selling_price"]', array('class' => 'form-control clone'))}}
....
Grab the items using $items = Input::get('items'); (btw this is the point where php threw an error: you never got the $items from the request)
Iterate over the items array and add every single one of it to your Sale model..