laravel user list with posts and profile links - php

I try to get list of all users with post and link them to different page where all their posts is listed.
Obviously I must make my list page first then my users detail page, but some how I ended up with detail page and no list page :)))
Anyway: this is what I have so far:
Controller
public function chef() {
//
return view('front.chef');
}
public function chefdetail($username) {
$foods = Food::whereHas('user', function($q) use($username){
$q->where('username',$username);
})->get();
return view('front.chef-detail', compact('foods'));
}
My routes:
Route::get('/chef/{username}', 'FrontendController#chefdetail')->name('chefdetail');
Route::get('/chefs', 'FrontendController#chef')->name('chefs');
Questions (Problems) :
How do I get list of users with posts in my chef function?
How do I add username to my chefs detail page URL
Is it correct that I used $user = User::find(1); to getting users list? because I couldn't get users by id it returns error.

With this code you pass all your users that have posts to your blade page
public function chef() {
$users = User::has('posts')->get();
return view('front.chef', compact("users"));
}
In your blade you can show them like:
#foreach ($users as $user) {
{{ $user->username }}
#endforeach
then your chefdetail function should look like this:
public function chefdetail($username) {
$user = User::where("username", $username)->with("posts")->first();
return view('front.chef-detail', compact('user'));
}
and you can show the post like this:
#foreach ($user->posts as $post) {
$post->someproperty
#endforeach
hope this helps you.

Related

How to select an id in route pass it into the controller and fetch data against that id and redirect it view again in laravel 5.6

How to pass id from veiw into controller in then into another view again??
First of all this a basic question you should be able to search it anywhere on the internet. any how below is the solution.
web/routes.php:
Route::get('user/{id}','USerController#find')->name('user.get');
Or by passing user object in the route:
Route::get('user/{user}','USerController#find')->name('user.get');
UserController:
the below function accepts user object as a parameter in the route we defined above.
public function find(user $user)
{
return view('user.detail',compact('user'))
}
or
public function find($id)
{
$user = USer::find($id);
return view('user.detail',compact('user'))
}
resources/view/user/detail.blade.php:
{{ $user -> name }}
{{ $user -> email }}
and in order visit the route user.find use the below line:
View Detail
No you can use this code as reference to your project.
first solution is .
change route
Route::get('/show_vedio/{$id}', 'VedioController#show')->name(show_videos);
and use this {{ route('show_vedios', $vedio->id )}} in href
it's not entirely clear what you are trying to do, maybe i will help you:
public function show(int $id): View
{
$video = Video::find($id);
return view('video.show', ['video' => $video]);
}

How do I fetch data based on user id using Laravel 5.4

I have models User and Diares set up with the hasMany and BelongTo relstionship. I'm trying to fetch data from the Diaries table associated with a particular user. I tried auth but it didnt work for me. How can i achieve that and display it in the blade view as well. Here is my current code:
public function index(User $id)
{
$user = User::find($id);
$record = $user->diary;
return view('home')->with('record', $record);
}
The blade file it should display to:
#foreach ($record as $diary)
{{ $diary->error }}
{{ $diary->fix }}
#endforeach
In your index function the $id is not integer - this is a User instance, so you can try use this:
public function index(User $user)
{
$record = $user->diary;
return view('home')->with('record', $record);
}

How to pass variable from foreach to view?

I'm trying to pass a variable from foreach to my view. So I can access this using in my select form. Because I have two tables M:M relationship between departments and user. I need to get all the department_name where the user_id belong. For me able to send a data via department_name Here what I did please take a look.
DB Diagram:
department_user
As you can see here user_id is the id of the user and document_id is where the users belong.
Model:
Department:
public function users()
{
return $this->belongsToMany('\App\Models\User', 'department_user');
}
User:
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Controller:
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
foreach ($departmentRecipient as $department)
{
$department->users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
}
return view('document.create')->with('department', $department);
}
I'm getting all the users_id when I die and dump my variable departmentRecipient.
View:
<div class = "form-group">
<label for = "recipient" class = "control-label">Recipient:</label>
<select name = "recipient[]" multiple class = "form-control select2-multi" id = "myUserList">
#foreach ($department as $list)
<option value = "{{ $list->user_id }}">{{ $list->department_name }}</option>
#endforeach
</select>
</div>
I wanted to foreach the $department in my Controller to my select form. But it always says.
Trying to get property of non-object (View: C:\Users\JohnFrancis\LaravelFrancis\resources\views\document\create.blade.php)
Goal:
Use the following loop to iterate through the department users and add them to pivot table.
foreach($request->department as $departmentId)
{
foreach(Department::find($departmentId->id)->users()->get() as $user1) //find the users belonging to the current department
{
$document->sentToUsers()->sync([ $user1->id => ['sender_id' => $user->id]],false );
}
}
Also remove the following code form your getDocuments() as it is redundant:
foreach ($departmentRecipient as $department)
{
$department->users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
}
I don't see user_id property in your dumped value of $departmentRecipient object, that is why you are getting the error you mentioned. However, there is a users array inside of $departmentRecipient object, which you made inside your foreach loop. You are plucking every user_id which are in individual department and setting in a property named users of $departmentRecipient object, and so you are getting an array inside users property. Here I have a solution for you,
public function getDocuments()
{
$departmentRecipient = DB::table('departments')->get();
$departmentUsers = array();
foreach ($departmentRecipient as $department)
{
$users = DB::table('department_user')
->where('department_id', '=', $department->id)
->pluck('user_id');
foreach ($users as $userId) {
$departmentUsers[$userId] = $department->department_name;
}
}
return view('document.create')->with('department', $department)->with('departmentUsers', $departmentUsers);
}
and inside of your view loop through the variable $departmentUsers, like this,
#foreach ($departmentUsers as $userId => $departmentName)
<option value = "{{ $userId }}">{{ $departmentName }}</option>
#endforeach
This will work but as your department contains multiple users so you will get individual department name multiple time in your select2 dropdown. If you share more of what is your goal by select2 then may be I can help you to solve your problem in other way.
Moreover if you are interested to use of Eloquent then you can get rid of lots of foreach looping.
In your case you can have multiple users against each department. So to make it work correctly with your forearch code. You need to make sure you are getting one user record against each depart. So modify following line of code in controller.
$department->users = DB::table('department_user')->where('department_id', '=', $department->id)->pluck('user_id');
But you want to display all users of department then you have to change foreach loop code into view.
Try This Code
App/Department
public function users()
{
return $this->belongsToMany('App\Entities\User', 'department_user', 'user_id', 'department_id');
}
App/User
public function departments()
{
return $this->belongsToMany('App\Models\Department', 'department_user');
}
Controller
use App/User;
public function getDocuments($userId,User $User)
{
$getSpecificUser = $User->with('departments')->find($userid);
return view('document.create')->compact('getSpecificUser');
}
View
#foreach ($getSpecificUser as $getUser)
#if(empty($getUser->departments) === false)
#foreach ($getUser->departments as $departments)
<option value = "{{ $getUser->id }}">{{ $departments->department_name }}</option>
#endforeach
#endif
#endforeach

Dyanmic url in laravel

I am a beginner in laravel so please excuse me if this is a simple question
I am trying to pass a db variable through my url so e.g blog?=category
It displays all results but when i change the url to blog/category1 it doesn't display anything.
DB Fields:id,category, name
1 category1 test
This is in my routes:
Route::get( '/blog', 'BlogController#index' );
Route::get('/', 'HomeController#index');
Route::get('blog/{category}', function($category = null)
{
// get all the blog stuff from database
// if a category was passed, use that
// if no category, get all posts
if ($category)
$posts = Post::where('category', '=', $category);
else
$posts = Post::all();
// show the view with blog posts (app/views/blog.blade.php)
return View::make('blog.index')
->with('posts', $posts);
});
BlogController
class BlogController extends BaseController {
public function index()
{
// get the posts from the database by asking the Active Record for "all"
$posts = Post::all();
// and create a view which we return - note dot syntax to go into folder
return View::make('blog.index', array('posts' => $posts));
}
}
This is my view layout:
#extends('base')
#section('content')
#foreach ($posts as $post)
<h2>{{ $post->id }}</h2>
<p>{{ $post->name }}</p>
#endforeach
#stop
Thanks
You need to add ->get() after your Eloquent query to fetch the results.
Route::get('blog/{category}', function($category = null)
{
// get all the blog stuff from database
// if a category was passed, use that
// if no category, get all posts
if ($category)
$posts = Post::where('category', '=', $category)->get();
else
$posts = Post::all();
// show the view with blog posts (app/views/blog.blade.php)
return View::make('blog.index')->with('posts', $posts);
});

How to store homepage in cache in laravel 4

I am new in laravel and php. I am developing a magazine site with laravel 4. I want to store home page in laravel cache . But In my homepage , there are many queries . Please see details below.:
My HomepageController index method:
public function index()
{
return View::make('homepage');
}
My Query Helper Function which is used for post by category in my Homepage:
public static function cat_post($category, $limit)
{
$posts = Post::whereHas('categories', function($q) use ($category)
{
$q->where('category_slug', 'like', $category);
})->with('categories')->take($limit)->orderBy('created_at', 'DESC')->get();
return $posts;
}
In My homepage.blade.php , I used this helper function many times. like below:
<?php $national = Helper::cat_post('national', 3); ?>
#foreach ($national as $post)
{{ Helper::img_src($post) }}
<h4>{{ $post->title }}</h4>
</div>
#endforeach
Now i want to put homepage in cache and when new post created, then delete old homepage from cache and store new one.
Please help me. Is it possible ?????
To store a value in cache you can use Laravel's Cache:
public function index()
{
return Cache::rememberForever('homepageCache', function()
{
return View::make('homepage');
});
}
This snipped tries to retrieve a cached version of View::make('homepage') and otherwise creates it.
Every time a post is created, updated or deleted you need to invalide your homepageCache:
Cache::forget('homepageCache');

Categories