It can not find my variable in my view in laravel 5.6 - laravel

<?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$datanews['newss'] = News::orderBy('created_at','desc')->get();
$dataevent['events'] = Event::orderBy('created_at','desc')->get();
$user['users'] = User::all();
return view('user/aktuelles.index',$datanews, $dataevent,$user);
}
this is a part of my controller, i can show news and events in my view but everytime it says it can not find the variable user?
i dont know why because i dont know why it shows me the other variables but not the user variable???
in my view i can see the other variables like this:
#foreach ($newss as $news)
{{$news->newstitel}}
#endforeach
but i want to show user like this:
{{$user[1]->avatar}}
i tried everything so i tried so look my controller like this:
$user = DB::table('users')->get();
or get the variable via compact
and i tried exactly the same so like this
$user['users'] = User::orderBy('created_at','desc')->get();
and a foreach in my view but it can not found the variable user??
i dont know why
this is the error
Undefined variable: users

return view('user.aktuelles.index', compact('datanews', 'dataevent', 'user');

I am not sure how the helper view() handles the 4th parameter you are passing. According to the docs you can pass data like this:
return view('user/aktuelles.index',[
'datanews' => $datanews,
'dataevent' => $dataevent,
'user' => $user,
]);
or
return view('user/aktuelles.index')->with([
'datanews' => $datanews,
'dataevent' => $dataevent,
'user' => $user,
]);
Maybe give this way a try.
Edit:
The view() helper accepts 3 Parameters: $view = null, $data = [], $mergeData = [] so the 4th parameter you are trying to pass is not even working. You have to pass your data as second parameter or with the chained function with(array $data).

You have to return value in view like below method:
Change this line
$user['users'] = User::orderBy('created_at','desc')->get();
To
$user = User::orderBy('created_at','desc')->get();
return view('user/aktuelles.index', ['datanews' => $datanews,'dataevent'=> $dataevent,'users'=>$user]);
Now, You will get result inside your view using 'users'.

You are not passing variables to view correctly use with or compact to pass variables to view.
i prefer compact as it is simple and easier.
Passing data to view using compact:
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$datanews = News::orderBy('created_at','desc')->get();
$dataevent = Event::orderBy('created_at','desc')->get();
$user = User::all();
return view('user.aktuelles.index',compact('datanews', 'dataevent','user'));
}
Passing variables to view using with:
public function index()
{
$datanews = News::orderBy('created_at','desc')->get();
$dataevent = Event::orderBy('created_at','desc')->get();
$user = User::all();
return view('user.aktuelles.index)->with(['datanews' => $datanews,'dataevent'=> $dataevent,'users'=>$user]);
}

You should try this:
use Illuminate\Support\Facades\DB;
use App\News;
use App\User;
use App\Event;
public function index()
{
$data['news'] = News::orderBy('created_at','desc')->get();
$data['events'] = Event::orderBy('created_at','desc')->get();
$data['users'] = User::all();
return view('user/aktuelles.index', $data);
}

Related

Laravel How to get Route Profile based on Route Name

I have this route:
Route::get('/test',['as'=>'test','custom_key'=>'custom_value','uses'=>'TestController#index'])
I've been tried to use $routeProfile=route('test');
But the result is returned url string http://domain.app/test
I need ['as'=>'test','custom_key'=>'custom_value'] so that I can get the $routeProfile['custom_key']
How can I get 'custom_value' based on route name ?
For fastest way, now I use this for my question:
function routeProfile($routeName)
{
$routes = Route::getRoutes();
foreach ($routes as $route) {
$action = $route->getAction();
if (!empty($action['as']) && $routeName == $action['as']) {
$action['methods'] = $route->methods();
$action['parameters'] = $route->parameters();
$action['parametersNames'] = $route->parametersNames();
return $action;
}
}
}
If there's any better answer, I will be appreciate it.
Thanks...
Try this:
use Illuminate\Support\Facades\Route;
$customKey = Route::current()->getAction()['custom_key'];
I believe you are looking for a way to pass variable to your route
Route::get('/test/{custom_key}',[
'uses'=>'TestController#index',
'as'=>'test'
]);
You could generate a valid URL like so using
route('test',['custom_key'=>'custom_key_vale'])
In your view:
<a href="{route('test',['custom_key'=>'custom_key_vale'])}"
In your controller method:
....
public function test(Request $request)
{
$custom_key = $request->custom_key;
}
....
You can try one of the below code:
1. Add use Illuminate\Http\Request; after namespace line code
public function welcome(Request $request)
{
$request->route()->getAction()['custom_key'];
}
2. OR with a facade
Add use Route; after namespace line code
and use below into your method
public function welcome()
{
Route::getCurrentRoute()->getAction()['custom_key'];
}
Both are tested and working fine!

Laravel API APP Many-Many Relationship, how to return specific information in JSON?

I been trying to figure this out for some time now. Basically i got 2 models ' Recipe ', ' Ingredient ' and one Controller ' RecipeController ' .
I'm using Postman to test my API. When i go to my get route which uses RecipeController#getRecipe, the return value is as per the pic below:
Return for Get Route
If i want the return value of the get route to be in the FORMAT of the below pic, how do i achieve this? By this i mean i don't want to see for the recipes: the created_at column, updated_at column and for ingredients: the pivot information column, only want name and amount column information.
Return Value Format I Want
Recipe model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Recipe extends Model
{
protected $fillable = ['name', 'description'];
public function ingredients()
{
return $this->belongsToMany(Ingredient::class,
'ingredient_recipes')->select(array('name', 'amount'));
}
}
Ingredient Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Ingredient extends Model
{
protected $fillable = ['name', 'amount'];
}
RecipeController
<?php
namespace App\Http\Controllers;
use App\Ingredient;
use App\Recipe;
use Illuminate\Http\Request;
class RecipeController extends Controller {
public function postRecipe(Request $request)
{
$recipe = new Recipe();
$recipe->name = $request->input('name');
$recipe->description = $request->input('description');
$recipe->save();
$array_ingredients = $request->input('ingredients');
foreach ($array_ingredients as $array_ingredient) {
$ingredient = new Ingredient();
$ingredient->name = $array_ingredient['ingredient_name'];
$ingredient->amount = $array_ingredient['ingredient_amount'];
$ingredient->save();
$recipe->ingredients()->attach($ingredient->id);
}
return response()->json(['recipe' => $recipe . $ingredient], 201);
}
public function getRecipe()
{
$recipes = Recipe::all();
foreach ($recipes as $recipe) {
$recipe = $recipe->ingredients;
}
$response = [
'recipes' => $recipes
];
return response()->json($response, 200);
}
API Routes:
Route::post('/recipe', 'RecipeController#postRecipe')->name('get_recipe');
Route::get('/recipe', 'RecipeController#getRecipe')->name('post_recipe');
Thanks Guys!
I think your best solution is using Transformer. Using your current implementation what I would recommend is fetching only the needed field in your loop, i.e:
foreach ($recipes as $recipe) {
$recipe = $recipe->ingredients->only(['ingredient_name', 'ingredient_amount']);
}
While the above might work, yet there is an issue with your current implementation because there will be tons of iteration/loop polling the database, I would recommend eager loading the relation instead.
But for the sake of this question, you only need Transformer.
Install transformer using composer composer require league/fractal Then you can create a directory called Transformers under the app directory.
Then create a class called RecipesTransformer, and initialize with:
namespace App\Transformers;
use App\Recipe;
use League\Fractal\TransformerAbstract;
class RecipesTransformer extends TransformerAbstract
{
public function transform(Recipe $recipe)
{
return [
'name' => $recipe->name,
'description' => $recipe->description,
'ingredients' =>
$recipe->ingredients->get(['ingredient_name', 'ingredient_amount'])->toArray()
];
}
}
Then you can use this transformer in your controller method like this:
use App\Transformers\RecipesTransformer;
......
public function getRecipe()
{
return $this->collection(Recipe::all(), new RecipesTransformer);
//or if you need to get one
return $this->item(Recipe::first(), new RecipesTransformer);
}
You can refer to a good tutorial like this for more inspiration, or simply go to Fractal's page for details.
Update
In order to get Fractal collection working since the example I gave would work if you have Dingo API in your project, you can manually create it this way:
public function getRecipe()
{
$fractal = app()->make('League\Fractal\Manager');
$resource = new \League\Fractal\Resource\Collection(Recipe::all(), new RecipesTransformer);
return response()->json(
$fractal->createData($resource)->toArray());
}
In case you want to make an Item instead of collection, then you can have new \League\Fractal\Resource\Item instead. I would recommend you either have Dingo API installed or you can follow this simple tutorial in order to have in more handled neatly without unnecessary repeatition

Create a route that has uri-segment

I tried to call a function on the controller and the function I have created a route, but how to create a route that has uri-> segement ?
Example
$route['select-item'] = 'select_item';
Controllers
function select_item() {
$item = $this->uri->segment(3);
$data = array ('get_item' => $this->Model->My_item($item));
$this->load->view('Myview');
}
Views
<?php echo $row->item;?>
I suggest you use codeigniters wildcards on routes, You can go ahead and set your route to:
$route['select-item/(:any)'] = 'select_item/$1';
then on your controller, just do:
function select_item($item) {
$data = array ('get_item' => $this->Model->My_item($item));
$this->load->view('Myview',$data);
}
And the link in your view should work properly.

why method post not found in Illuminate\support\facade\input

I work with laravael 5.3.9 .
In my controller I use
Illuminate\Support\Facades\Input;
But when I try to get input from a user form using method post like that :
function add(){
$fullName = Input::post('fullName' , 'test');
I get this error .
the only method that Input class has is "get" .
I dont want that in my system I want to work with method post , delete , put ....
I guess, Input::post method is not used with L5.3. Use the Request facade OR $request to get your input variable.
Try this in your controller
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class area_owners extends Controller
{
function add(Request $request)
{
// I assume all these input variable have same name in you FORM.
$fullName = $request->input('fullName');
$smsCode = $request->input('smsCode');
$authorizationId = $request->input('authorizationId');
$areaNumber‌​ = $request->input('areaNumber‌​');
$neigh_project_Id = $request->input('neigh_project_Id');
$area_owners = DB::table('area_owners')
->insert(['fullName'=>$fullName,
'smsCode'=>$smsCode,
'authorizationId'=>$authorizationId,
'are‌​aNumer'=>$areaNumber‌​,
'neigh_project_Id'=‌​>$neigh_project_Id])‌​;
return view('area_owners_add', ['area_owners' => $area_owners]);
}
}
Let me know if it helps.

How to use session_data in codeigniter throughout Website without including in particular view

Is there any other best way to use session_data in website.
How i set session in my project:
$sess_array = array('id' => $row->user_id,'name'=>$row->user_name,'email'=>$row->email,'condition'=>'','balance'=>$row->balance,'did_alloted'=>$row->did_alloted,'create_date'=>$row->create_date);
$this->session->set_userdata('logged_in', $sess_array);
when it comes to controller:
$data['id'] = $session_data['id'];
$data['name'] = $session_data['name'];
$data['email'] = $session_data['email'];
$data['balance']=$session_data['balance'];
$data['did_alloted']=$session_data['did_alloted'];
$data['create_date']=$session_data['create_date'];
$this->load->view('san-reception', $data);
and in my view. I use <?php echo $name ?> to get session_data.
So is there any method by which i can directly access session_data in view without including as $data.
$this->session->userdata('logged_in'); will be available directly in views and hence you just need to assigned this to a variable and then use that as array like bellow.
$userdata=$this->session->userdata('logged_in');
now variable $userdata contain all array field that you set in controller and hence you can use it as $userdata['id'], $userdata['name'] etc
public function __construct()
{
parent::__construct();
$data['session_data']=$this->session->user_data('logged_in');
}
public function some_function(){
$data['dummy']="";
$this->load->view('someview3',$data)
}
public function some_function1(){
$data['dummy']="";
$this->load->view('someview1',$data)
}
public function some_function2(){
$data['dummy']="";
$this->load->view('someview2',$data)
}
If you assign that into the constructor then it will call by automatically whenever a function calls in the controller.
you can view it in you view page by,
print_r($session_data);

Resources