View is not getting anything from the controller - laravel

Can anyone tell me why this will not return show.blade.php data?
ROUTE
Route::resource('news', 'NewsController', ['except' => ['create', 'store', 'edit', 'update', 'destroy']]);
MODEL
public function categories()
{
return $this->belongsToMany(ContentCategory::class);
}
public function tags()
{
return $this->belongsToMany(ContentTag::class);
}
CONTROLLER
public function show(News $news)
{
$news->load('categories', 'tags', 'product_press_releases', 'section');
return view('site.news.show', compact('news'));
}
VIEW show.blade.php
#section('content')
{{ $news->title ?? '' }}
{{ $news->id ?? '' }}
#foreach($news->categories as $key => $category)
<span class="label label-info">{{ $category->name }}</span>
#endforeach
#endcontent
For the life of me I cannot get why no data is being returned. I do these all the time and never ran into this.

I believe that your are not extending it to app.blade.php.
Add - #extends('YOUR_APP_LINK').
In your case -
#extends('YOUR_APP_LINK')
#section('content')
{{ $news->title ?? '' }}
{{ $news->id ?? '' }}
#foreach($news->categories as $key => $category)
<span class="label label-info">{{ $category->name }}</span>
#endforeach
#endcontent
Hope this will help you.

Related

Call to a member function load() on null

Can someone tell me what to do in this error.
The error is in this line. 'posts' => $author->posts->load('category', 'author')
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->posts->load('category', 'author'),
]);
});
this is my controller
class PostController extends Controller
{
public function index()
{
return view('frontend.posts', [
"title" => "All Posts",
// "posts" => Post::all()
"posts" => Post::latest()->get()
]);
}
public function show(Post $post)
{
return view('frontend.post', [
"title" => "Single Post",
"post" => $post
]);
}
}
this is my models
class Post extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $with = ['category', 'author'];
public function category(){
return $this->belongsTo(Category::class);
}
public function author(){
return $this->belongsTo(User::class, 'user_id');
}
}
and this is my user models
class User extends Authenticatable
{
use HasApiTokens;
use HasFactory;
use HasProfilePhoto;
use Notifiable;
use TwoFactorAuthenticatable;
public function post(){
return $this->hasMany(Post::class);
}
}
I have this previous error to "foreach() argument must be of type array|object, null given".
I want to display blog posts from certain users.
This is the code from posts.blade.php.
#foreach ($posts as $post)
<div class="p-t-32">
<h4 class="p-b-15">
<a href="/posts/{{ $post->slug }}"
class="ltext-108 cl2 hov-cl1 trans-04">
{{ $post->title }}
</a>
</h4>
<p class="stext-117 cl6">
{{ $post->excerpt }}
</p>
<div class="flex-w flex-sb-m p-t-18">
<span class="flex-w flex-m stext-111 cl2 p-r-30 m-tb-10">
<span>
<span class="cl4">By</span> <a class="stext-111 cl2 hov-cl1 trans-04" href="/authors/{{ $post->author->username }}">{{ $post->author->name }}</a>
<span class="cl12 m-l-4 m-r-6">|</span>
</span>
<span>
<a class="stext-111 cl2 hov-cl1 trans-04" href="/categories/{{ $post->category->slug }}">{{ $post->category->name }}</a>
<span class="cl12 m-l-4 m-r-6">|</span>
</span>
<span>
8 Comments
</span>
</span>
<a href="/posts/{{ $post->slug }}" class="stext-101 cl2 hov-cl1 trans-04 m-tb-10">
Continue Reading
<i class="fa fa-long-arrow-right m-l-9"></i>
</a>
</div>
</div>
#endforeach
The name of the relationship in User is post but in your controller you used posts.
The following should probably work:
Route::get('/authors/{author:username}', function(User $author){
return view('frontend.posts', [
'title' => 'Post By Author : $author->name',
'posts' => $author->load('post.category'),
]);
});

How to display specific data from array?

How can I correct display data from array. I guess it's a foreach loop, but I do not know how to bite it. I just need only header. It's in table calendars.
Thanks so much!
#foreach($list as $item)
{{ $item->header }}
#endforeach
I tried the above code but throws out an error, unknown value "header"
#foreach($results as $type => $list)
<div class="single-contact-information mb-30">
<h3>{{ $type }} </h3>
{{ $list }}
</div>
#endforeach
[{"id":1,"header":"test","description":"<p>test<\/p>","date":"2020-12-12"}]
Edit:
SearchController:
public function search(Request $request)
{
$search = $request->get('search');
$results = [];
$results['calendars'] = DB::table('calendars')->where('header', 'like', '%'.$search.'%')->get();
return view('pages.search', ['results' => $results]);
}
You should try this:
[{"id":1,"header":"test","description":"<p>test<\/p>","date":"2020-12-12"}]
Above value is json then use below code
$list = [{"id":1,"header":"test","description":"<p>test<\/p>","date":"2020-12-12"}];
#foreach($list as $item)
{{ $item['header'] }}
#endforeach
$list = json_decode($list);
#foreach($list as $item)
{{ $item['header'] }}
#endforeach
Updated Answer
#foreach(json_decode($list) as $item)
{{ $item->header }}
#endforeach
try this one
used json_decode function here
#foreach(json_decode($list) as $item)
{{ $item['header'] }}
#endforeach

Update Data in Laravel

This is my code :
Route:
Route::get('/editposts/{id}', function ($id) {
$showpost = Posts::where('id', $id)->get();
return view('editposts', compact('showpost'));
});
Route::post('/editposts', array('uses'=>'PostController#Update'));
Controller :
public function Update($id)
{
$Posts = Posts::find($id);
$Posts->Title = 10;
$Posts->Content = 10;
$Posts->save();
//return Redirect()->back(); Input::get('Title')
}
and View:
#foreach($showpost as $showpost)
<h1>Edit Posts :</h1>
{{ Form::open(array('url'=>'editposts', 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{ Form::submit('Update') }}
{{ Form::close() }}
#endforeach
but when I want to Update my data i receive an error :
http://localhost:8000/editposts/1
Missing argument 1 for App\Http\Controllers\PostController::Update()
You need to change route:
Route::post('editposts/{id}', 'PostController#Update');
Then the form to:
{{ Form::open(['url' => 'editposts/' . $showpost->id, 'method'=>'post']) }}
Change your post route to:
Route::post('/editposts/{id}', 'PostController#Update');
Done!
Correct the route,specify a parameter
Route::post('editposts/{id}', 'PostController#Update');
Pass the post'id as paramater
{{ Form::open(array('url'=>'editposts/'.$post->id, 'method'=>'post')) }}
Title : {{ Form::text('Title', $showpost->Title) }} <br> Content : {{ Form::text('Content', $showpost->Content ) }} <br> {{
Form::submit('Update') }}
{{ Form::close() }}
Notice $post->id
First declare your route:
Route::post('/editposts/{id}', array('uses'=>'PostController#Update'));
Then update your form url:
{{ Form::open(['url' => url()->action('PostController#Update', [ "id" => $showpost->id ]), 'method'=>'post']) }}
This is assuming your model's id column is id
(Optional) You can also use implicit model binding :
public function Update(Posts $id) {
//No need to find it Laravel will do that
$id->Title = 10;
$id->Content = 10;
$id->save();
}

Laravel 4 :: custom validation error message is not displaying?

I'm trying to create an online form and to display my own error messages. But for some reason it's not working correctly. Here's my controller code, CategoryController.php:
class CategoryController extends BaseController
{
public function add()
{
return View::make('admin');
}
public function validate_add()
{
$rules = array('category_name' => 'Required|Alpha|Min:4');
$messages = array('category_name.Required' =>'Please enter the category name');
$input = Input::all();
$validator = Validator::make($input, $rules, $messages);
if ($validator->fails())
{
return Redirect::to('admin')->withErrors($validator)->withInput(Input::all());
}
else
{
echo '<h1>WOW! your are are awesome!!! <3<h1> ';
}
}
}
And the admin.blade.php is following:
#extends('common')
#section('body')
<h1>Add Category</h1>
{{ HTML ::ul($errors->all(), array('class'=>'errors')) }}
{{ Form::open(array( 'url'=>'admin', $title="Admin Control Panel")) }}
<p>
{{ Form::label('Category Name:') }}
{{ Form::text('category_name', Input::old('category_name')) }}
</p>
<p>
{{Form::label('Parent Category') }}
{{ Form::select('Network', array('0' => 'Maincategory')) }}
</p>
<p>
{{ Form::submit('Submit') }}
</p>
{{ Form::close() }}
#stop
Interesting - I tried this on my local Laravel project and it looks like although you can specify your rules in mixed case, you need to specify the custom messages in lower case.
So if you changed your rules and your message override to; 'required' instead of 'Required' etc., it should work.

HasMany relationship old input

I have a model Category. Category has many Localization. When I store Category, I have these inputs:
{{ Form::text('title[en]', Input::old('title')) }}
{{ Form::text('title[ru]', Input::old('title')) }}
Which I store like this in my controler:
// Gett all inputs
$inputs = Input::all();
// Create resource
$item = Category::create([]);
// Create localization
foreach(Input::get('title') as $locale => $title)
{
$locale = new Localization(['locale' => $locale, 'title' => $title]);
$locale = $item->localization()->save($locale);
}
That works great but what is the best practise for updating such relationships? Currently I'm trying that with Form::model binding.
#foreach($locales as $key => $locale)
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#endforeach
I have no idea how Input::old could work in this situation, so now I'm using $model->translate($locale)->title to get the correct value. Basically the updating/validation part doesn't really work. What you could suggest to change to validate such relationship and update it?
Today I found a working solution storing/updating relationships with validation. I hope it's the best/simplest way to do that. I created a new array with inputs for validation and changed in the view errors accordingly.
This is my update controller.
public function update($id)
{
// Find resource
$item = Category::find($id);
foreach(Input::get('title') as $locale => $title)
{
$v['title_'.$locale] = $title;
}
// Attempt validation
if($item->validate($v))
{
foreach(Input::get('title') as $locale => $title)
{
$localization = $item->translate($locale);
$localization->title = $title;
$localization->save();
}
return Redirect::action('AdminCategoryController#edit', [$item->id]);
}
else
{
// Failure, get errors
$errors = $item->errors();
return Redirect::back()
->withInput()
->with('errors', $errors);
}
}
And this is the update view;
{{ Form::model($model, ['action' => ['AdminCategoryController#update', $model->id], 'method' => 'PUT']) }}
#foreach($locales as $key => $locale)
<div id="{{ $locale }}">
<div class="form-group">
{{ Form::label('title['.$locale.']', _('admin.title_'.$locale)) }}
{{ Form::text('title['.$locale.']', $model->translate($locale)->title, ['class' => 'form-control']) }}
#if($errors->has('title_'.$locale))
<div class="help-block alert alert-danger">{{ $errors->first('title_'.$locale) }}</div>
#endif
</div>
</div>
#endforeach
{{ Form::close() }}
This way you can easily CRUD, validate all types of relationships (input arrays) in Laravel.

Resources