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?
Related
I'm working with Laravel 5.1
I have a template for a page that was previously working fine. I could hit my route and the page would be rendered as expected. At some point the page started just displaying the text contained in the blade template rather than rendering my page. To my knowledge nothing had changed in my routes file, controller or blade. Is there anything that is known to cause this to happen? I've tried updating permissions, using a different method to call the view and creating a new view file all together.
The route:
Route::group(['prefix' => '/admin'], function() {
Route::group(['prefix' => '/reactor-rules'], function() {
Route::get('/visual-rules/{track_id?}', [
'as' => 'broker_visual_reactor_rules',
'uses' => 'ReactorRulesController#visualRules'
]);
});
});
ReactorRulesController#visualRules:
public function visualRules(IReactorTrackDAO $reactorTrackDAO, $id = 0)
{
$export = new ReactorExport();
$tracks = $export->getReactorTracks();
if ($id == 0) {
$eventsArray = [];
}
else {
$eventsArray = $export->getArrayForTrack($id);
}
return $this->renderView('enterpriseBroker::reactor-rules.visual-rules', compact('eventsArray','tracks','reactorTrackDAO'));
}
My blade:
#extends($layout)
{{ SEO::setPageTitle(trans('enterpriseBroker::reactorRules.title'), false) }}
#section('content')
<br>
<br>
#if(empty($eventsArray))
<p>Please select a track below to view/export rules.</p>
#foreach($tracks as $track)
{{$track->name}}<br>
#endforeach
#else
#foreach($eventsArray as $track => $events)
<h4>{{$track}}</h4>
<a href="{{url().'/admin/visual-rules/'.$reactorTrackDAO->findByName($track)->id.'/download'}}" class="btn btn-primary" download>Export</a><br>
#foreach($events as $id => $event)
#if (count($event['rules']) > 0)
<div id="{{$track.'-'.str_replace(' ','_',$event['name'])}}">
<div class="col-lg-12">
<hr/>
<div class="col-lg-2">
<h4>{{$event['name']}}</h4>
</div>
<div class="col-lg-10 border border-primary">
#foreach($event['rules'] as $ruleId => $rule)
<h5>{{$rule['name']}}</h5>
<div class="col-lg-6">
<h6>Conditions to be met:</h6>
#foreach($rule['conditions'] as $condition)
<p>{{$condition}}</p>
#endforeach
</div>
<div class="col-lg-6">
<h6>Actions to run:</h6>
#foreach($rule['actions'] as $action)
<p>{!!$action!!}</p>
#endforeach
</div>
#endforeach
</div>
</div>
</div>
#endif
#endforeach
#endforeach
#endif
#endsection
#section('scripts')
#endsection
This is how it originally appeared:
This is how it currently appears:
It seems to be error with $layout
Try to test it using a hard coded value as below:
#extends('layouts.app')
and run below command
php artisan view:clear
I resolved the issue by creating a new blade file, pasting the contents of the old one in and pointing my controller to the new view. I'm not sure how this resolved the issue.
I'm trying to show a book's comments by ISBN (book table's PK) and I get the following error:
Invalid argument supplied for foreach
I'm using Laravel relationship and a foreach to get the records from the following query, in a Helper class:
function getCommentsByISBN($data)
{
foreach (Book::where("ISBN", $data)->get() as $comments) {
return $comments->comments;
}
}
And here's my Book model, comment relationship:
public function comments()
{
return $this->hasMany(Comment::class, "ISBN", "ISBN");
}
And here's the view where I show the comments:
#foreach(getCommentsByISBN(session("isbn")) as $comment)
<div class="form-group">
<h3>
{{ getUserWhoPostedComment($comment->email) }}
</h3>
<p>
{{ $comment->commentary }}
</p>
#if(Session::has("username") && isAdmin(session("username")))
<button type="button" onclick="openModal('{{$comment->commentary}}')"
name="warningButton" class="btn btn-warning" data-toggle="modal"
data-target="#modalWarning">
<i class="fas fa-exclamation-circle"></i>
</button>
#endif
<hr>
<span>
Hace: {{ getTimeWherePostedComment($comment->publicated_at) }}
</span>
</div>
#endforeach
Thanks in advance!
I think you helper returns void because no book was found with that ISBN.
I think it should look like this btw
function getCommentsByISBN($isbn)
{
if ($book = Book::where("ISBN", $isbn)->first()) {
return $book->comments;
}
}
and in your blade your top should look like
#php
$comments = getCommentsByISBN(session("isbn")) ?: [];
#endphp
#foreach($comments as $comment)
<div class="form-group">
/// Rest of the code
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);
});
}
I'm trying register in my app but this Error happened and I don't know why.
and my post.blade.php file has this code:
<div class="blog-post">
<h2 class="blog-post-title">
<a href="/posts/{{$post->id}}">
{{$post->title}}
</a>
</h2>
<p class="blog-post-meta">
{{$post->user->name }}
{{$post->created_at->toFormattedDateString()}}
</p>
{{$post->body}}
postcontroller has this code:
public function index()
{
$posts=Post::latest()->get();
return view('posts.index',compact('posts'));
}
and index file is:
#foreach($posts as $post)
#include('posts.post')
#endforeach
<nav class="blog-pagination">
<a class="btn btn-outline-primary" href="#">Older</a>
<a class="btn btn-outline-secondary disabled" href="#">Newer</a>
</nav>
</div><!-- /.blog-main -->
I think your code need to update like:
public function index()
{
$posts=Post::with('users')->latest()->get();
return view('posts.index',compact('posts'));
}
<p class="blog-post-meta">
{{$post->users->name }}
{{$post->created_at->toFormattedDateString()}}
</p>
Hope this work for you!
assume that you are including post.blade.php in index.blade.php file.
In above case you are not passing $post to post.blade.php. Your foreach loop will be like :
#foreach($posts as $post)
#include('posts.post', ['post' => $post])
#endforeach
I assume that you are including post.blade.php in index.blade.php file.
In above case you are not passing $post to post.blade.php. Your foreach loop will be like :
#foreach($posts as $post)
#include('posts.post', ['post' => $post])
#endforeach
My model code
how we can call this function in blade.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class BasicModel extends Model
{
public static function get_product_count($id){
$query = "select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id";
print_r($query);
return $query->row_array();
}
}
My view.blade.php code
count in foreach loop or show in all category
#foreach ($r as $row)
<li class="grid-item type-rent">
<div class="property-block">
<img src="{{ URL::to('/template/images/background-images/sub-category-images/' .$row->sub_cat_images. '')}}" alt=""> <!-- <span class="images-count"><i class="fa fa-picture-o"></i> 2</span> <span class="badges">Rent</span> -->
<div class="property-info">
<h4>{{ ucwords(substr($row->sub_cat_name, 0, 22)) }}</h4>
<span class="location">NYC</span>
<div class="price"><strong>Items</strong><span>
<!-- start count code from here -->
$data = $this->BasicModel->count {{ ($row->sub_id) }}
echo $data['count'];
</span></div>
</div>
<!-- <div class="property-amenities clearfix"> <span class="area"><strong>5000</strong>Area</span> <span class="baths"><strong>3</strong>Baths</span> <span class="beds"><strong>3</strong>Beds</span> <span class="parking"><strong>1</strong>Parking</span> </div> -->
</div>
</li>
#endforeach
My BasicController Code
public function grid(Request $request, $id)
{
if ($id == 1) {
$r = DB::table('sub_category')->select('*')->where('cat_id', $id)
->where('sub_status', '1')->orderBy('sub_id', 'asc')->get();
$name = DB::table('category')->where('cat_id', $id)->get();
return view('buy-and-sell/grid', compact('r','name','count'));
}
image for your help
image for your help
problem in this image please solve the problem
Although its no good Practice Accessing the DB in Blade (better do this in the controller and pass the data) you can do:
<div class="price"><strong>Products</strong>
<span>
{{ BasicModel::where('sub_id', $row->sub_id)->count() }}
</span>
</div>
Its not tested, but have a look at the Eloquent docs, the count() method is explained there.
Update: I am not shure if laravel will find the class BasicModel (I never would access Models directly in blade, as stated do this in the controller and pass the data.) So maybe you need to write it with the full Namespace most likely {{ \App\BasicModel::where() }}.