how can i use auth value into v-if condition in vue - laravel

i want to use the Auth variable in vue. but its not running
my code in vue is this. This code is possible?
<template lang="html">
<div class="chat-message" v-if="message.user_from == '<?php echo
Auth::user()->id; ?>'">
<div class="chatright">
{{message.user_from}} {{message.msg}}
</div>
</div>
<div class="chatleft" v-else>
{{message.user_from}} {{message.msg}}
</div>
</template>

<script> var user_is = <?php echo Auth::user()->id; ?></script>
then put the variable in condition finally that work

Try using Vuex it fits for your case or you can use the localStorage to persist the userId, otherwise you can't do this :
message.user_from == '<?php echo Auth::user()->id; ?>
Because you are trying to initialize user_from within the template, You should do it within the script tag

You can attach it to the root document of the HTML or you can pass the user as a prop to that Vue component.
Note: If you pass it in vue the HTML document object, you need to understand not to send any sensitive information of course.
In your you master page in the head section, add this:
<script>
window.App = {!! json_encode(
'user' => Auth::user(),
'signedIn'=>Auth::check(),
]) !!};
</script>
And in your component, you can reach it the normal way: App.user.something.
Or you can pass it as a prop if you send a $user object.
<your-compoenent :user="{{$user}}"></your-component>
Hope this hep you.

Related

Pass variable from blade to blade

I'm new to uusing Laravel blade templating.
I have a bootstrap modal that I need to show on button click, also, I need to pass some values on that click event.
For example.
On my parent blade: (btw, its a nested modal blade)
modal_1.blade.php
<div class="modal" id="modal1">
...
#foreach($templates as $key => $val)
<button onclick="previewItem($templates[$key]['color'])">
</button>
#endforeach
</div>
<script>
const previewItem = (color) => {
// how to pass this `color` to the child modal blade
}
</script>
and the child blade modal
modal_2.blade.php
<div class="modal" id="modal2">
// how to access passed variable from modal1 ?
</div>
you can create a component and inject here your variables:
#component('components.updateMyUserModal' , ['modal_id' => $account->id , 'modal_title' => $account->title , 'modal_body' => $aContext, ] )
#endcomponent
one file needs to be inside the other, after that, you need to use cookie, to store the variable's value in the previous modal, when you click on the button to select the value, make by javascript a cookie that saves this value and on the next blade you recover that value and uses.
How to use:
https://www.w3schools.com/js/js_cookies.asp

How to make alert with SweetAlert in Laravel

I would like to use SweetAlert to display my data.
I did my function
public function registration()
{
Gate::authorize('admin-level');
$url = URL::signedRoute(
'register',
now()->addMinutes(20));
return redirect('users')->with('success','$url');
}
and route that goes with it
Route::get('registration', [App\Http\Controllers\UserController::class, 'registration'])->name('registration');
The problem is with message, since I downloaded SweetAlert with composer I should probably got everything working, but then when I try to execute my class with button threw the route:
<button type="button" class="btn btn-outline-primary">{{ __('Registration link') }}</button>
#if(session('succes_message'))
<div class= "alert alert-succes">
{{session('succes_message')}}
</div>
#endif
Nothing pops up(when it should)
What might be wrong with it?
When you use ->with() it means, store items in the session for the next request.
return redirect('users')->with('success', '$url');
Here comes the question. What do you do after this?
Create a notification information or an alert (popup with SweetAlert)?
If it will be used as a notification, your code has no problem. If you want to make alert (popup with SweetAlert), your understanding is wrong.
Just because the class you are using uses the name alert, doesn't mean it make an alert with SweetAlert.
To use SweetAlert, you can add JavaScript in the header or before the </body> tag:
<script>
#if($message = session('succes_message'))
swal("{{ $message }}");
#endif
</script>
Or to use SweetAlert2 :
<script>
#if($message = session('succes_message'))
Swal.fire(
'Good job!',
'{{ $message }}',
'success'
)
#endif
</script>
If you are confused about placing the script in a specific blade view, please read my answer here.

Using data on dispatched event and trigger div

I have a component that dispatches a browser event with an object
// Livewire Component Method
public function passToDashboard($dataId)
{
$data = Model::find($dataId);
$this->dispatchBrowserEvent('show-data', ['data' => $data]);
}
Now on my dashboard blade view i've got
<div class="some-classes" x-data="{dataDisplay:false}">
<div x-show="dataDisplay">
{{-- This is where i want to use the object --}}
{{ $data->title }}
</div>
</div>
<script>
window.addEventListener('show-data', data => {
console.log(data.detail.title); // outputs title just fine
})
</script>
The question is, how to 'unhide' the dataDisplay and how to show it with the passed data? Thanks!
You can listen for these events directly on the element using #event-name.window="dataDisplay = true"
To get the event data, you use the $event variable and it should be under $event.detail.data.title
Use x-text to get the text onto the element. See my full example below.
So in your case:
<div class="some-classes" x-data="{dataDisplay:false, title: ''}" #event-data.window="dataDisplay = true; title = $event.detail.data.title">
<div x-show="dataDisplay">
<h3 x-text="title"></h3>
</div>
</div>
The documentation for this can be found here: https://laravel-livewire.com/docs/2.x/events#browser
Do notice I changed the event name, because it does apparently not work if you start the event name with "show". When I changed to "event-data" or anything else it started working again.

Pass data from blade to vue component

I'm trying to learn vue and with that I want to integrate it with laravel too..
I simply want to send the user id from blade to vue component so I can perform a put request there.
Let's say I have this in blade:
<example></example>
How can I send Auth::user()->id into this component and use it.
I kept searching for this but couldn't find an answer that will make this clear.
Thanks!
To pass down data to your components you can use props. Find more info about props over here. This is also a good source for defining those props.
You can do something like:
<example :userId="{{ Auth::user()->id }}"></example>
OR
<example v-bind:userId="{{ Auth::user()->id }}"></example>
And then in your Example.vue file you have to define your prop. Then you can access it by this.userId.
Like :
<script>
export default {
props: ['userId'],
mounted () {
// Do something useful with the data in the template
console.dir(this.userId)
}
}
</script>
If you are serving files through Laravel
Then here is the trick that you can apply.
In Your app.blade.php
#if(auth()->check())
<script>
window.User = {!! auth()->user() !!}
</script>
#endif
Now you can access User Object which available globally
Hope this helps.
Calling component,
<example :user-id="{{ Auth::user()->id }}"></example>
In component,
<script>
export default {
props: ['userId'],
mounted () {
console.log(userId)
}
}
</script>
Note - When adding value to prop userId you need to use user-id instead of using camel case.
https://laravel.com/docs/8.x/blade#blade-and-javascript-frameworks
Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the #json Blade directive. The #json directive accepts the same arguments as PHP's json_encode function. By default, the #json directive calls the json_encode function with the JSON_HEX_TAG, JSON_HEX_APOS, JSON_HEX_AMP, and JSON_HEX_QUOT flags:
<script>
var app = #json($array);
var app = #json($array, JSON_PRETTY_PRINT);
</script>
Just to add for those who still get error.
For me this <askquestionmodal :product="{{ $item->title }}"></askquestionmodal> still gives error in console and instead showing html page I saw white screen.
[Vue warn]: Error compiling template:
invalid expression: Unexpected identifier in
Coupling to connect 2 rods М14 CF-10
Raw expression: :product="Coupling to connect 2 rods М14 CF-10"
Though in error I can see that $item->title is replaced with its value.
So then I tried to do like that <askquestionmodal :product="'{{ $item->title }}'"></askquestionmodal>
And I have fully working code.
/components/askquestionmodal.vue
<template>
<div class="modal-body">
<p>{{ product }}</p>
</div>
</template>
<script>
export default {
name: "AskQuestionModal",
props: ['product'],
mounted() {
console.log('AskQuestionModal component mounted.')
}
}
</script>

laravel 4 how to show result at the same page and how to solve circle invoke

I am totally new to laravel, I am now want to use laravel 4.
Suppose I have a page A.php, and it contains a form & a submit button. After I submit the post request to B.php, and in B.php I query data from database.
My question is I want to show my result on B.php , that it is to say the same page of A.php request, how do I write in routes.php.
My code:
master.blade.php
<!DOCTYPE HTML>
<html>
<head>
<metacharset="UTF-8">
<title>course query</title>
</head>
<body>
<div class="container">
#yield('container')
</div>
<h1 class="ret">The result is:
#yield('ret')
<input id="result" type="text"/>
</h1>
</body>
</html>
A.php
#extends('course.master')
#section('container')
<h1>My Courses</h1>
{{Form::open(array('url' => 'csOp'))}}
{{Form::label('course', 'Your course')}}
{{Form::text('course')}}
{{Form::submit('Submit')}}
{{Form::close()}}
#endsection
routes.php
Route::get('course', function(){
return View::make('course.B');
});
Route::post('csOp', function(){
// do something
//$inputCourse = Input::get('course');
//$records = Courses::where('name', '=', $inputCourse)->get();
// how do I return
//return View::make('csOp', $records);
});
As you can see, in A.php I have a form and request to csOp
Form::open(array('url' => 'csOp')
csOp is B.php, and in B.php I query data from db, and now I got the results,
but how can I put result to the page (B.php) itself? That it is to say I want to put the result to
<input id="result" type="text"/>
You know in jquery is easy, how do I use it in laravel 4 ?
And if return to csOp, absolutlly will get an error, it is in a circle. So how can I solve it ?
Thanks very much.
If you want to populate a form based on model contents, i,e. populate form using database data.
So in laravel you can use Form Model Binding. To do so, use the Form::model method. so in your case
Route::post('csOp', function(){
// do something
$inputCourse = Input::get('course');
$records = Courses::where('name', '=', $inputCourse)->get();
// how do I return
return View::make('csOp')->with('records',$records);
});
And your csOp.blade.php
#extends('course.master')
#section('container')
<h1>My Courses</h1>
{{Form::model($records,array('url' => 'csOp'))}}
{{Form::label('course', 'Your course')}}
{{Form::text('course')}}
{{Form::close()}}
#endsection
Now, when you generate a form element, like a text input, the model's value matching the field's name will automatically be set as the field value. So, for example, for a text input named course, the Courses model's course attribute would be set as the value.

Resources