Laravel: Accessing Path Function in Model in Index File - laravel

I have set up the following function in my model:
public function path() {
return route('news.show', ['id' => $this->id, 'slug' => $this->slug]);
}
I would now like to access that function in my index.blade.php file -- like this:
#foreach ($articles as $article)
<a href="{{ $article->path() }}">
// rest of code goes here
</a>
#endforeach
But when I try this, I get the following error:
Facade\Ignition\Exceptions\ViewException
Missing required parameters for [Route: news.show] [URI: news/{id}/{slug}]. (View: C:\laragon\www\startup-reporter\resources\views\news\index.blade.php)
Here is what my routes (web.php) looks like:
Route::get('news', 'NewsController#index')->name('news.index');
Route::get('news/create', 'NewsController#create')->name('news.create');
Route::get('news/{id}/{slug}', 'NewsController#show')->name('news.show');
Route::get('news/{id}/edit', 'NewsController#edit')->name('news.edit');
Route::post('news', 'NewsController#store')->name('news.store');
Route::put('news/{id}', 'NewsController#update');
And here is my controller:
// Index
public function index() {
$news = News::latest()->get();
return view('news.index', ['articles' => $news]);
}
// Show
public function show(News $id) {
return view('news.show', compact('id'));
}
Any idea why this is not working and what I need to do to get this to work?
Thanks.

In your routes file you have defined 2 parameters, {id} and {slug}.
But in your controller you have only accepted 1 parameter, $id.
You should amend your show controller method like this:
// Show
public function show(News $id, $slug) {
return view('news.show', compact('id'));
}

Related

Missing required parameters for [Route: listele] [URI: {language}/{slug}]

Missing required parameters for [Route: listele] [URI: {language}/{slug}] [Missing parameters: language, slug]. (View: C:\xampp\htdocs\efsane\resources\views\product\product.blade.php)
What is the reason I am getting such an error?
Blade file
#foreach ($categories as $p)
{{$p->name}}
#endforeach
Route
Route::group(['prefix' => '{language}' ], function(){
Route::get('/{slug}' , 'App\Http\Controllers\ProductController#category')->name('listele');
});
My Controller
public function category($slug)
{
$category = Category::where('slug' , $slug )->first();
$data['category'] = $category;
$data['categories'] = Category::inRandomOrder()->get();
$data['posts'] = Post::where('category_id' , $category->id)->orderBy('id', 'DESC')->paginate(10);
return view('product.kategorilist' , $data );
}
You will need to put the route paramter values in an array and put that array in your route method route('listele', [app()->getLocale(), $p->slug]).
You will also need to access the category slug from the object so you have to use $p->slug.
#foreach ($categories as $p)
<a href="{{route('listele', [app()->getLocale(), $p->slug])}}"
class="list-group-item">{{$p->name}}</a>
#endforeach
--EDIT
There was also the </a> endtag missing
--EDIT2
Your controller method defines only the $slug parameter. But you are defining a prefix in your route for the $language parameter and the route itself defines the $slug parameter.
You have to simply add another parameter called $language to your controller method.
public function category($language, $slug) { .... }
In your case the language value was assigned to the slug variable and therefore no categroy was found (null is set). If you want to access an attribute of a null object you have a problem.
I would add a check to ensure $category is not null.
public function category($language, $slug) {
$category = Category::where('slug' , $slug )->first();
if(is_null($category)){
return redirect()->back();
}
....
}

Method Illuminate\Database\Eloquent\Collection::links does not exist

I created a model relationship between User and Message. I want to implement a list of messages for the authenticated user but I get the following error.
Method Illuminate\Database\Eloquent\Collection::links does not exist
Controller
public function index()
{
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $user->message);
}
Message provider
class message extends Model
{
public function user() {
return $this->belongsTo('App\User');
}
}
User provider
public function message ()
{
return $this->hasMany('App\Message');
}
index.blade.php
#extends('layouts.app')
#section('content')
<h1>messages</h1>
#if(count($messages)>0)
#foreach ($messages as $message)
<div class="well">
<h3>{{$message->user}}</h3>
<small>Written on {{$message->created_at}} </small>
</div>
#endforeach
{{$messages->links()}}
#else
<p> no post found </p>
#endif
#endsection
Error
"Method Illuminate\Database\Eloquent\Collection::links does not exist.(View: C:\xampp\htdocs\basicwebsite\resources\views\message\index.blade.php)"
Check your view blade, that method (links()) only could be used when your data model is implementing paginate() method.
If you dont use paginate(), remove this part:
{{$messages->links() }}
If you are trying to paginate your data when it gets to the view then you need to add the paginate in your controller before passing the data to the view. Example
return $users = Users::select('id','name')->paginate(10);
with that paginate method in your controller, you can call the links method to paginate your object in view as shown below
{{$users->links()}}
hope it helps you
There are 2 ways to resolve this issue:
Either use paginate function while searching data from database:
$users = DB::table('users')->where('id',$user_id)->paginate(1);
Remove links() function from index.blade.php
{{ $messages->links() }}
Remove {{ $messages->links() }} to in your index.blade.php because {{ $messages->links() }} is supported only when you use paginate
You can do something like this in your controller file.
public function index()
{
$messages = Message::all()->paginate(5);
$user_id = auth()->user()->id;
$user = User::find($user_id);
return view('message.index')->with('messages', $messages, $user->message);
}

Trying to get property 'post_titile' of non-object

This is My Controller.
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
//dd($page);
return view('web_views.index',['page' => $page]);
}
This is my view page
<h4>{{$page->post_titile}}</h4>
It's better to use Route-Model Binding I think.
Your route (if you are using resource route, it's already done):
Route::get('posts/{post}', 'PostController#show); // domain.tld/posts/1
Your method should look like this:
public function show(Post $post)
{
return view('web_views.index',compact('post'));
}
In your view:
<h4>{{ $post->post_titile }}</h4>
May be $posts->id you are passing, has no result in database so you need to check it by using if-statement
public function show(Posts $posts)
{
$page = Posts::find($posts->id);
if($page == null){
$page = ['post_title' => 'Not Available'];
}
return view('web_views.index',['page' => $page]);
}
I believe this error is because of not finding data for an ID into database. So if as per above script will pass the fetched data to view otherwise it will push an item into $page array.

laravel send parameter in route

Is thier anyway to do somethins like this ,
in web.php
Route::get('/test', 'testController#test');
in test Controller
public function test ($url)
{
//while $url store test in route
}
I know only if I send parameter I have to use
Route::get('/{test}', 'testController#test');
UPDATE
I want to do something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
in my controller
public function test ($url)
{
while $url store test,test2in route
}
LASTEST UPDATE
I dont want to use {url}
I want to make /test = $url when I enter to url/test
In my web.php I use this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
The reason that I want to do something like this because I want to make 1 function that alll route can use In my controller I do this .
public function test($url,$preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id',$url)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
I dont want todo something like this
Route::get('/test', 'testController#test');
Route::get('/test2', 'testController#test');
and In controller
public function test($preview=null)
{
//$url shoud be test or test 2
try {
$test = (isset($preview)) ? test::where('test.id','test)->first()
} catch (\Exception $e) {
return redirect('notfound');
}
}
You need to combine both elements
Route::get('/test/{url}', 'testController#test');
want to make /test = $url
You can't, but you can have /test?foo=$url instead. So you keep your route like
Route::get('/test', 'testController#test');
Then add Request $request as controller method argument (and you remove $url)
public function test(Request $request) {
...
Finally you obtain your url with
$url = $request->input('foo');
Your Route
Route::post('/test', 'testController#test')->name('test);
If you use blade.
<a href="{{ route('test') }}"
onclick="event.preventDefault();
document.getElementById('test_id').submit();">
Test Click
</a>
{!! Form::open(['url' => route('test'), 'method' => 'post', 'id' => 'test_id']) !!}
<input type="hidden" name="url" value="{{ $url}}">
{!! Form::close() !!}
In your controller.
public function test(Request $request)
{
$data = $request->all();
$url = $data['url'];
//do something with your url...
}

laravel 7 article argument not passed title in articles view

I am trying to make a single page of website but i cant passed argument article in view
my controller is:
public function single(Article $article)
{
$article->increment('viewCount');
$comments = $article->comments()->where('approved' , 1)->where('parent_id', 0)->latest()->with(['comments' => function($query) {$query->where('approved' , 1)->latest();}])->get();
return view('Home.articles.single' , compact('article' , 'comments'));
}
and my view is
<div class="subject_head">
<div class="subject_head--title"><h1 class="title">
{{$article->title}}
</h1>
</div>
</div>
but i cant passed article title. and my model is
protected $table='articles';
protected $casts= [
'images'=>'array'
];
protected $fillable= ['title','slug','description','body','images','tags'];
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function user()
{
return $this->belongsTo(User::class);
}
i passed this and while used
$article->all()
this passed all data
but when use
$article->title
this method is null
and when use
dd($article)
It has been changed.
Now you need to pass it as array ['name' => 'James']
in your case
public function single(Article $article)
{
$article->increment('viewCount');
$comments = $article->comments()->where('approved' , 1)->where('parent_id', 0)->latest()->with(['comments' => function($query) {$query->where('approved' , 1)->latest();}])->get();
return view('Home.articles.single' ,['article'=>$article,'comments'=$comments]));
}
Check it here : https://laravel.com/docs/7.x/views
i changed Route of
Route::get('/articles/{articleSlug}' , 'ArticleController#single');
Route::get('/series/{courseSlug}' , 'CourseController#single');
to
Route::get('/articles/{article:Slug}' , 'ArticleController#single');
Route::get('/series/{course:Slug}' , 'CourseController#single');
and solved problem.
thank you of all.

Resources