laravel 7 article argument not passed title in articles view - laravel

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.

Related

How to re-render a table with Livewire after an event emitted from another component

I'm new to Livewire and I am stuck with this problem.
I've created a table.blade.php component with livewire, and another searchbar.blade.php component, which is not a child of the table component. Every time a search for a term, the table should rerender with the seached parameter.
All is right, and the search query gives the correct result (clients with pagination), but somehow the table does not rerender the html.
Any ideas what I'm doing wrong? Thanks
<div>
<input type="text" wire:model="query" autofocus>
</div>
class SearchBar extends Component
{
public $query;
public function updatedQuery()
{
$this->emit('searchForQuotes', $this->query);
}
public function render()
{
return view('livewire.clients.searchbar');
}
}
<div>
<table>
<tbody>
#foreach($clients as $client)
#livewire('clients.row', ['client' => $client], key($client->id))
#endforeach
</tbody>
</table>
</div>
class Table extends Component
{
use WithPagination;
public $query;
protected $listeners = [
'searchForQuotes' => 'render'
];
public function mount()
{
$this->resetData();
}
public function resetData()
{
$this->query = null;
}
public function render($query = null)
{
$q = Client::query();
if ($query) {
$q->whereRaw("CONCAT(surname, ' ', name) LIKE '%" . $query . "%'");
}
$clients = $q->latest()->paginate(20);
return view('livewire.clients.inc.table', [
'clients' => $clients, 'query' => $query
]);
}
}
You can make your child components reactive by making your key() unique every render of the parent:
#livewire('clients.row', ['client' => $client], key($client->id . "-" . Str::random()))
By adding a Str::random(), the key is different every time the parent updates, which forces the children to update as well. This also works with now(), but only as long as you have a prefix. It is important to note that this causes more requests and thus can make your table slower.
Try something like this :
class Table extends Component
{
use WithPagination;
public $query;
protected $listeners = ['searchForQuotes'];
public function mount()
{
$this->resetData();
}
public function searchForQuotes($query)
{
$this->query = $query;
// Do something
$this->render();
}
public function resetData()
{
$this->query = null;
}
public function render()
{
$q = Client::query();
if ($this->query) {
$q->whereRaw("CONCAT(surname, ' ', name) LIKE '%" . $query . "%'");
}
$clients = $q->latest()->paginate(20);
return view('livewire.clients.inc.table', [
'clients' => $clients, 'query' => $this->query
]);
}
}
I think I found the problem, but don't know how to solve it.
I the table.blade.php component I've got this code.
#foreach($clients as $client)
#livewire('clients.row', ['client' => $client], key($client->id))
#endforeach
It seems like the nested component are not rendering after firing the event.

Laravel: Accessing Path Function in Model in Index File

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

ErrorException thrown with message "Trying to get property 'user' of non-object

I am using relationship in my laravel project. I am trying to show my post and replies. But i keep getting this error. I've tried various solution but none of them worked. Can anyone help me?
Post model:
protected $fillable = [
'title', 'content', 'category_id' , 'slug', 'user_id',
];
public function user1()
{
return $this->belongsTo('App\User');
}
public function replies()
{
return $this->hasMany('App\Reply');
}
Reply model:
protected $fillable = ['content','user_id','posts_id'];
public function post(){
return $this->belongsTo('App\Post');
}
public function user()
{
return $this->belongsTo('App\User');
}
PostController:
public function shro($slug)
{
$pst= Post::where('slug',$slug)->first();
return view('posts.show')->with('p', $pst);
}
show.blade.php
<div class="panel panel-default">
<div class="panel-heading">
<img src="/uploads/avatars/{{ $p->user->avatar }}" alt="" width="70px" height="60px">
<span>{{ $p->user->name }}, <b>{{ $p->created_at->diffForHumans() }}</b></span></br>
</div>
$p, or $pst (confusing variable names) is null, and this is because ->first() can return null. Do you have a Post record in your database that matched slug?
Rule of thumb; never assume something exists.
Add some logic to ensure the Post exists before trying to access a property of it:
$post = Post::where("slug", $slug)->first();
if(!$post){
abort(404);
}
return view('posts.show')->with('post', $post);
// OR
$post = Post::where("slug", $slug)->findOrFail(); // or firstOrFail();
return view('posts.show')->with('post', $post);
Also, check your $post->user:
#if($post->user)
<img src="/uploads/avatars/{{ $post->user->avatar }}" width="70px" height="60px"/>
<span>{{ $post->user->name }}, <b>{{ $post->created_at->diffForHumans() }}</b></span></br>
#endif
If $post->user returns null, you'll have a similar error.
You can eager load the user with it's relative post at once by doing :
//...
$pst= Post::where('slug',$slug)->with(['user1'])->first();
//...

Laravel Crinsane/LaravelShoppingcart associate() doesn't work

In my Laravel I'm using this shoppingcart .
When I add one product to my shopping cart I want to have associate() with App\Product Model .
This is my code :
public function store(Request $request)
{
// store product information to Cart
Cart::add($request->id, $request->name, 1, $request->price)
->associate('App\Product');
return redirect(route('cart.index'))
->with('success_message', 'محصول با موفقیت به سبد اضافه شد');
}
But when I want to access model $item->model->id in view I get this error :
Trying to get property 'id' of non-object (View: C:\xampp\htdocs\digikala\resources\views\cart.blade.php)
Edit :
my cart view (cart.blade.php) codes :
<table border="1" class="table">
#foreach (Cart::content() as $item)
{{ $item->model->id }}
#endforeach
</table>
Finally i could solve this problem .
Everything was about $request data inside store() method .
Mistakes were in the form of adding product to cart .
I did not post the product ID correctly to the store() method .
If anyone had this problem in the future I hope to test $request first by this code :
public function store(Request $request)
{
return $request;
}
public function store(Request $request)
{
//verify the submitted product
$product = Product::where('slug', $request->input('slug'))->first();
//check if item is available
if($product === null){
return redirect()->route('cart.index')->with('error', 'Unable to add product to cart');
}
else{
Cart::add($product->id, $product->title, 1, $product->price)
->associate('App\Product');
return redirect()->route('cart.index')->with('success', 'Product added to cart');
}
return false;
}

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.

Resources