I am trying to fetch some data from table in laravel 5.0 like so
public function index()
{
$data = DB::table('modules')->get();
return view("BaseView.home")->with('data',$data);
}
this is my view
#foreach($data as $modules)
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
{!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
#foreach($moduleCategories as $category)
<a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
#endforeach
</div>
</li>
#endforeach
$module->id is obtained from another query result. Now when I try to run this I am getting Array to string conversion. Can someone point out the mistake. The expected output is > 1 in the sense there can be multiple categories names matching that condition.
The problem is that you are trying to put php logic inside an echo {{ ... }}. You are trying to echo out a collection or an array of data, hence the error you are getting, Array to string conversion. The proper way to do this is to do the logic in the controller. But for a quick fix, replace:
{!! $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get() !!}
to
<php $moduleCategories = DB::table('module_categories')->where('modules_id','=',$modules->id)->get(); ?>
Never use {{ ... }} or {!! ... !!} to put logic, those are to echo out a string.
==EDIT==
I suggest to use laravels eloquent relationship methods, this will simplify the code, and seperate the logic from the view.
Note: Expecting if you are using laravel naming convention.
On your Modules model, add a relationship to ModuleCategory like so:
public function module_categories()
{
return $this->hasMany('App\ModuleCategory');
}
On your controller, on the index method replace :
$data = DB::table('modules')->get();
with
$data = Modules::get();
and finally on the view, change it like so:
#foreach($data as $modules)
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{{ $modules->module_name }}<i class="plusMinus fa fa-plus-square plusMinusSpacing" aria-hidden="true"></i>
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
#foreach($modules->module_categories as $category)
<a class="dropdown-item" href="#">{{ $category->categories_name }}</a>
#endforeach
</div>
</li>
#endforeach
As I commented on Carlos's solution, here is how I solved the same error...
//Controller
$users = User::where('blah', 'blah')->get();
return view('index', [
'users' => $users,
]);
//View
<script type="text/javascript">
angular.module("app").factory("DataService", function() {
return {
users: {!! $users !!},
};
});
</script>
As discussed above, this will result in the Array to string conversion error, since $users is an array.
However, this error won't happen if $users is a `collection'
I.e.
//Controller
$users = User::all();
return view('index', [
'users' => $users,
]);
//This is ok
Or,
//Controller
$users = collect([]);
return view('index', [
'users' => $users,
]);
//This is fine too
Related
I'm trying to find the slugs complete and incomplete model TaskboardColumn, then I only want the values of the user and the project.
Here is what I've tried:
Model
public static function projectOpenTasks($projectId, $userID=null)
{
$taskBoardColumn = \App\TaskboardColumn::where('slug', 'incomplete')->first();
$taskBoardColumn2 = \App\TaskboardColumn::where('slug', 'inprogress')->first();
$projectTask = \App\Task::where('tasks.board_column_id', $taskBoardColumn->id)->orWhere('tasks.board_column_id', $taskBoardColumn2->id);
if($userID)
{
$projectIssue = $projectTask->where('user_id', '=', $userID);
}
$projectIssue = $projectTask->where('project_id', $projectId)
->get();
return $projectIssue;
}
Controller
$this->openTasks = Task::projectOpenTasks($this->project->id);
View
<ul class="list-task list-group" data-role="tasklist">
<li class="list-group-item" data-role="task">
<strong>#lang('app.title')</strong>
<span class="pull-right"><strong>#lang('app.dueDate')</strong></span>
</li>
#forelse($openTasks as $key=>$task)
<li class="list-group-item row" data-role="task">
<div class="col-xs-8">
{{ ($key+1).'. '.ucfirst($task->heading) }}
</div>
<label class="label label-danger pull-right col-xs-4">{{ $task->due_date->format($global->date_format) }}</label>
</li>
#empty
<li class="list-group-item" data-role="task">
#lang('messages.noOpenTasks')
</li>
#endforelse
</ul>
With this code I'm getting all the tasks, and I need just this project's tasks.
You can use grouping to achieve this
$projectTask = \App\Task::where(function($q) {
$q->where('tasks.board_column_id', $taskBoardColumn->id);
$q->orWhere('tasks.board_column_id', $taskBoardColumn2->id)
})->get();
Thanks
orwhere is used in places where only one of the query has to run. just like and keyword in programming orwhere is used in sense of query.
following is the code snippet -
$projectTask = $query->where('tasks.board_column_id', $taskBoardColumn->id)
->orWhere('tasks.board_column_id', $taskBoardColumn2->id)
->get();
I create an array for the blade view. Collect the data from table and store in an array, $post_data. For laravel generated array, foreach loop will do the job. But, it seems a different things with self created array. Please help.
I use 2 foreach because the array consist of 2 dimensional array.
The result of dd($post_data)
The result of var_dump($data)
The result of var_dump($item)
ERROR: Trying to get property 'title' of non-object
Controller
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = array('title' => $post->article_title,
'name' => $RMM->department.'#'.$post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
}
}
Blade
#foreach($post_data as $key => $data)
#foreach ($data as $item)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item->title }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item->name }}
# {{$item->department}}</a>
</div>
#endforeach
#endforeach
Company
```migrations```
Schema::create('companies', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('department');
$table->string('branch');
$table->timestamps();
});
Post
Schema::create('posts', function (Blueprint $table) {
$table->bigIncrements('id');
$table->timestamps();
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('company_id');
$table->string('event_title')->nullable();
$table->string('article_title')->nullable();
$table->string('date');
$table->string('author')->nullable();
$table->string('article')->nullable();
$table->string('description')->nullable();
$table->string('file')->nullable();
$table->string('banner_image')->nullable();;
$table->string('gallery_image')->nullable();
$table->index('user_id');
$table->index('company_id');
});
The problem is you are tying to access a property of a NON OBJECT as the error says.
item is not an object, it's an array.
so you have to use the array access method to access its values.
#foreach($post_data as $key => $data)
#foreach ($data as $item)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item['name'] }}
# {{$item['department'] }}</a>
</div>
#endforeach
#endforeach
UPDATE
Looking at the dump of the $post_data realized that you don't have to loop each element of the array again.
#foreach($post_data as $key => $data)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $data['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $data['name'] }}</a>
</div>
#endforeach
If you just want get the title, name and date it's simple
Controller
post_data = Array();
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = array(
'title' => $post->article_title,
'name' => $RMM->department.'#'.$post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
}
}
// You can send a array of objects
return view('example')->with('posts', $post_data);
View
#foreach($posts as $post)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item['name'] }}
# {{$item['department']}}</a>
</div>
#endforeach
I correct it. Thank you for all the comments and advice. Here is how I do it.
The $post_data[] is correct since I need to store a lot of return result from find function. Since, find already return an array of corresponding id, I do not need to put into another array, just use it as it is, as explain by #Ghost. Thus, one foreach enough to get the job done.
Controller
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = $post;
}
return view('home')->with('posts', $post_data);
}
Blade
#foreach($posts as $post)
<div class="col bg-light ">
<a class="nav-link pb-0 pt-0" href="#">{{ $item['title'] }}</a>
<a class="nav-link pb-0 pt-0" href="#">{{ $item['name'] }}
# {{$item['department']}}</a>
</div>
#endforeach
Update answer
Another method, is to convert the array into object. The error is about non-object, directly working on it would help.
ERROR: Trying to get property 'title' of non-object.
Alternative way
$RMM = DB::table('companies')->where('branch', 'RMM')->get();
foreach ($RMM as $RMM)
{
$post = post::find($RMM->id);//get post for each department
if (isset($post))
{
$post_data[] = array('title' => $post->article_title,
'name' => $RMM->department.'#'.$post->author,
'date' => date('Y-m-d', strtotime($post->date)),
);
}
}
//change to object before send to blade
$object = json_decode(json_encode($post_data), FALSE);
return view('home')->with('posts', $object);
$permissions = DB::table('file_permissions')
->leftjoin('adminfiles','file_permissions.fileid','adminfiles.id')
->where('user_id', $user)
->get();
I am getting these file permissions as per user from the database and listing them in the left column of the admin panel
<ul class="treeview-menu">
#foreach($permissions as $permission)
<li><i class="fa fa-circle-o"></i> {{ $permission->filename }}</li>
#endforeach
</ul>
But in the output it makes url like this
http://localhost/laravel/$permission-%3Efileaddress
thanks in advance
Check the Laravel route parameters
https://laravel.com/docs/5.5/routing#route-parameters
Example (see docs)
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
Link like that
link
I think this will do the trick.
<a href="{{ url('') }}/{{ $permission->fileaddress }}">
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 want to make menu and submenu dynamic .I made menu with their link but unable to make submenu,please help me my database structure
table name:menu
id menu_name url timestamps
table:sub_menu
id submenu_name link menu_id timestamps
my query is like this
public function menu()
{
$sql=\DB::table('menu')->rightjoin('sub_menu','menu.id','=','sub_menu.menu_id')
->select('submenu_name','link','url','menu_id','menu_name','menu.id')->get();
return view('products.show.menu',compact('sql'));
}
view
<ul>
#foreach($sql as $key => $nav)
#if($key > 0)
<li>
{{$nav->menu_name}}
#if (count($nav->submenu_name) > 0 )
<ul>
#foreach($nav->submenu_name as $child)
<li>{{$child->submenu_name}}</li>
#endforeach
#endif
</ul>
</li>
#endif
#endforeach
</ul>
Have you set up models for these tables? Your query will return multiple rows for each menu/submenu combination, meaning you can't just iterate over it as you are. There's no need to use the query builder here.
Assuming your models are set up as follows (you will need to check the namespace used in the relationships):
class Menu extends Eloquent
{
protected $table = 'menu';
public function submenu()
{
return $this->hasMany('App\SubMenu');
}
}
class SubMenu extends Eloquent
{
protected $table = 'sub_menu';
public function menu()
{
return $this->belongsTo('App\Menu');
}
}
In your controller, you can do:
public function menu()
{
$menu = Menu::with('submenu')->get();
return view('products.show.menu', compact('menu'));
}
Then in your view:
<ul>
#foreach($menu as $menuItem)
<li>
{{ $menuItem->menu_name }}
#if( ! $menuItem->submenu->isEmpty())
<ul>
#foreach($menuItem->submenu as $subMenuItem)
<li>{{ $subMenuItem->submenu_name }}</li>
#endforeach
</ul>
#endif
</li>
#endforeach
</ul>
You can use it without controller
`#foreach(App\Menu::get() as $menuItem)
#if( ! $menuItem->submenu->isEmpty() )
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
{{ $menuItem->menu_name }}
</a>
#else
<li>
{{ $menuItem->menu_name }}
#endif
#if( ! $menuItem->submenu->isEmpty())
<ul class="dropdown-menu" role="menu">
#foreach($menuItem->submenu as $subMenuItem)
<li>{{ $subMenuItem->submenu_name }}</li>
#endforeach
</ul>
#endif
</li>
#endforeach`