I am trying to save users to a followers table when one user follows another. When I try to get one user to follow another I get
Call to a member function follow() on integer
whenever I try to follow another user.
Follow Button/Form
{!! Form::open(['route' => 'follow_user']) !!}
{!! Form::hidden('id', $user->id) !!}
<button type="submit" class="btn btn-primary">Follow {{$user->name}}</button>
{!! Form::close() !!}
Route
Route::post('/follow', [
'as' => 'follow_user', 'uses' => 'FollowersController#store'
]);
Followers Controller
public function store()
{
$user1 = Auth::user()->id;
$user2 = Input::get('id');
$user1->follow($user2);
return redirect()->action('HomeController#index');
}
Methods I am using in User model
function followers()
{
return $this->belongsToMany('App\User', 'followers', 'user_id', 'follower_id');
}
function follow(User $user) {
$this->followers()->attach($user->id);
}
function unfollow(User $user) {
$this->followers()->detach($user->id);
}
You're trying to run follow() on a ID, not the User object (as you probably want).
This returns an integer:
$user1 = Auth::user()->id;
Maybe you want something like this:
$user1 = Auth::user();
$user2 = Input::get('id');
$user1->follow(User::find($user2));
Thanks to #blackpla9ue for the fix.
Related
I need to search records by creation date in Laravel
my User Model
public function scopeCreate_at($query, $created_at){
if($created_at)
return $query->whereRaw('created_at', 'LIKE', "%$created_at%");
}
My UserController
class UserController extends Controller
{
public function index(Request $request){
$name = $request->get('name');
$email = $request->get('email');
$bio = $request->get('bio');
$created_at = $request->get('created_at');
$users = User::orderBy('id', 'DESC')
->name($name)
->email($email)
->bio($bio)
->created_at($created_at)
->paginate(10);
return view('user', compact('users'));
}
The view
<div class="form-group">
{ Form::date('created_at', null, ['class' => 'form-control', 'placeholder' => 'Creacion'])}}
</div>
But, when I reload the page, I have this
BadMethodCallException
Method Illuminate\Database\Query\Builder::created_at does not exist.
The others methods works very well
'created_at' !== 'create_at'
scopeCreate_at
Update:
public function scopeCreate_at
scopeCreate_at
Update:
...Create_at
Update:
lagbox hands the OP the letter 'd' and says, "You dropped this"
But seriously, you can name the function scopeCreated_at or call the scope by what you named it create_at to resolve that issue.
I'm trying to connect companies that are used by specific user role. A user with a specific role can "work" for multiple companies. A company can "employ" multiple users. I have 5 tables (users, role_user, roles, companies and company_user)
Models relations:
App\User:
public function roles()
{
return $this
->belongsToMany('App\Role')
->withTimestamps();
}
public function companies()
{
return $this
->belongsToMany('App\Company')
->withTimestamps();
}
App\Role:
public function users()
{
return $this
->belongsToMany('App\User')
->withTimestamps();
}
App\Companies:
public function users()
{
return $this->belongsToMany('App\User'); // with user_role ??
}
Companies Controller
public function edit(Request $request, $id) {
$company = Company::findOrFail($id);
$users = User::where('role_id',4)->pluck('username')->all(); // no role_id column
$users = User::pluck('username','id')->all(); // returns all users
return view('companies.edit', compact(['company','users']));
}
public function update(Request $request, $id) {
/* TODO */
}
Edit view
{!! Form::select('users[]', $users, null, ['class' => 'form-control', 'multiple' => 'multiple']) !!}
I want to asign users whith a specific user role to these companies. Is there a way to setup the relation or perhaps a scope?
Bonus question :) Is there a simple way to display concatinated value in a dropdown? First name + Last name instead of username?
Perhaps not the tidiest solution but it seems to work :)
Model
public function scopeOfRole($query, $role) {
return $query->
join('role_user', 'role_user.user_id', '=', 'users.id')->
join('roles', 'roles.id', '=', 'role_user.role_id')->
select(
DB::raw('GROUP_CONCAT(users.first_name," ",users.last_name) as username'),
'users.id')->
where('roles.name', $role)->
groupBy('users.id');
}
Controler
public function edit(Request $request, $id) {
$company = Company::findOrFail($id);
$users = User::OfRole('my role')->pluck('username','users.id')->all();
return view('companies.edit', compact(['company','users']));
}
edit view
{!! Form::select('users[]', $users, $company->users()->pluck('users.id'), ['class' => 'form-control', 'multiple' => 'multiple']) !!}
I am trying to execute 2 queries at the same time on the same function on my application. This function on the controller registers a new house in the system and at the same time, its suppose to feed a field in the Users table that has been null, and this field will then be updated with the new id of the house i have just created. For some reason, the first query works fine but i have been struggling with the second. I believe my logical is fine, maybe the Laravel syntax is making me a bit confused. Can someone help me?
This is my controller
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\House;
use App\User;
class AdminHouseController extends Controller
{
public function index(){
}
public function create($role_id){
if($role_id == 1){
return view('admin.house.create');
}else{
return redirect('home');
}
}
public function store(Request $request){
House::create($request->all());
$house_admin = Auth::user()->id;
$house = House::where('house_admin', $house_admin)->first();
User::findOrFail($house_admin)->update(['house_id' => $house->id]);
return redirect('home');
}
public function show($id){
}
public function edit($id){
}
public function update(Request $request, $id){
}
public function destroy($id){
}
}
This is my form
//i believe the problem is not here, but anyway
#extends('layouts.app')
#section('content')
<p><b>Register your house</b></p>
{!! Form::open(['method'=>'post', 'action'=>'AdminHouseController#store']) !!}
{!! Form::text('house_address', null,['placeholder'=>'House Address']) !!}
<input type="hidden" name="house_admin" value="{{Auth::user()->id}}">
{!! Form::number('nflatmates', null, ['placeholder'=>'How many flatmates']) !!}
{!! Form::submit('Register', ['class'=>'ui-btn buttonDefault']) !!}
{!! Form::close() !!}
#stop
And finnaly, this my router web.php
//i also believe the problem is not here, but in my controller
use App\User;
Route::get('/', function () {
return view('welcome');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/house/{role_id}', 'AdminHouseController#create')->name('house');
Route::post('store', [
'uses' => 'AdminHouseController#store'
]);
You need to add the house_id field to the $fillable array in the User model:
protected $fillable = ['house_id', 'other_fields'];
Also, you have two foreign keys instead of one which is redundant. You might want to keep only house_admin foreign key.
I'm looking for some help. I've searched on other topics, and saw what is the problem approximatively, but didn't succeed to fix it on my code.
Now the question is: I have NotFoundHttpException when i try to submit an update on my code.
Here is the Controller and my function update
<?php
namespace App\Http\Controllers;
use Request;
use App\Http\Requests;
use App\T_collaborateurs_table;
class testing extends Controller
{
public function index()
{
$user = T_collaborateurs_table::all();
return view ("read", compact("user"));
}
public function create()
{
return view("create");
}
public function store(Request $Request)
{
T_collaborateurs_table::create(Request::all());
return redirect("index");
}
public function show($id)
{
$user=T_collaborateurs_table::find($id);
return view("show", compact("user"));
}
public function edit($id)
{
$user=T_collaborateurs_table::find($id);
return view("update", compact("user"));
}
public function update(Request $Request, $id)
{
$user = T_collaborateurs_table::find($id);
$user->update(Request::all());
return redirect("index");
}
}
Now the routes
Route::get("create", "testing#create");
Route::post("store", "testing#store");
Route::get("index", "testing#index");
Route::get("show/{id}", "testing#show");
Route::get("edit/{id}", "testing#edit");
Route::patch("update/{id}", "testing#update");
And now the view update.blade.php
<body>
{{Form::model($user, ['method'=>'patch', 'action'=>['testing#update',$user->id]])}}
{{Form::label('Id_TCa', 'ID')}}
{{Form::text('Id_TCa')}}
{{Form::label('Collaborateur_TCa', 'collab')}}
{{Form::text('Collaborateur_TCa')}}
{{Form::label('Responsable_TCa', 'resp')}}
{{Form::text('Responsable_TCa')}}
{{Form::submit("update")}}
{{Form::close()}}
</body>
Here the route:list
I'm sorry if my words are not very understable...
Thank you all for your time.
{{Form::model($user, ['method'=>'PATCH', 'action'=> ['testing#update',$user->id]])}}
Or try to use 'route' instead of 'action',to use 'route' you just need a little edit in your update route.
Route::patch("update/{id}", array('as' => 'task-update', 'uses'=>'testing#update'));
in your view:
{{Form::model($user, ['method'=>'PATCH', 'route'=>['task-update',$user->id]])}}
And please follow the convention of class naming. Your class name should be 'TestingController' or 'Testing'.
You could try method spoofing by adding
{{ method_field('PATCH') }}
in your form and change the form method to POST
{{ Form::model($user, ['method'=>'POST', 'action'=>['testing#update', $user->id]]) }}
add the id as an hidden field
{{ Form::hidden('id', $user->id) }}
access the id in the controller as
public function update(Request $Request)
{
$id = Input::get('id');
$user = T_collaborateurs_table::find($id);
$user->update(Request::all());
return redirect("index");
}
also need to modify your route accordingly
Route::patch("update", "testing#update");
Try using on function update:
return redirect()->route('index');
Edit3: Could a reason be because both controllers are leading to the same page?
Edit2: Still not working after the answers I got.
Edit: Error one is solved, now I'm getting:
Undefined variable: project (View:
/var/www/resources/views/pages/showProject.blade.php)
Can this be because both variables are leading to the same page? The projects variable was working perfectly before the comment system.
public function index()
{
$projects = Project::all();
return view('pages.projects', compact('projects'));
}
Project variable declare.
I'm trying to get my comments from my database to show on a specific 'project page' in the laravel 5 project I'm working on. The idea is that the user can add art projects and other users can comment on them, but whenever I try to visit the page I get
Undefined variable: comments (View:
/var/www/resources/views/pages/showProject.blade.php)
This is my controller
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
public function store()
{
$input = Request::all();
$comment = new Comment;
$comment->body = $input['body'];
$comment->project_id = $input['project_id'];
$comment->user_id = Auth::user()->id;
$comment->save();
return redirect('projects/'.$input['project_id']);
}
These are my routes
// add comment
Route::post('projects/{id}','CommentController#store');
// show comments
Route::post('projects/{id}','CommentController#index');
And my view
#if (Auth::check())
<article> <!--Add comment -->
<br/>
{!! Form::open() !!}
{!! form::text('body', null, ['class' => 'form-control']) !!}
<br/>
{!! Form::Submit('Post Comment', ['class' => 'btn btn-primary form-control']) !!}
{!! Form::hidden('project_id', $project->id) !!}
{!! Form::close() !!}
<br/>
</article>
<article>
#foreach ($comments as $comment)
<article>
<p>Body: {{ $comment->body }}</p>
<p>Author: {{ $comment->user->name }}</p>
</article>
#endforeach
</article>
#else
<p>Please log in to comment</p>
#endif
The Model
class Comment extends Model
{
//comments table in database
protected $guarded = [];
// user who has commented
public function author()
{
return $this->belongsTo('App\User','user_id');
}
// returns post of any comment
public function post()
{
return $this->belongsTo('App\Project','project_id');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
public $timestamps = false;
}
Is there any way I can solve this?
Thanks in advance
First, you need to make sure that you are aliasing your 'Comment' model in your controller. This is done with the use statement.
use App\Comment;
class CommentController extends Controller
{
public function index()
{
$comments = Comment::all();
return view('pages.showProject', compact('comments'));
}
}
Second, you will need to change your route for showing comments from a POST request to a GET request. At the moment you are making identical routes and furthermore GET is the correct request type for retrieving data.
Route::get('projects/{id}','CommentController#index');
Third, you are referencing a $project variable in your view, but never passing it in from the controller. That needs to reference something.
I think your relationship is wrong. Try this:
Comment model:
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
}
User model:
class User extends Model
{
public function comments()
{
return $this->hasMany('App\Comment');
}
}
In the view you can use:
#foreach($comments as $comment)
<p>{{ $comment->user->name }}</p>
#endforeach
I needed to empty the show in the commentsController and only use it for saving the comments. For showing them I made an extra function in my projectsController. It ended up being this;
public function show($id)
{
$project = Project::findOrFail($id)->load("User");
$input = Request::all();
//-----------------------DB-----------------------------//
$project_comments = DB::table('comments')
->select('body', 'name')
->where('project_id', '=', $id)
->join('users', 'users.id', '=', 'user_id')
->get();
//-----------------------DB-----------------------------//
return view('pages.showProject', ['project' => Project::findOrFail($id), 'comments' => $project_comments]);
}