Laravel: scope search by date - php

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.

Related

Laravel 8 error 404 page not found , I wonder where did I do wrong here?

At the most basic of understanding, I've been trying to match the route and the form action. I think that I am doing it right but I wonder why does the error keeps on showing ? I may have missed something anywhere but I just really couldn't find it. Please help. In a very tight schedule, I need to complete this project by tuesday
P.S : when i submit the form it goes to this address http://127.0.0.1:8000/profile/edit/1 .
Form
<x-layout>
<x-setting heading="Edit Staff Profile">
<div class="flex flex-col">
<form method="POST" action="/profile/edit/{{$profil->id}}" enctype="multipart/form-data">
#csrf
<div class="mb-6">
<label class="block mb-2 uppercase font-bold text-sm text-gray-700" for="images">
Profile photo
</label>
<input type="file" name="images">
</div>
Route
Route::get('profile', [UserController::class, 'index'])->middleware('auth')->name('profile');
Route::get('profile/edit/{id}', [UserController::class, 'show'])->middleware('auth');
Route::post('profile/edit/{id}', [UserController::class, 'update'])->middleware('auth');
UserController
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Profile;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
public function index()
{
$id = Auth::user()->id;
$info = User::where('id', $id)->first();
return view('profile', compact('info'));
}
// public function create()
// {
// return view('staffrecord.create');
// }
public function store()
{
$attributes = request()->validate([
'name' => 'required|max:255',
'username' => 'required|min:3|max:255|unique:users,username',
'email' => 'required|email|max:255|unique:users,email',
'password' => 'required|min:7|max:255',
]);
if (auth()->attempt($attributes)) {
return redirect('/')->with('success', 'Your account has been created.');
}
return redirect('/profile')->with('errors', 'Authentication failed.');
}
public function show($id)
{
$profil = User::findOrFail($id);
return view('staffrecord.edit', compact('profil'));
}
public function edit()
{
$id = Auth::user()->id;
$profil = Profile::findOrFail($id);
return view('staffrecord.edit', compact('profil'));
}
public function update(Request $request, $id)
{
$data = Profile::findOrFail($id);
$data->staff_id = $request->staff_id;
$data->name = $request->name;
$data->gender = $request->gender;
$data->address = $request->address;
$data->email = $request->email;
$data->phonenumber = $request->phonenumber;
$data->department = $request->department;
$data->save();
return redirect('/')->route('profile');
}
}
A user may has his logins but they may not have setup their profiles so when you do such request profile find will fail and return to 404 error.
Also to make a note ALWAYS use foreign keys in Profile table linking to user id it's not necessary that a user->id say 1 will have profile->id 1.
in User model add this function:
public function profile() {
return $this->hasOne('App\Models\Profile');
}
Then load user profile in update function of controller like:
public function update(Request $request, $id){
$user = User::with('profile')->findOrFail($id);
if (is_null($user->profile){ echo 'user don't has profile'; }
//Update profile from within
$user->profile()->updateOrCreate([$request->all()]);
//NOTE request->all is not safe
}
use updateOrCreate() for in case user does not have a profile.
I always name my routes:
Route::post('profile/edit/{id}', [UserController::class, 'update'])->name('user.update')-> middleware('auth')
Then form action looks like this:
<form method="POST" action="{{route('user.update', ['id' =>$profil->id]) }}"
This way 'id' defined in route will be easier to be identified.
Naming routes and using route() may save you some headaches when moving to production.

parameter passed to relationship from controller to model in laravel but not working

in my controller parameter passed to posts function in user model with construct method .
class MyController extends Controller
{
private $user;
public function __construct(User $getuser)
{
$this->user = $getuser;
}
public function index($id = 2)
{
$posts = $this->user->posts($id);
$user = User::FindOrFail($id);
return $user->posts;
}
}
in my user model parameter accessed and passed to relationship .
class User extends Authenticatable
{
use Notifiable;
protected $fillable = [
'name', 'email', 'password',
];
function posts($id)
{
return $this->hasMany('App\Post')->where('id',$id);
}
}
it works when use like this
"return $this->hasMany('App\Post')->where('id',1);"
but not working with passed parameter. getting this error
"Symfony\Component\Debug\Exception\FatalThrowableError Too few
arguments to function App\User::posts(), 0 passed in
C:\xampp\htdocs\blog\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasAttributes.php
on line 415 and exactly 1 expected"
Check your controller method you should be returning. ie: return $posts instead of return $user->posts as this is seeking to find posts without passing in the id as you do with $posts = $this->user->posts($id);
That's why you are getting a symphony error of too few arguments as you pass no arguments in return $user->posts
User Model
function posts($id)
{
return $this->hasMany('App\Post');
}
You could access the post with the given condition by using where on the relation method.
Querying relations
https://laravel.com/docs/7.x/eloquent-relationships#querying-relations
$post = $user->posts()->where('id', $id)->first();
You could use get() or first() according to your requirement.
$posts = $user->posts()->where('id', $id)->get();
If you want a user who has a post that satisfies the criteria.
$user = User::whereHas('posts', function($query) use($id){
$query->where('id', $id);
// You may add several other conditions as well.
})
->with(['posts' => function($query) use($id){
$query->where('id', $id);
}
])
->first();
Now,
$user->posts
will give a collection of only ONE post Model Instance that satisfied the condition

Laravel route throws NotFoundHttpException

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');

Call to a member function follow() on integer

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.

Laravel 5.1 - Showing Comments on Specific Page

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]);
}

Categories