EDIT:
I am using Laravel 4 PHP and initially I thought this problem was related to the 'link_to_route' method on a webpage so you can simply link to another webpage that does not contain any dynamic data.
However, I am discovering that the order you list your Routes will ultimately determine if your routes are successfully reached or not.
Authors2.php (Controller)
class Authors2_Controller extends BaseController {
public $restful = true;
public function contact() {
return View::make('authors2.index')
->with('title','Authors and Books')
->with('authors2', Author2::orderBy('name')->get());
}
public function getnew() {
return View::make('authors2.new')
->with('title', 'Add New Author');
}
Routes.php
Route::get('authors2', array('as'=>'authors2', 'uses' =>'Authors2_Controller#contact'));
Route::get('authors2/new', array('as'=>'new_author', 'uses'=>'Authors2_Controller#getnew'));
index.blade.php (view)
#extends('layouts.default')
#section('content')
<h1>Authors2 Home Page </h1>
<ul>
#foreach($authors2 as $author2)
<li>{{ link_to_route('author2', $author2->name, $parameters = array($author2->id)) }}</li>
#endforeach
</ul>
<p>{{ link_to_route('new_author', 'Add Author') }} </p>
#endsection
When I click on the 'Add Author' link, I get the error 'Trying to get property of non-object' error.
EDIT:
So now when I change the order of the routing where if I list the 'authors2/new' route BEFORE the 'authors2' route, the route will actually work:
Route::get('authors2/new', array('as'=>'new_author', 'uses'=>'Authors2_Controller#getnew'));
Route::get('authors2', array('as'=>'authors2', 'uses' =>'Authors2_Controller#contact'));
Does this have to deal with how Routes are first received and if so, why does this happen?
As mentioned by #Barry_127, Laravel will match routes based from most specific to least specific. So its good practice to list your routes in that order.
Related
Scenario
What i try to do
I am creating a multicolumn user index page, where the right column shows details from the user selected in the left column.
When selected, the user is not pulled out of the collection but freshly out of the database, so the data is up to date.
I defer the loading of the user list using the described method in the livewire documentation.
The user has a 'roles' relationship, which is displayed in the list column.
What I'd expect
I would expect that once the $this→users is set as a collection of the users and a user is selected, only the query will fire for getting the data for this user.
What actually happens
When a user is selected, a query for getting all users from the database is run (again), and because of the fact that the roles from the user are displayed in the list view, for each user, a new query is executed.
After that, a query for getting the selected user is executed. Afterwards another query for getting the roles of the user is fired to.
So my questions
Why does Livewire lose the relations that were eager loaded in the first declaration of public $users?
Why is it that Livewire reruns the query for getting all users, while the public $users is already defined as a collection of users?
Files:
UserListDetail.php
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Livewire\Component;
class UsersListDetail extends Component {
public string $search = '';
public $users;
public $selectedUser;
public int $timesRun = 0;
public bool $readyToLoadUserList = false;
protected $queryString = [
'search' => [ 'except' => '' ],
];
// Defer loading users
public function readyToLoadUserList()
{
// Get all users with roles relationship
$this->users = User::with('roles')->get();
$this->readyToLoadUserList = true;
}
public function selectUser(int $userId)
{
$this->selectedUser = User::with('roles')->find($userId);
}
public function render()
{
return view('livewire.users-list-detail', [
'selectedUser' => $this->selectedUser,
]
);
}
}
simplified version of user-list-detail.blade.php
<div>
<div wire:init="readyToLoadUserList">
#if($readyToLoadUserList)
<ul>
#foreach($users as $user)
<li wire:click="selectUser({{ $user->id }})">
{{ $user→name_first }} {{ $user→name_last }},
#foreach($user→roles as $role)
{{ $role→label }},
#endforeach
</li>
#endforeach
</ul>
#endif
</div>
<div>
#isset($selectedUser)
{{ $name_first
#endisset
</div>
</div>
When selectUser() method is triggered, the livewire will re-render the blade and since wire:init="readyToLoadUserList" is there, it will load every user (again).
Replce readyToLoadUserList() with mount() and simply keep wire:init="" empty.
Also, condition with #if($users->count() > 0)
I'm developing a personal blog but I can't get the browser to show me what I have in a function which has yet to show me a single post, however I can manage to view a list of all the posts, I can view just 5 (latest) which appear on the main, homepage.
Now I'm going for the part where you click on the title and everything about this post should be displayed. I inspected the code on the part where I'm having the issues and the part where the foreach is isn't being rendered to the browser, maybe I'm not doing something correct on the blade part?
PostsController.php
public function show(Post $slug)
{
$post = Post::find($slug);
return view('posts.show', ['posts' => $post]);
}
Posts/show.blade.php
#extends('layouts.app')
#section('showpost')
<div>
#foreach ($posts as $post)
<h1> {{ $post->title }} </h1>
<p> {{ $post->body }} </p>
#endforeach
</div>
#endsection
web.php
Route::get('/posts/{post}', 'PostsController#show');
Just to show you how I'm referencing the template that shows just one post.
#foreach ($posts as $post)
<li>
<a href="/posts/{{ $post->slug }}">
<h1> {{ $post->title }} </h1>
</a>
<p> {{ $post->slug }} </p>
</li>
#endforeach
Post::find is used to retrieve a model by its primary key which is in most cases named id. Heir in your case you are passing $slug as an argument, and as It's is supposed to render only a single item with a given slug you should use Post::where('slug', $slug)->first() this will only return one item and you won't have to use a foreach loop in the show.blade.php template.
Another problem is here
public function show(Post $slug) {
$post = Post::find($slug);
return view('posts.show', ['posts' => $post]);
}
You are using Route Model Binding which will automatically set the parameter $slug of the function show equal to the record in the posts table which has the id which is passed in the URL request. No need to perform Post::find($slug)
for example, if the request URL is http://localhost:8000/posts/1 here the id is 1 so the parameter $slug will be populated with the record which has id==1 unless you have Customizing The Key like this
Define in the App\Models\Post::class a method call
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug';
}
With this definition, the post item which will be retrieved when performing Route model biding will be based on the value of the slug column within a posts table.
You can learn more about at Route Model Biding
In order to implement the Route Model Binding completely, you need to specify it in 3 places, routes.php, PostsController.php and override it on the model, Post.php:
Pass the desired target inside the get request method and place it inside the wildcard, this is next to where you specify the controller and which function to use inside of the controller.
From this: Route::get('/posts/{post}', 'PostsController#show');
To this: Route::get('/posts/{slug}', 'PostsController#show');
Override the target (from id to "whatever") using the getRouteKeyModel function, this is just like #Yves Kipondo had provided
/**
* Get the route key for the model.
*
* #return string
*/
public function getRouteKeyName()
{
return 'slug';
}
Tweak the show function inside the PostsController, passing the Model's name and the target so the query is completed. All of this inside the parameter of the function. And since your'e overriding the use of the id, you no longer have to specify it inside Eloquent query to the database.
So, instead of this:
public function show(Post $slug)
{
$post = Post::find($slug);
return view('posts.show', ['posts' => $post]);
}
Change it to this:
public function show(Post $slug)
{
return view('posts.show', ['post' => $slug]);
}
I have some posts on my index page, and each post has an edit button on it.
The problem is, I want the URL to be hungarian, but every time I change the function's name from edit to sth. else it gives me 404 error.
I show the posts with the following code:
#foreach($posts as $post)
<div class="card p-3">
<h3>{{$post->title}}</h3>
<small>Feltöltve: {{$post->created_at}}</small>
<h3>Szerkesztés</h3> I TRY TO CHANGE /EDIT TO STH. ELSE HERE
</div>
#endforeach
And here is my posts controller with the edit function:
public function edit($id) { I change edit here as well
$post = Post::find($id);
return view('elado.szerkeszt')->with('post', $post);
}
In web.php, I've
Route::resource('elado', 'PostsController');
Because you're using resource() method in your route declaration. Which will use by default there routes and control methods
[
'create',
'store',
'show',
'edit',
'update',
'destroy',
]
If you want to change the method name, declare the route on your own
Route::post('/change', 'PostsController#change');
you can exclude edit method from resource routes with except method like, then define new route with your custom edit method and put before resources routes:
Route::post('/elado/{id}', 'PostsController#sth');
Route::resource('elado', 'PostsController')->except([
'edit'
]);
As a project I am building a stackoverflow like forum. On the page on which a single question is shown I want the user to be able to click on the questioner's name and be forwarded to the respective user profile page. I am able to get the name from the database with {{ $question->user->name }}. The problem occurs when adding the part!
Also, the profile pages work. I can access them and the url then says for example: ../profile/1.
This is the route in the web.php file:
Route::get('/profile/{user}', 'PageController#profile')->name('profile');
This is the PageController part:
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile')->with('user', $user);
}
This is the code from the show.blade View question page which does not work:
<p>
Submitted by {{ $question->user->name }}
</p>
The error message I get is Undefined variable: user.
Which surprises me because forwarding on the profile page to a specific question works with this blade code:
View Question
The respective route in the web.php file:
Route::resource('questions', 'QuestionController');
And QuestionController:
public function show($id)
{
$question = Question::findOrFail($id);
return view('questions.show')->with('question', $question);
}
I thought I defined the variable $user in the PageController like I defined $question in the QuestionController?
I can see you are using Eloquent models with relations. If you want to display the user id on the question, you can use the relation between the Question and User to find the id of the posting user.
Submitted by {{ $question->user->name }}
^^^^^^^^^
//just change your like this way
public function profile($id)
{
$user = User::with(['questions', 'answers', 'answers.question'])->find($id);
return view('profile',compact('user));
}
I am sort of new to the Laravel framework and I am building just a simple blog. I can create a blog, show a blog and show a overview of all blogs. Now I would like to delete a blog. So, I have created a delete button in my view with a route link which will pass also the id of the article. Then, in my routes file I specify a delete request and a controller method. In the method I find the id and try to delete the row with the id I specified in the route/view.
This doesn't work. Instead of activate the destroy/delete method it shows the article instead of deleting it and activates the show method instead of the delete method. Can somebody help me out, What do I wrong?
View.blade.php
<a href="{{route('nieuws.destroy', ['id' => $blog->id])}}" onclick="return confirm('Weet je dit zeker?')">
<i class="fa fa-trash"></i>
</a>
Route
Route::group(['middleware' => 'auth'], function () {
Route::get('/aanvragen', 'aanvragenController#index')->name('aanvragen.index');
Route::get('/logout' , 'Auth\LoginController#logout')->name('logout');
Route::get('/nieuws/toevoegen', 'blogController#create')->name('blogs.add');
Route::post('/nieuws/store', 'blogController#store')->name('nieuws.store');
Route::delete('/nieuws/{id}', 'blogController#destroy')->name('nieuws.destroy');
});
Route::get('/nieuws', 'blogController#index')->name('blogs.index');
Route::get('/nieuws/{blog}', 'blogController#show')->name('blogs.show');
Controller methods
Delete/Destroy
public function destroy($id) {
$blog = Blog::find($id);
$blog->delete();
return redirect('/nieuws');
}
Show
public function show(Blog $blog) {
dd('show');
return view('blogs.show', compact('blog'));
}
A delete() route requires you to POST your data.
HTML forms only supports GET and POST, other methods like DELETE, PUT, etc are not supported, that's why Laravel uses the _method to spoof methods which are not supported by HTML forms.
You do not want use GET in these cases, since someone can send a user the url (http://yoursite.com/blog/delete/1) in an IM or via email. The user clicks and the blog is gone.
Define your route as it would be when using resource controllers, so:
Route::delete('/nieuws/{id}', 'blogController#destroy')->name('nieuws.destroy');
And either use a form with the delete method:
// apply some inline form styles
<form method="POST" action="{{ route('nieuws.destroy', [$blog->id]) }}">
{{ csrf_field() }}
{{ method_field('DELETE') }}
<button type="submit">Delete</button>
</form>
Or do some javascript magic as the link SR_ posted in his comment on your OP.
One more thing, add some sort of validation in your destroy action. Right now when you provide a non-existing id or something else, you will get a 500 error, instead you want to have a 404.
public function destroy($id)
{
$blog = Blog::findOrFail($id);
$blog->delete();
return redirect('/nieuws');
}
I think you need to update your destroy function like:
public function destroy($id) {
$blog = DB::table('blog')->where('id',$id)->delete();
return redirect('/nieuws');
}
And update your view code like:
<a href="{{route('nieuws.destroy', [$blog->id])}}" onclick="return confirm('Weet je dit zeker?')">
<i class="fa fa-trash"></i>
</a>
Hope this work for you!
I'm also new to Laravel but I made it work through this way:
(I use 'Article' as the model's name and the resource "method" in the route stands for a bunch of useful routes including the route you wrote)
Controller:
public function destroy($id){
Article::find($id)->delete();
//$article = Article::find($id);
return redirect()->back()->withErrors('Successfully deleted!');
}
Route:
Route::resource('article','ArticleController');
However, I think the problem lies in the default definition of database's name of your model. Laravel will assume that you have a database named blogs since you have a model named "blog". Are you having the database's name right?
To use DELETE HTTP Verb, your form should consists of the POST method and settings the method_field('DELETE')
Example:
<form method="POST" action="{{ route('xxx.destroy', $xxx->id) }}">
{{ csrf_field }}
{{ method_field('DELETE') }}
</form>