Khubab
Khubab

Reputation: 21

How to pass data from two different controller to single view in laravel5

I am new to Laravel5. There are two controllers Dashboard.php and Stats.php. I want to pass variables from both controllers to my single view DashBoard.blade.php Guide me is this possible and also guide me the about the route of project.

here is my routing code:

` Route::get('/', function () { return view('welcome'); });

Auth::routes();

Route::get('/home', 'HomeController@index')->name('home');

Route::get('/DashBoard', 'DashBoard@ratingdata')->name('DashBoard');

Route::get('/Stats', 'Stats@statsdata')->name('Stats'); `

It works when views are different. but i need data on single view

Upvotes: 0

Views: 1538

Answers (2)

Pedro Alves
Pedro Alves

Reputation: 96

About the routes, you can use the resources routing, it will create all your basic routes. Check this out (https://laravel.com/docs/5.8/controllers#resource-controllers)

A example of that, would be:

Route::resource('/dashboard', 'DashboardController');
Route::resource('/stats', 'StatsController');

To display data of multiple models in a view all you need to do is declare the model in the beggining of your controller.

Example:

<?php

namespace App\Http\Controllers;
use App\Stats;
use Auth;
use Illuminate\Http\Request;

class DashboardController extends Controller
{
/**
 * Display a listing of the resource.
 *
 * @return \Illuminate\Http\Response
 */
public function index()
{
    $stats = Stats::all();
    $dashboard = Dashboard::all();

    return view('the_view_you_wanna_show', compact('stats', 'dashboard'));
}

Then, all you need to do now, is go to your view and display your data.

Example:

<h1>Displaying the names of my dashboard</h1>
@foreach($dashboard as $names)
 {{$names->name}}
@endforeach

<h1>Displaying the stats name</h1>
@foreach($stats as $stats_names)
 {{$stats_names->name}}
@endforeach

Tip: When you create your models, go to your prompt and type:

php artisan make:model NameOfYourModel -a

It will create all the things you need to manipulate this model.

Upvotes: 1

Sachin Vairagi
Sachin Vairagi

Reputation: 5334

Below is the example of get route to fetch user data and display in view -

Route

  Route::get('edit_profile', 'AdminController@editProfile');

In AdminController

public function  editProfile(){
        $data['title'] = 'Edit Profile';
        $data['profile_info'] = Admin::where('id',1)->first();

        return view("Admin::layout.edit_profile", $data);
    }

You can print profile info in view as -

{{$profile_info->name}}

Upvotes: 0

Related Questions