passing different type variables to the view from controller in laravel - laravel

i want to pass two variables called as repcounter and suppliers to the view to do two different task.
here is my function in controller,
public function admin()
{
$suppliers = SupplierData::all();
$repcounter= SalesRep::count();
return view('dashboard', compact('suppliers'));
}
this is how i send suppliers data. it worked fine. but i don't have an idea to send repcounter and suppliers at once.. each time i try i gave error undefined variable.
so how to send this two varibles to the dashboard.blade.php view?

You should try this:
public function admin()
{
$suppliers = SupplierData::all();
$repcounter= SalesRep::count();
return view('dashboard', compact('suppliers','repcounter'));
}

Replace:
return view('dashboard', compact('suppliers'));
With the following code:
return view('dashboard', compact('suppliers,'repcounter'));

You can pass multiple variables to the view by nesting the data you want in an array. See below code.
public function admin()
{
//create an empty array
$response = array();
//nest your data insde the array instead of creating variables
$response['suppliers'] = SupplierData::all();
$response['repcounter'] = SalesRep::count();
return view('dashboard', compact('response'));
}
Inside your View, you can access them as below
$response['suppliers']
$response['repcounter']

Related

pass array to the same controller function that accepts request object in laravel

I have a testController in which I have two function importCustomer() and addUpdateCustomer(Request $request).
I want to pass on the importCustomer values to the addUpdateCustomer function, but the problem is I can't pass the array, because of the request object.
function importCustomer(Request $request){
//Will read the csv file and for each record call the
//addUpdateCustomer function
$dataPayload = [];
$this->addUpdateCustomer($dataPayload);
}
function addUpdateCustomer(Request $request){
//Insert if user is new else update the details if already exists.
}
Is the addUpdateCustomer function publically accessible, meaning is there a route defined for it? If not just remove the Request object as a parameter and replace it with an array.
public function addUpdateCustomer(array $payload = [])
{
// do stuff
}
Alternatively you merge some content into the $request:
$this->addUpdateCustomer($request->merge($dataPayload));

recover the slug of a category linked to another category Laravel

I would like to recover the slug of 2 categories from my routes but can’t write the Controller.
My Route
Route::get('technicians/o/{occupation}/c/{city}', 'User\TechnicianController#viewoccupationcity');
My Controller
public function viewoccupationcity($slug)
{
$technicians = TechnicianResource::collection(occupation::where('slug',$slug)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
Route::get('technicians/o/{occupation}/c/{city}', 'User\TechnicianController#viewoccupationcity');
Your controller will accept the parameters from your route as variables by order
public function viewoccupationcity($ocupation, $city)
{
...
}
Example:
URL: technicians/o/foo/c/bar
public function viewoccupationcity($ocupation, $city)
{
// $ocupation will be 'foo'
// $city will be 'bar
}
Ok, you would need to retrieve 2 variables as that is what you are passing
public function viewoccupationcity($occupation, $city)
If you want the whole slug to do another search then you would use the $request object. So like so
public function viewoccupationcity(Request $request, $occupation, $city){ // You also need to include the Request decleration
$slug = $request->path();
$technicians = TechnicianResource::collection(occupation::where('slug',$slug)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
EDIT: We are having to do a lot of guesswork as your question isn't very clear. I think what you are trying to achieve is probably this
public function viewoccupationcity($occupation, $city){
$technicians = TechnicianResource::collection(occupation::where('city',$city)->where('occupation',$occupation)->firstOrFail()->technicians()
->with('city','occupation')
->latest()->get());
return $technicians;
}
If you need something more then you need to give more details

Redirect from controller to named route with data in laravel

I'm gonna try to explain my problem:
I have a named route called 'form.index' where I show a html form.
In FormController I retrieve all form data.
After do some stuff with these data, I want to redirect to another named route 'form.matches' with some items collection.
URLS
form.index -> websiteexample/form
form.matches -> websiteexample/matches
FormController
public function match(FormularioRequest $request)
{
// Some stuffs
$list = /*Collection*/;
return redirect()->route('form.matches')->with(compact('list'));
}
public function matches()
{
// How to retrieve $list var here?
return view('form.views.matches')->with(compact('list'));
}
The problem:
When the redirects of match function occurs, I get an error "Undefined variable: list' in matches funcion.
public function match(Request $request)
{
// Operations
$list = //Data Collection;
return redirect()->route('form.matches')->with('list',$list);
}
In view
#if(Session::has('list'))
<div>
{!!Session::get('list')!!}
</div>
#endif
You can use Redirect::route() to redirect to a named route and pass an array of parameters as the second argument
Redirect::route('route.name',array('param1' => $param1,'param2' => $param2));
Hope this helps you.

Laravel 5.4 Undefined Variable from controller to view

I recently got started with Laravel 5.4, I'm familiar with 5.3. I'm trying to pass a variable from my controller to the view and keep getting an "Undefined variable $savedStores".
public function index()
{
//
$stores = Store::where('id as user_id')->get();
return view('home')->with('savedStores', $store);
}
That is my controller code.
In my view, I have
#if(count($savedStores)>0)
#foreach($savesStores as $savedStore)
<p>{{$savedStore -> name}}</p>
#endforeach
#endif
return view('home',['savedStores'=>$stores]);
spelling mistake chane $store to $stores
Just change your code:
from:
$stores = Store::where('id as user_id')->get();
to:
$stores = Store::where('id',$some_id_value)->get();
Or you can get all store records by:
$stores = Store::all();
You are passing the variable to view in correct manner.
More details check here:
https://laravel.com/docs/5.4/views
Actually with method used for session data.
You can pass variables to view.
return view('home',['savedStores'=>$stores]);
or
return view('home',compact('stores')); // as store variable.
Try this one,
public function index()
{
$stores = Store::select('*','id as user_id')->get();
dd($stores);//see query result, if you get correct result here, just remove this line
return view('home')->with('savedStores', $stores );
}

Adding methods to Eloquent Model in Laravel

I'm a bit confused how I am to add methods to Eloquent models. Here is the code in my controller:
public function show($id)
{
$limit = Input::get('limit', false);
try {
if ($this->isExpand('posts')) {
$user = User::with(['posts' => function($query) {
$query->active()->ordered();
}])->findByIdOrUsernameOrFail($id);
} else {
$user = User::findByIdOrUsernameOrFail($id);
}
$userTransformed = $this->userTransformer->transform($user);
} catch (ModelNotFoundException $e) {
return $this->respondNotFound('User does not exist');
}
return $this->respond([
'item' => $userTransformed
]);
}
And the code in the User model:
public static function findByIdOrUsernameOrFail($id, $columns = array('*')) {
if (is_int($id)) return static::findOrFail($id, $columns);
if ( ! is_null($user = static::whereUsername($id)->first($columns))) {
return $user;
}
throw new ModelNotFoundException;
}
So essentially I'm trying to allow the user to be retrieved by either user_id or username. I want to preserve the power of findOrFail() by creating my own method which checks the $id for an int or string.
When I am retrieving the User alone, it works with no problem. When I expand the posts then I get the error:
Call to undefined method
Illuminate\Database\Query\Builder::findByIdOrUsernameOrFail()
I'm not sure how I would go about approaching this problem.
You are trying to call your method in a static and a non-static context, which won't work. To accomplish what you want without duplicating code, you can make use of Query Scopes.
public function scopeFindByIdOrUsernameOrFail($query, $id, $columns = array('*')) {
if (is_int($id)) return $query->findOrFail($id, $columns);
if ( ! is_null($user = $query->whereUsername($id)->first($columns))) {
return $user;
}
throw new ModelNotFoundException;
}
You can use it exactly in the way you are trying to now.
Also, you can use firstOrFail:
public function scopeFindByIdOrUsernameOrFail($query, $id, $columns = array('*')) {
if (is_int($id)) return $query->findOrFail($id, $columns);
return $query->whereUsername($id)->firstOrFail($columns);
}
Your method is fine, but you're trying to use it in two conflicting ways. The one that works as you intended is the one in the else clause, like you realised.
The reason the first mention doesn't work is because of two things:
You wrote the method as a static method, meaning that you don't call it on an instantiated object. In other words: User::someStaticMethod() works, but $user->someStaticMethod() doesn't.
The code User::with(...) returns an Eloquent query Builder object. This object can't call your static method.
Unfortunately, you'll either have to duplicate the functionality or circumvent it someway. Personally, I'd probably create a user repository with a non-static method to chain from. Another option is to create a static method on the User model that starts the chaining and calls the static method from there.
Edit: Lukas's suggestion of using a scope is of course by far the best option. I did not consider that it would work in this situation.

Resources