Getting the database data to front view in laravel? - laravel

As it is quite easy to get data from database in admin panel,but the case is that how can i get/view those data to front view , front view contains the data from several table. Could you please help me ? How can i manage those front pages easily ?

There are a lot of ways, but this is what I normally do.
Use a separate controller method (say index() HomeController) for the frontpage, and create an array of all the variables with the data from database and pass it on to the page. Let's say our homepage has some slider images, some blog posts, and and our team section, then your HomeController would look something like this:
class HomeController extends Controller
{
public function index()
{
$data = []; //your empty array
$data['sliders'] = Slider::all(); //data from sliders table
$data['posts'] = Post::all(); //data from posts table
$data['teams'] = Team::all(); //data from teams table
return view('frontend.index',compact('data'));
}
Now you can access all these in your frontend blade (here index.blade.php) as such:
#foreach($data['teams'] as $key=> $value)
//your loop code
#endforeach
Hope this helps.

In the wonderfull world of laravel this is super easy. But first let me dive a into the structure of laravel a bit.
It all begins with the controller. In Laravel, Controllers a re meant to group assiociated request handling logic within a single class. A basic resource controller would look like this:
class DomainController extends Controller
{
public function index(){} // list domains
public function create(){} // show create form
public function store(Request $request){ } // handle the form POST
public function show($id){} // show a single domain
public function edit($id){} // show edit page
public function update(Request $request, $id){} // handle show edit page POST
public function destroy($id){} // delete a domain
}
Now how can you return the data to the view?
Let's say we want to generate a list of all users using the index function from the controller.
public function index()
{
$users = User::all();
return view('users.index', compact('users'));
}
With this return statement we will get a view and in that view we will have the $users variable available because of the use of the comapct function.
Now if we want to show a simple list:
#foreach($users as $user)
<li>{{$user->name}}</li>
<li>{{$user->age}}</li>
#endforeach

Related

Please how do I share data from show method to two different views

Please I need to know if there is a way I can share data from one controller method to multiple views,
This is the CategoryController show method
/**
* Display the specified resource.
*
* #param int $id
* #return \Illuminate\Http\Response
*/
public function show($id)
{
$category = Category::find($id);
$users = $category->user;
return view('categories.show')->with('users', $users);
}
what I want is to share the same data with another page profile-display.blade.php without creating another controller.
#Adam this will help you.
route.php
Route::get('users/{id}', 'CategoryController#show')->name('profile');
Route::get('Category/{id}', 'CategoryController#show')->name('category');
CategoryController.php
public
function show($request, $id) {
$category = Category::find($id);
$users = $category->user;
if ($request::route()->getName() == 'category') {
return view('categories.show')->with('users', $users);
} else {
return view('profile.show')->with('users', $users);
}
}
Different routes can use the same controller, but you are going to have a harder time having a single controller present multiple views without a chaos of conditions or at least just make a new controller/method.
You can shave of some of your of your code to make a slimmer approach, though, by using model binding with routes:
routes.php
Route::get('categories/{category}', 'CategoryController#show');
and then in CategoryController.php:
public function show(Category $category)
{
return view('categories.show')->with('users', $category->user);
}
This will enable model binding to auto-instantiate the model if it exists and return a 404 if not.
You can reiterate the process for a second view, but just reuse the same controller (which I personally wouldn't prefer at all). Just add the route and the new method in the same controller:
routes.php
Route::get('categories/{category}', 'CategoryController#show');
Route::get('profile-display', 'CategoryController#profileDisplay');
and then in CategoryController.php:
public function show(Category $category)
{
return view('categories.show')->with('users', $category->user);
}
public function profileDisplay()
{
return view('profile-display');
}
I haven't added any model bindings to the profileDisplaymethod as I couldn't really understand how you would like to attache the category to a profile display page (as the name suggests), but that could give you some rough ideas.
you can use \Illuminate\Support\Facades\View::share('foo', 'bar');

In which Controller should I write logic for Models that are in a relationship

I am making a blog with users who each have posts. Naturally, I have a UserController, PostController, and a User and Post model.
The User model has a one-to-many relationship with the Post model like so
// User Model
public function posts()
{
return $this->hasMany('App\Post');
}
I would like to get all the posts of a specific user by using
// UserController or PostController...
$posts = User::find($id)->posts()->get()
Should I write this logic in my UserController (because it uses the User model) or should I write the logic in my PostController (because it returns posts)?
Actually, you just need to create the relationship as you did, and then you will be able call it wherever you want, just like as you described, with User::find($id)->posts()->get().
So, if you need to return a user's post on a view, for instance, you can do something like that on your UserController:
public function postsView(User $user)
{
$posts = $user->posts()->get();
return view('user.posts', compact('posts'));
}
Also, if you want the other way around (to know who is the user behind the post), you can create a relationship on your Post model using belongsTo().
// Post Model
public function user()
{
return $this->belongsTo('App\User');
}
You can write the query anywhere in UserController or PostController
$user = User::with('posts')->whereId($id)->first();
echo '<pre>';
print_r($user->toArray());
exit;
You'll get user with all posts
In your Model User put the relationship.
public function posts()
{
return $this->hasMany('App\Post','foreign_key','local_key');
}
In your UserController or PostController get the results by using
$posts = User::find($id);
foreach($posts->posts as $post)
{
echo $post->title;
}
You can query from both controllers. From where you want to query the relationship depends on where and how you want to fetch data from.
For example, if you are showing posts related to user on a user profile page with other bio data etc then you will call the relationship in UserController.
On other hand, let's say you want to show posts related to an author on a search page then it will be better to have the posts queried via relationship in PostController.
In short, it's a choice based on convenience and optimization to be made.

Navigation bar with categories (and subcategories)

I need your help. I new in Laravel.
I want to get all categories and subcategories into my navigation bar so on every page. I have a Category model. How to get all categories? Can I just using something like
Category::all()->get() etc.
in my layout, is it right to call from the layout?
You should use view composers to pass a variable to all pages. First create a view composer in App\View\Composer;
namespace App\View\Composers;
use App\Category;
use Illuminate\View\View;
class InjectCategory
{
protected $categories;
public function __construct(Category $categories)
{
$this->categories= $categories;
}
public function compose(View $view)
{
$categories= $this->categories->all();
$view->with('categories',$categories);
}
}
Then you should add the view composer to the AppServiceProvider's boot method.
public function boot(Request $request)
{
$this->app['view']->composer(['includes.frontend.menu'], Composers\InjectCategory::class);
}
Now you can use the $categories values from your menu.blade.php and include it to top of any page you want to show navigation.
Some how when i was working on a Blog Project i also had the same issue which i solved by sharing the data with all views which is quite easy and simple way.
in your app/Provider/AppServiceProvider.php file in boot Method add below code:
public function boot()
{
$categories = Category::all();
view()->share('categories', $categories);
}
and now you can access $categories in every view for more detail info visit this link.

handling models in laravel 5 like in codeigniter

I'm new on laravel.
I have functions on my model php. I want to use them in controller and send to view.
This is my example function.
public function select()
{
$users = DB::table('user')->get();
}
now I need to use this on controller and view.
In codeigniter I handle it like this:
$data['content'] = $this->model->select();
$this->load->view('admin/users', $data);
in codeigniter we first load model then we call its one of its method and then we pass processed data to view . what is counter part of this in laravel 5
In Laravel 5 you can do it only using controller, like this:
public function select()
{
$users = DB::table('user')->get();
return view('admin.users',compact('users'));
}
if you want do it using Eloquent Model you need a model first. I assume you model name is User and your table name is users
User.php
protected $table = 'users'; // mention the table name
UserController.PHP
public function select()
{
$users = User::all(); // it will return a collection of data form User model
return view('admin.users',compact('users')); // write all variables you want pass through inside compact separated with comma
}

Passing the same data over different views in Laravel

I have for example this code in my HomeController:
public function index() {
$comments = Comment::get_recent();
$top = User::get_top_uploaders()->get();
$top_something = User::get_top_something_uploaders()->get();
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
return View::make('index') ->with('data', $data)
->with('comments', $comments)
->with('top', $top)
->with('top_something', $top_something);
}
It works great, but I need to make another couple of view with the same data not only for index but also for other pages like comments(), post()...
How to make this in HomeController that I don't need to make it copy and paste those variables in every controller?
Pass your data using share method:
// for single controller:
class SomeController extends BaseController {
public function __construct()
{
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
View::share('data', $data);
}
}
For all controllers you can put this code in BaseController's constructor
If the data is displayed using the same HTML each time you could put that piece of HTML into a partial and then use a View Composer.
Create a view and call it whatever you want and put in your HTML for the data.
In templates that need that partial include it #include('your.partial')
In either app/routes.php or even better app/composers.php (don't forget to autoload it)
View::Composer('your.partial', function($view)
{
$data = Post::orderBy('created_at', 'DESC')->paginate(6);
$view->with('data', $data);
});
Now whenever that partial is included in one of your templates it will have access to your data

Resources