1

I have a problem when I learning laravel. My views include master.blade.php and top.blade.php file. In master.blade.php, I used @include('top') command to get content show UI. But now I don't know how to get and passing database to top.blade.php. I was used direct App\Article; to do this. can anyone help me? thanks.

Master.blade.php file

@include('top')

Top.blade.php file

<?php 
use App\Article;
$articles = Article::orderBy(DB::raw('RAND()'))->take(1)->get();
 ?>
@foreach ($articles as $a)
{{ $a->title }}
@endforeach
1

2 Answers 2

2

You could do this:

<?php 
$articles = \App\Article::orderBy(DB::raw('RAND()'))->take(1)->get();
?>

But it's better to keep data logic in a model or a controller and pass it to the views.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks @Mezenin. if my top.blade.php appearing in all pages, then what do I do?
@Dung, this should work in all views which include top.blade.php
Is there a better way to handle laravel?
1

Juste use a Controller to pass database data in to your view, it should be

ArticlesController.php

$articles = Article::orderBy(DB::raw('RAND()'))->take(1)->get();
return view('master', compact('articles');

It's just an example, but now top.blade.php which is included in master, will contain $articles.

1 Comment

Thanks @Dumas. follow you, I must to call view top.blade.php in all controller to show top.blade.php in all page.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.