Access Element of a field Variable - php

I want to access an element of a variable sent to the view
Here is my Controller
public function more($id)
{
$chickdata = Gamefarm::where('id','=',$id)->get();
$photos = Photo::where('chicken_id','=',$id)->get();
return View::make('gamefarms/readmore',compact('chickdata','photos'));
}
I am sending the variable 'photo' to the views
Here is the code that i want to work on views
#foreach ($photos as $myphotos)
#endforeach
<?php dd($myphotos->photo_loc[3]); ?>

I would try something like this:
public function more($id){
$chickdata = Gamefarm::where('id','=',$id)->get();
$photos = Photo::where('chicken_id','=',$id)->get();
$viewdata = array(
'chickdata'=> $chickdata,
'photos'=> $photos
);
return View::make('gamefarms/readmore', $viewdata);
}

Your view code is incorrect. It should be this.
#foreach ($photos as $myphotos)
{{ $myphotos->photo_loc[3] }}
#endforeach
No need to change your controller code - it is correct

Related

Pass json data to blade view from controller

I am loading a json file from my resources folder resources/data/example.json
public function __construct()
{
// Load json file
$path = base_path('resources/data/rooms.json');
$content = file_get_contents($path);
$data = json_decode($content);
}
my json file looks like this, it's a simple one just for an example:[ { "id":"bicycle", "category":"vehicle", "name":"Bicycle One", "images":[ "/img/bike_slider_1.jpg", "/img/bike_slider_2.jpg" ], },
so now I am wondering how can I pass some of this data to the view which is e.g bikes.blade.php
which looks like this:
#extends('layouts.default') #section('content') <main>{{ content[1] }}</main>
any help will be appreciated :)
public function index()
{
// Load json file
$path = base_path('resources/data/rooms.json');
$content = file_get_contents($path);
$data = json_decode($content);
return view('bikes', [
'items' => $data,
]);
}
Inside blade
#foreach ($items as $item)
{{ $item->name }}
#endforeach
https://laravel.com/docs/8.x/views#passing-data-to-views
you can follow this link. You already convert JSON data into object. Now just pass it from controller.
return view('yourBladeFile')->with('data ', $data );
Now in blade file you can read it like:
#foreach($data as $item)
<p> {{$item->name}} </p>
#endforeach
or other suitable way for you.

Grabbing the ID number in a blade

I have a route that takes me to my item page.
Route::get('/items/{item}', 'ItemsController#show');
In this page I have a form if the form is not filled out properly it will redirect to the forms method which currently is
action="/items"
How can I access that same {item} id number while in the blade?
Edit: Here is the Controller code
public function index()
{
$item = Post::get();
$price = $item->price;
return view('item');
}
public function show(Item $item)
{
return view('item', compact('item'));
}
You're returning compact('item') which gives you $item in your blade template.
You can use it within blade syntax, just like this:
{{ $item->id }}

laravel pagination : Call to a member function render() on array

In laravel controller I have following code:
public function getAdmins(){
//$users = $this->user->all();
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
$exceptSuperadmin = array();
foreach($users as $user){
if(!$user->isUser())
$staffs[] = $user;
}
$users = #$staffs;
return view('users::admins.list')->with('staffs',$users)->with('search',$search);
}
In Model I have:
public function findUsers($search)
{
return self::where('name','like','%'.$search['name'].'%')
->where('username','like','%'.$search['uname'].'%')
->where('role','like','%'.$search['role'].'%')
->paginate(5);
}
And In blade file I have:
#if($staffs)
#foreach($staffs as $staff)
<!-- Some code here to loop array -->
#endforeach
#else
No Staffs
#endif
{!! $staffs->render() !!} Error comes at this line
I am not geeting why this error comes....staffs is an array and render() a function to echo the pagination pages...but can't getting the error...Anybody to help.
By applying foreach the pager object and assign an array you lose the paging properties, so you will have an array rather than a pager object.
I recommend the following solution for your case:
Controller:
public function getAdmins(){
$search[] =array();
$search['name']= Input::get('name','');
$search['uname']= Input::get('uname','');
$search['role']= Input::get('role','');
$users = $this->user->findUsers($search);
return view('users::admins.list')->with('users',$users)->with('search',$search);
}
Blade file:
#if($users)
#foreach($users as $user)
#if(!$user->isUser())
<!-- Some code here to loop array -->
#endif
#endforeach
#else
No Staffs
#endif
{!! $users->render() !!}
NO, render() doesn't work on an object per se, neither on the array you are creating out of the required object for the pagination to work (LengthAwarePaginator)
Since you have a collection, and you need one, you could use one of the methods provided to do your filtering, such as filter.
Something like (untested but should work):
$staff = $users->filter(function ($value, $key) {
return !$value->isUser();
});

Passing data from controller to view in Laravel

I am new to Laravel and I have been trying to store all records of table 'student' to a variable and then pass that variable to a view so that I can display them.
I have a controller - ProfileController and inside that a function:
public function showstudents() {
$students = DB::table('student')->get();
return View::make("user/regprofile")->with('students',$students);
}
In my view, I have this code:
<html>
<head>
//---HTML Head Part
</head>
<body>
Hi {{ Auth::user()->fullname }}
#foreach ($students as $student)
{{ $student->name }}
#endforeach
#stop
</body>
</html>
I am receiving this error: Undefined variable: students (View:regprofile.blade.php)
Can you give this a try,
return View::make("user/regprofile", compact('students')); OR
return View::make("user/regprofile")->with(array('students'=>$students));
While, you can set multiple variables something like this,
$instructors="";
$instituitions="";
$compactData=array('students', 'instructors', 'instituitions');
$data=array('students'=>$students, 'instructors'=>$instructors, 'instituitions'=>$instituitions);
return View::make("user/regprofile", compact($compactData));
return View::make("user/regprofile")->with($data);
For Passing a single variable to view.
Inside Your controller create a method like:
function sleep()
{
return view('welcome')->with('title','My App');
}
In Your route
Route::get('/sleep', 'TestController#sleep');
In Your View Welcome.blade.php. You can echo your variable like {{ $title }}
For An Array(multiple values) change,sleep method to :
function sleep()
{
$data = array(
'title'=>'My App',
'Description'=>'This is New Application',
'author'=>'foo'
);
return view('welcome')->with($data);
}
You can access you variable like {{ $author }}.
The best and easy way to pass single or multiple variables to view from controller is to use compact() method.
For passing single variable to view,
return view("user/regprofile",compact('students'));
For passing multiple variable to view,
return view("user/regprofile",compact('students','teachers','others'));
And in view, you can easily loop through the variable,
#foreach($students as $student)
{{$student}}
#endforeach
You can try this as well:
public function showstudents(){
$students = DB::table('student')->get();
return view("user/regprofile", ['students'=>$students]);
}
Also, use this variable in your view.blade file to get students name and other columns:
{{$students['name']}}
Try with this code:
return View::make('user/regprofile', array
(
'students' => $students
)
);
Or if you want to pass more variables into view:
return View::make('user/regprofile', array
(
'students' => $students,
'variable_1' => $variable_1,
'variable_2' => $variable_2
)
);
In Laravel 5.6:
$variable = model_name::find($id);
return view('view')->with ('variable',$variable);
public function showstudents() {
$students = DB::table('student')->get();
return (View::make("user/regprofile", compact('student')));
}
try with this code :
Controller:
-----------------------------
$fromdate=date('Y-m-d',strtotime(Input::get('fromdate')));
$todate=date('Y-m-d',strtotime(Input::get('todate')));
$datas=array('fromdate'=>"From Date :".date('d-m-Y',strtotime($fromdate)), 'todate'=>"To
return view('inventoryreport/inventoryreportview', compact('datas'));
View Page :
#foreach($datas as $student)
{{$student}}
#endforeach
[Link here]
$books[] = [
'title' => 'Mytitle',
'author' => 'MyAuthor,
];
//pass data to other view
return view('myView.blade.php')->with('books');
or
return view('myView.blade.php','books');
or
return view('myView.blade.php',compact('books'));
----------------------------------------------------
//to use this on myView.blade.php
<script>
myVariable = {!! json_encode($books) !!};
console.log(myVariable);
</script>
In laravel 8 and above, You can do route binding this way.
public function showstudents() {
$students = DB::table('student')->get();
return view("user/regprofile",['students'=>$students]);
}
In the view file, you can access it like below.
#foreach($students as $student)
{{$student->name}}
#endforeach

How to pass collection to view in Laravel?

I think I am missing something very simple. But I have no more patience to seek for it, so I need to ask.
I am trying to render view with list of elements of type Event
In my view I have a foreach loop:
#foreach ($events as $e)
......
{{ $e->title }}
......
#endforeach
Controller:
$account = Account::find(\Session::get('account'));
$events = $account->events()->get();
return view('events.index')->with('events', $events);
In my understanding it should be working this way. But instead I get
Invalid argument supplied for foreach()
I also tried:
$account = Account::find(\Session::get('account'));
$events = $account->events();
return view('events.index')->with('events', $events);
but in this approach my foreach loop will not run even once (no error).
Of course I have everything defined in my models.
Account:
public function events()
{
return $this->hasMany('App\Event');
}
One approach which is working is passing data as array like this:
$account = Account::find(\Session::get('account'));
$events = $account->events()->get()->toArray();
return view('events.index')->with('events', $events);
But then I need to work with array indexes in my view like this:
#foreach ($events as $e)
......
{{ $e['title'] }}
......
#endforeach
and I really, really don't want to do it this way.
So please tell my what am I missing.
Update:
I can't pass $account to my view and use $account->events in the view because I need to perform some filtering on events before I pass it.
use like this
$account = Account::find(\Session::get('account'));
$events = $account->events;
return view('events.index',['events'=> $events]);
use collect:
$account = Account::find(\Session::get('account'));
$events = $account->events;
return view('events.index', collect('events'))
;

Categories