Grabbing the ID number in a blade - php

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 }}

Related

How to pass a collection or array from blade file to controller in laravel?

$cartItems contains all the rows of products from database and I am using this inside a blade file.
I want to pass this $cartItems back to a controller from this blade file
Note: $cartItems is from index() function in a controller like below.
$cartItems = DB::table('products')->whereIn('id', $cartItemsArray)->get();
return view('cart.index', compact('cartItems')
Below is my code.
index.blade.php
Proceed to checkout
web.php
Route::get('/cart/checkout/{cartItems}', 'CartController#checkout')->name('cart.checkout')->middleware('auth');
CartController.php
public function checkout($cartItems)
{
dd($cartItems);
return view('cart.checkout');
}
The error I am getting is,
Missing required parameters for [Route: cart.checkout] [URI: cart/checkout/{cartItems}]. (View: E:\github\LARAVEL\Deal-Ocean\resources\views\cart\index.blade.php)
You can use a form to send data back to server
Update your route from get to post
Route::post('/cart/checkout', 'CartController#checkout')->name('cart.checkout')->middleware('auth');
Use a form to post data to server. You can pass any additional data along with the request as well.
<form method="post" action="/cart/checkout">
#foreach($cartItems as $item)
<input name="cartItems[]" value="{{ $item->id }}"
#endforeach
<button class="site-btn">Proceed to checkout</button>
</form>
And in your controller use Request to access data
public function checkout(Request $request)
{
$cartItems = DB::table('products')->whereIn('id', $request->get($cartItems))->get();
dd($cartItems);
return view('cart.checkout');
}
If you want to proceed with the get request you should be able to do as follow
As $cartItems is a collection of products. So you can send the product ids and query the products using the ids from request.
<a href="{{ route('cart.checkout', ['cartItems' => $cartItems->pluck('id')->toArray()]) }}"
class="site-btn">Proceed to checkout</a>
Update controller
public function checkout(Request $request)
{
$cartItems = DB::table('products')->whereIn('id', $request->get($cartItems))->get();
dd($cartItems);
return view('cart.checkout');
}
Why use the same code logic of the index() method in the checkout method in the
CartController.
the checkout method will look like this:
$cartItems = DB::table('products')->whereIn('id', $cartItemsArray)->get();
return view('cart.checkout', compact('cartItems');

how to check if object's variable is not empty?

I don't know if I correctly formulated the question. However, I've got 2 tables - products and categories (many to many relationship) and in categories page I want to display it's products with pagination if it has any and if it doesn't - I want to display "products not found". It worked, but without pagination.
Here's the controller:
public function show($slug)
{
$category = $this->categoryRepository->findBySlug($slug);
$paginate = $category->products()->paginate(6);
return view('site.pages.category')->with(['category' => $category,
'paginate' => $paginate]);
}
What to do achieve this?
Wrap it around an if statement like if(isset($your_variable) && !empty($your_variable)){ You may only need isset OR !empty, but you can mess around and see what works. Hope that helps!
I modified the controller like this:
public function show($slug)
{
$category = $this->categoryRepository->findBySlug($slug);
$products = $category->products();
if(isset($products) && !empty($products)){
$paginate = $products->paginate(6);
return view('site.pages.category')->with(['category' => $category,
'paginate' => $paginate]);
}
else {
return view('site.pages.category', compact('category'));
}
}
However, now I get this: Call to a member function products() on null..
Try this code below. I am not a Laravel Developer but just looked at some docs and writing this answer.
You are getting Call to a member function products() on null error, because $category is null (Not have any data). So you should check whether the $category have any data before calling products().
And you can check whether the products is empty or not in blade template and print the message accordingly. No need to render another template for that.
public function show($slug)
{
$category = $this->categoryRepository->findBySlug($slug);
if ($category) {
$products = $category->products()->paginate(6);
}
return view('site.pages.category')->with(['products' => $products]);
}
And in your Blade Template, check the $products is not empty,
#if ($products)
#foreach ($products as $product)
{{ $product->name}}
#endforeach
{{ $products->links() }}
#else
products not found
#endif
And obviously, change the template to your needs.

unable to print table data in laravel

need print column data in my laravel app. My controller is TaskController.php
public function index()
{
$tasks = Task::all();
return view('tasks.index')->with('tasks', $tasks);
}
index.blade.php file is
#if(isset($tasks))
#foreach ($tasks as $task)
<h1>{{ $task->task_name }}</h1>
#endforeach
#endif
I am going include this index view file in show.blade.php file as following
#include('tasks.index')
but unable to print table data no any errors occurred. how can I print task_name in show view file?
If you are including the index blade inside the show blade, then you need to change your controller and pass data to the final blade (show instead of index) like this
return view('tasks.show')->with('tasks', $tasks);
If you want to show data on task.index then use this code.
public function index()
{
$tasks = Task::all();
//this line will pass $task data to this view
return view('tasks.index',compact('tasks'));
}

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

Categories