Laravel 4 route NOT passing in a username - model-view-controller

Hi, I have been trying to solve this issue for hours how, researched Stack Overflow and many other websites, but no luck.
//-------Route
Route::get('/profile/{firstName}', array(
'as' => 'userProfile',
'uses' => 'ProfileController#user'
));
//--------Controller
class ProfileController extends BaseController {
public function user($firstName) {
$user = User::where('firstName', '=', $firstName);
if($user->count()) {
//First record return from the query
$user = $user->first();
return View::make('profile.user')
->with('user', $user);
}
return "sorry, 404";
//return App::abort(404);
}
}
Finally link:
<li> My Profile </li>
------------------------------
*If I put the username into the URL manually, it works, however when I clicked on the link I get localhost:8000/profile/{firstName} with "sorry, 404"
Thank you for the help!!!

Your route userProfile requires the parameter firstName so you have to pass that in when generating the url:
{{ URL::route('userProfile', Auth::user()->firstName) }}
(How you get the firstName in the view doesn't matter I just used Auth::user since I thought this might be your use case)

Related

Laravel 5.1, passing my ID

I'm trying to pass an ID of a past and insert it into another database.
I got a page with shows posts like this
/posts/{id}
. From there on i want to add a comment section, so i got my form set up like this:
<form method="POST" action="/posts/{{ $post->id }}/comments">
(When i inspect the code, it inserts the right id and the "{{ $posts->id }}" spot.
inside my routes.php i got the folling route:
Route::post('/posts/{post}/comments', 'CommentsController#store');
and inside CommentsController.php i got the following
public function store(Post $post)
{
Comment::create([
'body' => request('body'),
'post_id' => $post->id
]);
return back();
}
When ever i try to add a comment i get this error:
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'post_id'
cannot be null
When i change my code from CommentsController.php to this:
'post_id' => "2"
it works fine (but the comment will always be added at post with ID 2)
I can't seem to find out why my id wont go trough.
Anny help with this?
Try this
public function store(Request $request, Post $post)
{
$comment= new Comment;
$comment->body = $request->body;
$comment->post_id = $post->id;
$comment->save();
return back();
}
The route model binding allows you to convert the Post ID passed into the route into the actual post object in the controller method. It may even work smoother if you use a relationship between a post and a comment, like so:
public function store(Request $request, Post $post)
{
$post->comments->create([
'body' => $request->body
]);
return back();
}
Inside post model
public function comments()
{
return $this->hasMany('App\Comment','post_id');
}

Laravel 5.5 - Show specific category from API response

I am returning an API response inside a Categories controller in Laravel 5.5 like this...
public function get(Request $request) {
$categories = Category::all();
return Response::json(array(
'error' => false,
'categories_data' => $categories,
));
}
Now I am trying to also have the option to return a specific category, how can I do this as I am already using the get request in this controller?
Do I need to create a new route or can I modify this one to return a specific category only if an ID is supplied, if not then it returns all?
Better case is to create a new route, but you can also change the current one to retrieve all models if the parameter is not supplied. You first gotta choose which approach you will be using. For splitting it into multiple calls you can see Resource controllers and for using one method you can follow Optional Route Parameters
It will be much cleaner if you will create another route. For example
/categories --> That you have
/categories/{id} -> this you need to create
And then add method at same controller
public function show($id) {
$categories = Category::find($id);
return Response::json(array(
'error' => false,
'categories_data' => $categories,
));
}
But if you still want to do it at one route you can try something like this:
/categories -> will list all categories
/categories?id=2 -> will give you category of ID 2
Try this:
public function get(Request $request) {
$id = $request->get('id');
$categories = $id ? Category::find($id) : Category::all();
return Response::json(array(
'error' => false,
'categories_data' => $categories,
));
}

Laravel 5 - insert multiple users

I have a simple User - Department relationship. My User Model has the following
public function department() {
return $this->belongsTo('App\Department', 'departmentId');
}
And my Department Model has
public function user() {
return $this->hasMany('App\User');
}
At the moment I am working with the departments side of things. My index function looks like the following
public function index() {
$departments = Helper::returnDepartmentsFromLdap();
return view('departments.index', compact('departments'));
}
What it basically does it gets all the departments from LDap (Active Directory) and displays them. On the index page for departments, I have
{!! link_to_route('departments.updateDepartments', 'Update Database', null, array('class' => 'btn btn-info')) !!}
So the database can be updated if new departments are added to our server. I do not have a create function as it is not needed.
Anyways, at the moment, my routes are like so
Route::model('departments', 'Department');
Route::bind('departments', function($value, $route) {
return App\Department::whereId($value)->first();
});
Route::resource('departments', 'DepartmentsController', ['except' => ['show', 'edit', 'create', 'delete', 'update', 'destroy']]);
Route::post('departments/updateDepartments', array('as' => 'departments.updateDepartments', 'uses' => 'DepartmentsController#updateDepartments'));
And in my updateDepartments function I am simply doing the following for now
public function updateDepartments()
{
dd("TEST");
}
If I click on the button on my index page to update the database, which should trigger the above, I am seeing a MethodNotAllowedHttpException.
Am I missing something obvious here?
try to use get:
because you can only pass data using get method with link link_to_route
Route::get('departments/updateDepartments', array('as' => 'departments.updateDepartments', 'uses' => 'DepartmentsController#updateDepartments'));
Route::post('departments/updateDepartments', ...) means you only allow POST requests on that route. Make sure the form method is POST instead of GET (default) on your index page

Pass value to URL - REST style

<h1>Edit page of {{ $user->username }}</h1>
{{ Form::open(['route' => 'user.store']) }}
... the rest of the view
This is in my login view. The related code in the store method in the controller looks like this:
if (Auth::attempt(Input::only('username', 'password'))) {
$user = Auth::user();
return Redirect::route('user.show', ['user' => $user]);
}
and the show method:
public function show($user)
{
return View::make('user.edit', ['user' => $user]);
}
And I get .../user/%7Buser%7D as URL (and I want it to be, eg. .../user/exampleusername) and also an exception: ErrorException: Trying to get property of non-object.
When I dd($user) in the show method (or in the view, doesn't matter), I get simply string[6] {user}, which means I do not pass the $user successfully to the user.show route.
The official docs give this example: return Redirect::route('profile', array('user' => 1)); which seems relevant to my case, which I think should look like this in my code: return Redirect::route('user.show', ['user' => $user]);?
Funny, though, if in the show method I try to take the user object from the session (Auth::user()), and dump it, as here:
public function show($user)
{
$user = Auth::user();
dd($user);
...
it will still be NULL, but if I dump it in the index method:
public function index()
{
if (Auth::check()) {
dd(Auth::user());
...
, then it returns correct object, full of parameters and values... I have no idea what's going on and why in one method I have the session object, but in the other I don't.
Any suggestions on how to go around this problem?
UPDATE: I narrowed it down to this implementation in the store method:
return Redirect::route('user.show')->with('user', $user);
and in the show method:
$user = Session::get('user');
return View::make('user.edit', ['user' => $user]);
Because apparently the only place where you can pass an array that will explode into single variables is in View::make, whereas in Redirect::to, Redirect::action and Redirect::route, etc., you must use the ->with('key', $value) function. Those values then will be available in the Session singleton.
Nevertheless, I still get .../%7Buser%7D in the URL. And I don't know how to get out of this...
You need to pass the id of the user to the user.show route - not the $user itself.
return Redirect::route('user.show', [$user->id]);

Laravel 4 Framework - Query scope not working

Im a big 'ol newbie at Laravel, and im trying to do a query scope but it doesnt seem to be working, i keep getting this error
Argument 1 passed to Letters::scopeForUser() must be an instance of User
My user IS logged in, but it still doesnt seem to be working.
This is my Letters model
<?php
class Letters extends Eloquent {
protected $table = 'letters';
public function scopeForUser(User $u)
{
return $query->where('userid', '=', $u->id);
}
}
and in my controller i have the following
Route::get('myletters', array(
'before' => 'auth|userdetail',
function()
{
// Grab the letters, if any, for this user
$letters = Letters::forUser(Auth::user())->get();
$data = [
'letters' => $letters
];
return View::make('myletters', $data);
}
));
Any help would be greatly appreciated.
Cheers
You should pass a variable $query as the first argument to your method in the Model. For example:
public function scopeForUser($query, User $u)
{
return $query->where('userid', '=', $u->id);
}
The first argument doesn't necessarily need to be $query, but it should be the same variable that you are using inside the scope method ($query in this case).

Resources