Looping through result of relational tables in laravel? - php

I do have a problem with the out of this code
this is the models used
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Navigation extends Model
{
protected $table = "navigation" ;
protected $primaryKey = "navi_id";
public function PrimaryNavigation()
{
return $this->hasMany(PrimaryNavigation::class);
}
}
and this how the query goes
<?php
namespace App\Http\Controllers;
use App\Navigation;
use App\PrimaryNavigation;
use Illuminate\Http\Request;
class NavigationController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$mainNavi = Navigation::with('PrimaryNavigation')->get() ;
return view('dump')->with('data',$mainNavi);
}
}
?>
Whenever i try to print out the result coming from this query it never showing the correct output from the related table .
when i print the output it shows correct result but when i tried to print out the related table data only it shows NULL value
#foreach($data as $single)
{{dd($single)}}</br>
#endforeach
this code shows the correct output
{"navi_id":8,"navi_name":"fouad","navi_route":"\/fouad","navi_sort":0,"navi_created_at":"2019-09-23 02:21:24.000000","navi_last_update":"2019-09-23 02:21:29.000000","primary_navigation":[{"primary_navi_id":5,"navigation_navi_id":8,"primary_navi_name":"tamer","primary_navi_route":"\/tamer","primary_navi_created_at":"2019-09-23 02:28:38.000000","primary_navi_last_update":"2019-09-23 02:28:40.000000","primary_navi_sort":0},{"primary_navi_id":13,"navigation_navi_id":8,"primary_navi_name":"momo","primary_navi_route":"\/momo","primary_navi_created_at":"2019-09-23 14:44:13.000000","primary_navi_last_update":"2019-09-23 14:44:15.000000","primary_navi_sort":0}]}
{"navi_id":9,"navi_name":"mohamed","navi_route":"\/mohamed","navi_sort":1,"navi_created_at":"2019-09-23 14:09:30.000000","navi_last_update":"2019-09-23 14:09:33.000000","primary_navigation":[{"primary_navi_id":6,"navigation_navi_id":9,"primary_navi_name":"soso","primary_navi_route":"\/SOSO","primary_navi_created_at":"2019-09-23 14:10:33.000000","primary_navi_last_update":"2019-09-23 14:10:36.000000","primary_navi_sort":0},{"primary_navi_id":14,"navigation_navi_id":9,"primary_navi_name":"yoyo","primary_navi_route":"\/yoyo","primary_navi_created_at":"2019-09-23 14:44:34.000000","primary_navi_last_update":"2019-09-23 14:44:37.000000","primary_navi_sort":0}]}
{"navi_id":10,"navi_name":"yasser","navi_route":"\/yasser","navi_sort":2,"navi_created_at":"2019-09-23 14:09:43.000000","navi_last_update":"2019-09-23 14:09:45.000000","primary_navigation":[{"primary_navi_id":7,"navigation_navi_id":10,"primary_navi_name":"mathy","primary_navi_route":"\/math","primary_navi_created_at":"2019-09-05 14:10:57.000000","primary_navi_last_update":"2019-10-09 14:10:59.000000","primary_navi_sort":0}]}
{"navi_id":11,"navi_name":"mahy","navi_route":"\/mahy","navi_sort":3,"navi_created_at":"2019-09-23 14:10:00.000000","navi_last_update":"2019-09-23 14:10:02.000000","primary_navigation":[{"primary_navi_id":8,"navigation_navi_id":11,"primary_navi_name":"toty","primary_navi_route":"\/toyt","primary_navi_created_at":"2019-09-23 14:11:20.000000","primary_navi_last_update":"2019-09-23 14:11:23.000000","primary_navi_sort":0},{"primary_navi_id":12,"navigation_navi_id":11,"primary_navi_name":"JAJA","primary_navi_route":"\/JAJ","primary_navi_created_at":"2019-09-23 14:43:54.000000","primary_navi_last_update":"2019-09-23 14:43:57.000000","primary_navi_sort":0}]}
but when i tried to show the related table only it gives null
#foreach($data as $single)
{{dd($single->primary_navigation)}}</br>
#endforeach

you must be instead of primary_navigation use ->PrimaryNavigation(as defined in your relationship)
#foreach($data as $single)
{{dd($single->PrimaryNavigation)}}</br>
#endforeach
or change your relation method name
public function primary_navigations()
{
return $this->hasMany(PrimaryNavigation::class);
}
and use
#foreach($data as $single)
{{dd($single->primary_navigations)}}</br>
#endforeach

Related

Laravel - Array to string conversion

I am trying to show the related applications to abstract, I have used the code below but I am getting this error
Array to string conversion
My controller
public function show($A_ID){
$abstract = Project::find($A_ID);
// I believe the issue is caused by the line below but I am not sure what is wrong about it
$applications = Application::find($A_ID);
return view('Abstracts.show')->with('abstract', $abstract)
->with($applications);
}
EDIT: (add model v1.0 and v1.1)
My model (v1.0) which show the error of Array to string conversion
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Traits\HasCompositePrimaryKey;
class Application extends Model{
//Table name
protected $table = 'student_application';
//composite key
protected $primaryKey = array('A_ID', 'S_ID');
protected $fillable = ['S_Justification' ];
public $incrementing = false;}
My edited Model (V1.1)
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Traits\HasCompositePrimaryKey;
class Application extends Model{
use HasCompositePrimaryKey;
//Table name
protected $table = 'student_application';
//composite key
protected $primaryKey = array('A_ID', 'S_ID');
protected $fillable = ['S_Justification' ];
public $incrementing = false;}
I want to note that the composite key is declared using this answer number two with currently 59 votes
For more information here is my view
#if (count($applications)>0)
#foreach ($applications as $application)
<tr>
<td><h5>{{$application->S_ID}}</h5></td>
</tr>
#endforeach
#else
<p> This project has no applications </p>
#endif
You are passing string to view.
return view('Abstracts.show')->with(['abstract'=> $abstract)];
give it a try.
Edit:
Or you can use like that.
with(array('order' => function($query)
Anyway you need to pass array in here. If you are just want to use ->with('abstract'); you need to add abstract function. For example:
public function deliveries() {
// this might be $this->hasOne... depends on what you need
return $this->hasMany('Abstracts', 'conditions', 'id')->where('foo', '!=', 'bar');
}
$applications is an object in your controller but you are accesing $applications as collection in your view file. You may try this:
$applications = Application::where('id', $A_ID)->get();
return view('Abstracts.show', compact('abstract', 'applications'));

Laravel 5.7 Undefined variable in view

I follow the guide ( https://www.phpflow.com/php/laravel-5-6-crud-operation-using-resource-controller/ ) and at point "How To Create Listing in Laravel 5.6" I get the error::
ErrorException (E_ERROR)
Undefined variable: employees (View: C:\xampp\htdocs\crud\resources\views\pages\index.blade.php)
Previous exceptions
* Undefined variable: employees (0)
And in code window the error is:
<?php
$__currentLoopData = $employees;
$__env->addLoop($__currentLoopData);
foreach($__currentLoopData as $key => $emp):
$__env->incrementLoopIndices();
$loop = $__env->getLastLoop(); ?>
Is it a compatibility issue between 5.6 and 5.7 or what? (please note that I am a noob in Laravel)
The guide is pretty slim, what you need to do in order to get you index working:
namespace App\Http\Controllers;
use App\Employee;
use Illuminate\Http\Request;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
//
return view('pages.index', ['employees' => Employee::all()]);
}
// ... The rest of the controller method below
}
If your resource definition is:
Route::resource('employee', 'EmployeeController');
The Path (URL) to access this will be: /employee
According to your link I do not see the full code of the controller, but your index method should look like this
public function index()
{
$employees = Employee::all();
// Pass data to view
return view('employee.index', ['employees' => $employees]);
}
The error remains, part of my code so far, EmployeeController.php:
public function index()
{
$employees = Employee::all();
return view('employee.index', ['employees' => $employees]);
}
Employee.php
class Employee extends Model
{
// Table name
protected $table = 'crud';
// Primary key
public $primaryKey = 'id';
}
index.blade.php
<tbody>
#foreach($employees as $key => $emp)
<tr>
<td>{{ $emp->id }}</td>
</tr>
#endforeach
</tbody>

Class 'App/Person' not found in index.blade.php

I'm building a Laravel 5.6.27 application in PHP 7.2.5 where assignments can be created and given a task (task_id) and a person (person_id) to assign them to (along with dueDate, etc.). I'm getting this error when I try to load the page:
Class 'App/Person' not found (View: /Users/mmickelson/Sites/sacrament/resources/views/assignments/index.blade.php)
Here's the index.blade.php file:
#extends('layouts.master')
#section('title', 'Assignments')
#section('content')
<table>
#foreach($assignments as $assignment)
<tr>
<td>{{$assignment->person->firstName}}</td>
</tr>
#endforeach
</table>
#endsection
I'm showing only the firstName of the person to help make it as simple as possible and isolate the issue.
Here's the (beginning of) the AssignmentController.php:
use App\Assignment;
use App\Task;
use App\Person;
use Illuminate\Http\Request;
class AssignmentController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index() {
$assignments = Assignment::all();
return view('assignments.index', ['assignments'=>$assignments]);
}
...
Here's the (beginning of) the Assignment.php model:
namespace App;
use Carbon\Carbon;
use Collective\Html\Eloquent\FormAccessible;
use Illuminate\Database\Eloquent\Model;
class Assignment extends Model
{
use FormAccessible;
protected $fillable = ['person_id', 'task_id', 'dueDate', 'status', 'completedDate'];
public function person()
{
return $this->hasOne('App/Person');
}
...
The database table for "assignments" has a person_id column, as a foreign key to the "people" table.
If I remove person->name from index.blade.php, leaving the line as <td>{{$assignment}}</td>, the page loads fine but of course, shows the object. So, it seems to have something to do with accessing the Person associated with the Assignment.
Any ideas about what is causing the error?
I guess this issue because the name of class is wrong App/Person should be App\Person
and you can write it like the following:
public function person()
{
return $this->hasOne(\App\Person::class);
}
There is a minor mistake in your model:
public function person()
{
return $this->hasOne('App/Person');
}
Change the above code to below code:
public function person()
{
return $this->hasOne('App\Person');
}
it is better if you use the below code:
public function person()
{
return $this->hasOne(Person::class);
}
Person::class is same as App\Person.

Adding data to from a database to the Index page of laravel 5.4

I am trying to create an adverts section on my landing page of a laravel 5.4 project using data from a database but it is not working.
in my welcome, I have added this lines of code
foreach($adverts as $advert) {
$advert;
}
I have then created a WelcomeController with the following code
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class WelcomeController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function __construct()
{
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
$adverts = DB::table('adverts')->get();
return view('welcome', ['adverts' => $adverts]);
}
}
This gives me an error $adverts is not defined
What could I be doing wrong?
$adverts is not defined error is coming because you are missing echo or {{ $adverts->item }} in case of Laravel.
You need to echo $adverts data in foreach in your blade file in the below way:
#foreach($adverts as $advert)
{{ $advert->item }}
#endforeach
Or you can simply use PHP as well like below:
foreach($adverts as $advert){
echo $advert->item;
}
You can also convert your data to array and then display in foreach like below:
$adverts = DB::table('adverts')->get();
$adverts = json_decode( json_encode($adverts), true);
#foreach($adverts as $advert)
{{ $advert['item'] }}
#endforeach
You can first check what's coming in $advert array in the below way:
echo "<pre>"; print_r($adverts); die;

How can I compact this code for sending info to the view from the Laravel Controller?

Here's my edit function in the controller
public function edit($id)
{
$game = Game::find($id);
// build list of team names and ids
$allTeams = Team::all();
$team = [];
foreach ($allTeams as $t)
$team[$t->id] = $t->name();
// build a list of competitions
$allCompetitions = Competition::all();
$competition = [];
foreach ($allCompetitions as $c)
$competition[$c->id] = $c->fullname();
return View::make('games.edit', compact('game', 'team', 'competition'));
}
I am sending data in order to display in a select list. I know about Eloquent ORM method Lists, but the problem is as far as I know it can only take property names as an argument, and not methods (like name() and fullname()).
How can I optimize this, can I still use Eloquent?
I would look into attributes and appends. You can do what you would like by adjusting your models.
Competition
<?php namespace App;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class Competition extends Model
{
protected $appends = ['fullname'];
...
public function getFullnameAttribute()
{
return $this->name.' '.$this->venue;
}
}
Team
<?php namespace App;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $appends = ['name'];
...
public function getNameAttribute()
{
return $this->city.' '.$this->teamName;
}
}
Controller
public function edit($id)
{
$game = Game::find($id);
$team = Team::get()->lists('id','name');
$competition = Competition::get()->lists('id','fullname');
return View::make('games.edit', compact('game', 'team', 'competition'));
}
The only thing I can think of (aside from using the map functionality of Eloquent collections) is to overwrite the toArray method in your model to add some custom attributes.
Eg.
public function toArray()
{
return array_merge(parent::toArray(), [
'fullname' => $this->fullname(),
]);
}
This will allow you to use something like:
$competition = $allCompetitions->fetch('fullname');
Although:
In saying all this I think the more elegant solution is to just provide the whole competition objects to the view and let the loop where you render them (or whatever) call the method itself.
You can call model method in view file if they are not related with other models. So if name() & fullname() returns result related to this model then you can use this model methods in view
#foreach (($allTeams as $t)
{{ $t->name() }}
#endforeach
ofcourse you have to pass the $allteams collection from controller to view

Categories